import { createRef } from 'react' import { describe, expect, it, vi } from 'vitest' import { act, fireEvent, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { SessionGoalRead } from '@opencode-manager/shared/opencode' import type { SessionPermissionModeState, SessionSandboxState } from '@opencode-manager/shared/schemas' import type { PromptInputHandle } from './PromptInput' import { createCommandActionsMock } from '@/test/test-utils' import { makeAgent, promptTextarea, renderPromptInput, type PromptInputFixture } from '@/test/promptInput' const SESSION_ID = 'test-session' const basePermissionState: SessionPermissionModeState = { sessionId: SESSION_ID, rootSessionId: SESSION_ID, mode: 'ask', lockedReason: null, } const baseSandboxState: SessionSandboxState = { sessionId: SESSION_ID, rootSessionId: SESSION_ID, sandboxed: false, source: 'default', resources: null, effectiveResources: { cpus: 2, memoryMib: 4096 }, lockedReason: null, available: true, } const idleGoal: SessionGoalRead = { supported: true, goal: null } const openGoal: SessionGoalRead = { supported: true, goal: { id: 'goal_1', objective: 'Ship the feature', status: 'active', rounds: 1, maxRounds: 50, boot: 'boot_1', updatedAt: 1, }, } interface ConfigFixture extends PromptInputFixture { permission?: Partial sandbox?: Partial } function withPermission(overrides: Partial = {}): SessionPermissionModeState { return { ...basePermissionState, ...overrides } } function withSandbox(overrides: Partial = {}): SessionSandboxState { return { ...baseSandboxState, ...overrides } } async function renderConfig(mobile: boolean, fixture: ConfigFixture = {}) { const user = userEvent.setup() const { permission, sandbox, ...rest } = fixture const result = await renderPromptInput({ mobile, goal: idleGoal, permissionMode: withPermission(permission), sandbox: withSandbox(sandbox), ...rest, }) return { ...result, user } } function configTrigger() { return screen.findByRole('button', { name: /^Session config/ }) } async function openConfig(user: ReturnType) { await user.click(await configTrigger()) } describe.each([ ['desktop', false], ['mobile', true], ] as const)('Session config (%s)', (label, mobile) => { it('does not mark the trigger active when no session toggle is on', async () => { const { user } = await renderConfig(mobile) const trigger = await configTrigger() expect(trigger).not.toHaveAttribute('data-active') if (mobile) expect(trigger).not.toHaveClass('bg-highlight') await openConfig(user) expect(await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })).toHaveAttribute('aria-checked', 'false') }) it.each([ ['permissions accept everything', { permission: { mode: 'auto' } }], ['commands are sandboxed', { sandbox: { sandboxed: true } }], ] satisfies Array<[string, ConfigFixture]>)('marks the trigger active while %s', async (_case, fixture) => { await renderConfig(mobile, fixture) const trigger = await configTrigger() expect(trigger).toHaveAttribute('data-active', 'true') if (mobile) expect(trigger).toHaveClass('bg-highlight') }) it('marks the trigger active while goal mode is armed', async () => { const { user } = await renderConfig(mobile) await openConfig(user) await user.click(await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ })) const activeTriggers = document.querySelectorAll('button[data-active="true"]') expect(activeTriggers).toHaveLength(1) if (mobile) expect(activeTriggers[0]).toHaveClass('bg-highlight') }) it('switches permissions to accept everything', async () => { const { user, fetchFake } = await renderConfig(mobile) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ }) await user.click(item) await waitFor(() => expect(fetchFake.lastRequest('PUT', `/api/session-permission-modes/${SESSION_ID}`)?.body).toMatchObject({ directory: '/test', mode: 'auto', }), ) }) it('offers permission and goal controls on a remote server without sandbox controls', async () => { const { user } = await renderConfig(mobile, { serverId: 'srv_remote' }) await openConfig(user) expect(await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })).toBeInTheDocument() expect(screen.getByRole('menuitemcheckbox', { name: /Goal mode/ })).toBeInTheDocument() expect(screen.queryByRole('menuitemcheckbox', { name: /Sandbox commands/ })).not.toBeInTheDocument() }) it('shows why permissions cannot be changed', async () => { const { user } = await renderConfig(mobile, { permission: { lockedReason: 'child' } }) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ }) expect(item).toHaveAttribute('aria-disabled', 'true') expect(item).toHaveTextContent('Inherited from parent session') }) it('disables permission changes and skips the write while the mode read is pending', async () => { const { user, fetchFake } = await renderConfig(mobile, { permissionModeRead: () => new Promise(() => {}), }) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ }) expect(item).toHaveAttribute('aria-disabled', 'true') expect(item).toHaveTextContent('Permissions: loading') await user.click(item) expect(fetchFake.findRequests('PUT', `/api/session-permission-modes/${SESSION_ID}`)).toHaveLength(0) }) it('reports unavailable permissions and skips the write', async () => { const { user, fetchFake } = await renderConfig(mobile, { permissionModeRead: () => ({ status: 500, json: { error: 'boom' } }), }) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ }) expect(item).toHaveAttribute('aria-disabled', 'true') expect(item).toHaveTextContent('Permissions: unavailable') await user.click(item) expect(fetchFake.findRequests('PUT', `/api/session-permission-modes/${SESSION_ID}`)).toHaveLength(0) }) it('shows the sandbox item checked while commands are sandboxed', async () => { const { user } = await renderConfig(mobile, { sandbox: { sandboxed: true } }) await openConfig(user) expect(await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })).toHaveAttribute('aria-checked', 'true') }) it.each([ [false, 'false', { sandboxed: true }], [true, 'true', { sandboxed: false }], ] as const)('toggles sandboxing from sandboxed=%s through the sandbox endpoint', async (sandboxed, checked, expectedBody) => { const { user, fetchFake } = await renderConfig(mobile, { sandbox: { sandboxed } }) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }) expect(item).toHaveAttribute('aria-checked', checked) await user.click(item) await waitFor(() => expect(fetchFake.lastRequest('PUT', `/api/session-sandbox/${SESSION_ID}`)?.body).toEqual(expectedBody), ) }) it('hides the sandbox item when sandboxing is unavailable', async () => { const { user } = await renderConfig(mobile, { sandbox: { available: false } }) await openConfig(user) expect(screen.queryByRole('menuitemcheckbox', { name: /Sandbox commands/ })).not.toBeInTheDocument() }) it('shows why sandboxing cannot be changed', async () => { const { user } = await renderConfig(mobile, { sandbox: { sandboxed: true, lockedReason: 'child' } }) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }) expect(item).toHaveAttribute('aria-disabled', 'true') expect(item).toHaveTextContent('Inherited from parent session') expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument() }) it('keeps the trigger summary when the sandbox write is pending', async () => { const { user } = await renderConfig(mobile, { sandboxWrite: () => new Promise(() => {}), }) const triggerName = (await configTrigger()).getAttribute('aria-label') await openConfig(user) await user.click(await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })) await user.keyboard('{Escape}') expect(await configTrigger()).toHaveAttribute('aria-label', triggerName) }) it('toggles goal mode', async () => { const { user } = await renderConfig(mobile) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ }) await user.click(item) expect(item).toHaveAttribute('aria-checked', 'true') }) it('shows why goal mode is unavailable', async () => { const { user } = await renderConfig(mobile, { goal: openGoal }) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ }) expect(item).toHaveAttribute('aria-disabled', 'true') expect(item).toHaveTextContent('A goal is already active for this session') }) it('opens the file picker from the attach action', async () => { const { user, container } = await renderConfig(mobile) const fileInput = container.querySelector('input[type="file"]') if (!(fileInput instanceof HTMLInputElement)) throw new Error('file input is missing') const click = vi.spyOn(fileInput, 'click').mockImplementation(() => {}) await openConfig(user) await user.click(await screen.findByRole('menuitem', { name: 'Attach image or PDF' })) expect(click).toHaveBeenCalledTimes(1) }) it('switches the agent radio and sends with the selected agent', async () => { const { user, fetchFake } = await renderConfig(mobile, { agents: [makeAgent({ id: 'build', mode: 'primary' }), makeAgent({ id: 'plan', mode: 'primary' })], }) await openConfig(user) const build = await screen.findByRole('menuitemradio', { name: /Build/ }) const plan = screen.getByRole('menuitemradio', { name: /Plan/ }) expect(build).toHaveAttribute('aria-checked', 'true') await user.click(plan) expect(plan).toHaveAttribute('aria-checked', 'true') expect(build).toHaveAttribute('aria-checked', 'false') await user.keyboard('{Escape}') fireEvent.change(promptTextarea(), { target: { value: 'hello' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(fetchFake.lastRequest('POST', `/api/opencode/api/session/${SESSION_ID}/agent`)?.body).toMatchObject({ agent: 'plan', }), ) }) it('opens the model picker from the model action', async () => { const { user } = await renderConfig(mobile) await openConfig(user) await user.click(await screen.findByRole('menuitem', { name: /Change model/ })) expect(await screen.findByRole('dialog', { name: 'Select model' })).toBeInTheDocument() }) it('omits the variant section when the model has no variants', async () => { const { user } = await renderConfig(mobile) await openConfig(user) await screen.findByRole('menuitem', { name: /Change model/ }) expect(screen.queryByRole('menuitemradio', { name: 'Default' })).not.toBeInTheDocument() }) it('saves the selected variant', async () => { const { user, fetchFake } = await renderConfig(mobile, { models: [ { id: 'claude-sonnet-4-5', providerID: 'anthropic', name: 'Claude Sonnet 4.5', variants: ['high', 'low'], }, ], }) await openConfig(user) await user.click(await screen.findByRole('menuitemradio', { name: 'high' })) await waitFor(() => expect(fetchFake.lastRequest('POST', '/api/providers/model-state')).toBeDefined()) expect(fetchFake.lastRequest('POST', '/api/providers/model-state')?.body).toMatchObject({ variant: { model: { providerID: 'anthropic', modelID: 'claude-sonnet-4-5' }, value: 'high' }, }) }) it('compacts the session from the context action', async () => { const user = userEvent.setup() const actions = createCommandActionsMock() await renderPromptInput({ mobile, goal: idleGoal, commandActions: actions }) await openConfig(user) await user.click(await screen.findByRole('menuitem', { name: /Compact session/ })) expect(actions.compact).toHaveBeenCalledWith('') }) it('keeps the surface open after a checkbox selection', async () => { const { user } = await renderConfig(mobile) await openConfig(user) const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ }) await user.click(item) expect(screen.getByRole('menuitemcheckbox', { name: /Accept all permissions/ })).toBeInTheDocument() }) it('updates the trigger summary when cycling the agent through the handle', async () => { const ref = createRef() await renderPromptInput({ mobile, goal: idleGoal, promptRef: ref, agents: [makeAgent({ id: 'build', mode: 'primary' }), makeAgent({ id: 'plan', mode: 'primary' })], }) expect((await configTrigger()).getAttribute('aria-label')).toMatch(/^Session config: Build,/) act(() => { ref.current?.cycleAgent() }) await waitFor(() => { expect(screen.getByRole('button', { name: /^Session config: Plan,/ })).toBeInTheDocument() }) }) describe('sandbox resources', () => { async function openResources(fixture: ConfigFixture) { const result = await renderConfig(mobile, { ...fixture, sandbox: { sandboxed: true, ...fixture.sandbox } }) await openConfig(result.user) const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ }) await result.user.click(item) await screen.findByRole('dialog', { name: 'Sandbox resources' }) return result } it('hides the resources item while the session is not sandboxed', async () => { const { user } = await renderConfig(mobile, { sandbox: { sandboxed: false } }) await openConfig(user) await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }) expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument() }) it('hides the resources item when sandboxing is unavailable', async () => { const { user } = await renderConfig(mobile, { sandbox: { sandboxed: true, available: false } }) await openConfig(user) expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument() }) it('shows the effective values with a custom marker when an override exists', async () => { const { user } = await renderConfig(mobile, { sandbox: { sandboxed: true, resources: { cpus: 8, memoryMib: 2048 }, effectiveResources: { cpus: 8, memoryMib: 2048 } }, }) await openConfig(user) const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ }) expect(item).toHaveTextContent('8 CPUs · 2 GiB · custom') }) it('prefills the dialog from the override', async () => { await openResources({ sandbox: { resources: { cpus: 8, memoryMib: 2048 }, effectiveResources: { cpus: 8, memoryMib: 2048 } }, }) expect(screen.getByLabelText('CPUs')).toHaveValue(8) expect(screen.getByLabelText('Memory (GiB)')).toHaveValue(2) }) it('saves the entered resources', async () => { const { fetchFake, user } = await openResources({ sandbox: { resources: null, effectiveResources: { cpus: 2, memoryMib: 4096 } }, }) const cpus = screen.getByLabelText('CPUs') await user.clear(cpus) await user.type(cpus, '4') const memory = screen.getByLabelText('Memory (GiB)') await user.clear(memory) await user.type(memory, '3') await user.click(screen.getByRole('button', { name: 'Save' })) expect(fetchFake.lastRequest('PUT', `/api/session-sandbox/${SESSION_ID}`)?.body).toMatchObject({ resources: { cpus: 4, memoryMib: 3072 }, }) }) it('clears the override with Use defaults', async () => { const { fetchFake, user } = await openResources({ sandbox: { resources: { cpus: 8, memoryMib: 2048 }, effectiveResources: { cpus: 8, memoryMib: 2048 } }, }) await user.click(screen.getByRole('button', { name: 'Use defaults' })) expect(fetchFake.lastRequest('PUT', `/api/session-sandbox/${SESSION_ID}`)?.body).toMatchObject({ resources: null }) }) it('shows the server error when saving resources fails', async () => { const { user } = await openResources({ sandbox: { resources: null, effectiveResources: { cpus: 2, memoryMib: 4096 } }, sandboxWrite: () => ({ status: 400, json: { error: 'Requested resources exceed the host' } }), }) await user.click(screen.getByRole('button', { name: 'Save' })) expect(await screen.findByRole('alert')).toHaveTextContent('Requested resources exceed the host') }) }) })