diff --git a/frontend/package.json b/frontend/package.json index 18f4b01c..4da6b232 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -21,6 +21,7 @@ "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-label": "^2.1.7", + "@radix-ui/react-popover": "^1.1.15", "@radix-ui/react-select": "^2.2.6", "@radix-ui/react-slider": "^1.3.6", "@radix-ui/react-slot": "^1.2.3", diff --git a/frontend/src/components/agent/AgentQuickSelect.tsx b/frontend/src/components/agent/AgentQuickSelect.tsx deleted file mode 100644 index 39b3c96d..00000000 --- a/frontend/src/components/agent/AgentQuickSelect.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import { useMemo } from 'react' -import { Check } from 'lucide-react' - -const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu' -import type { AgentInfo } from '@opencode-manager/shared/opencode' -import { useAgents } from '@/hooks/useOpenCode' -import { getAgentStyleVars } from '@/lib/agent-colors' -import { getPrimaryAgents } from '@/lib/primaryAgents' - -interface AgentQuickSelectProps { - directory?: string - currentAgent: string - onAgentChange: (agent: string) => void - isBashMode?: boolean -} - -type SelectableAgent = Pick - -const findAgent = (agents: SelectableAgent[], agentId: string): SelectableAgent | undefined => { - return agents.find(a => a.id.toLowerCase() === agentId.toLowerCase()) -} - -export function AgentQuickSelect({ - directory, - currentAgent, - onAgentChange, - isBashMode = false, -}: AgentQuickSelectProps) { - const { data: agents = [] } = useAgents(directory) - - const primaryAgents = useMemo(() => getPrimaryAgents(agents), [agents]) - - const handleSelect = (agentId: string) => { - onAgentChange(agentId) - } - - const currentAgentInfo = findAgent(agents, currentAgent) - const styleVars = isBashMode - ? getAgentStyleVars('plan') - : getAgentStyleVars(currentAgent, currentAgentInfo?.color) - const displayName = isBashMode ? 'Bash' : capitalize(currentAgentInfo?.name ?? currentAgent) - - const buttonContent = ( - - ) - - return ( - - - {buttonContent} - - - {primaryAgents.map((agent) => { - const apiColor = agent.color - const itemStyleVars = getAgentStyleVars(agent.id, apiColor) - const isSelected = agent.id.toLowerCase() === currentAgent.toLowerCase() - - return ( - handleSelect(agent.id)} - className="group flex items-center justify-between" - > -
- - {capitalize(agent.name)} - - {agent.description && ( - - {agent.description} - - )} -
- {isSelected && } -
- ) - })} -
-
- ) -} diff --git a/frontend/src/components/message/ComposerModelPill.tsx b/frontend/src/components/message/ComposerModelPill.tsx deleted file mode 100644 index a33ce1e3..00000000 --- a/frontend/src/components/message/ComposerModelPill.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { memo, useMemo } from 'react' -import { ModelQuickSelect } from '@/components/model/ModelQuickSelect' -import { ContextUsageMeter } from '@/components/session/ContextUsageMeter' -import { useSession } from '@/hooks/useOpenCode' -import { useContextUsage } from '@/hooks/useContextUsage' -import type { ModelSelectionSession } from '@/hooks/useModelSelection' -import { - CONTEXT_USAGE_TEXT_CLASS, - contextUsageAccessibleLabel, - contextUsageTone, - formatContextUsage, -} from '@/lib/contextUsage' -import { cn } from '@/lib/utils' - -interface ComposerModelPillProps { - directory?: string - sessionID: string - modelName: string - variant: string | null - modelSelectionSession?: ModelSelectionSession - open: boolean - onOpenChange: (open: boolean) => void - isCompacting: boolean - onCompact: () => void -} - -export const ComposerModelPill = memo(function ComposerModelPill({ - directory, - sessionID, - modelName, - variant, - modelSelectionSession, - open, - onOpenChange, - isCompacting, - onCompact, -}: ComposerModelPillProps) { - const { data: session } = useSession(sessionID, directory) - const contextUsage = useContextUsage(sessionID, directory, session?.revert?.messageID) - const pillUsage = contextUsage ? formatContextUsage(contextUsage) : null - const pillUsageTone = CONTEXT_USAGE_TEXT_CLASS[contextUsageTone(contextUsage?.usagePercentage ?? null)] - const pillLabel = [ - modelName || 'Select model', - variant ? `${variant} variant` : null, - contextUsage ? contextUsageAccessibleLabel(contextUsage) : null, - ].filter((part): part is string => part !== null).join(', ') - - const trigger = useMemo( - () => ( - - ), - [contextUsage, modelName, pillLabel, pillUsage, pillUsageTone, variant], - ) - - return ( - - {trigger} - - ) -}) diff --git a/frontend/src/components/message/ComposerToolsMenu.test.tsx b/frontend/src/components/message/ComposerToolsMenu.test.tsx deleted file mode 100644 index afef57c0..00000000 --- a/frontend/src/components/message/ComposerToolsMenu.test.tsx +++ /dev/null @@ -1,324 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { screen, waitFor } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { ComposerToolsMenu } from './ComposerToolsMenu' -import { renderWithProviders } from '@/test/render' -import { makeSettingsResponse } from '@/test/fixtures/api' -import type { FetchRoute } from '@/test/fetchFake' -import { SetSessionPermissionModeRequestSchema } from '@opencode-manager/shared/schemas' -import type { SessionPermissionModeState, SessionSandboxState } from '@opencode-manager/shared/schemas' - -const basePermissionState: SessionPermissionModeState = { - sessionId: 'ses_1', - rootSessionId: 'ses_1', - mode: 'ask', - lockedReason: null, -} - -const baseSandboxState: SessionSandboxState = { - sessionId: 'ses_1', - rootSessionId: 'ses_1', - sandboxed: false, - source: 'default', - resources: null, - effectiveResources: { cpus: 2, memoryMib: 4096 }, - lockedReason: null, - available: true, -} - -interface MenuFixture { - permission?: Partial - sandbox?: Partial - sandboxError?: { status: number, message: string } - goalArmed?: boolean - goalDisabled?: boolean - goalLabel?: string - sessionID?: string - remote?: boolean -} - -async function renderMenu(fixture: MenuFixture = {}) { - const user = userEvent.setup() - const sessionID = fixture.sessionID ?? 'ses_1' - const permissionState = { ...basePermissionState, sessionId: sessionID, rootSessionId: sessionID, ...fixture.permission } - const sandboxState = { ...baseSandboxState, sessionId: sessionID, rootSessionId: sessionID, ...fixture.sandbox } - const routes: FetchRoute[] = [ - { - method: 'GET', - path: `/api/session-permission-modes/${sessionID}`, - respond: () => ({ json: permissionState }), - }, - { - method: 'PUT', - path: `/api/session-permission-modes/${sessionID}`, - respond: (request) => { - const parsed = SetSessionPermissionModeRequestSchema.safeParse(request.body) - return { json: { ...permissionState, mode: parsed.success ? parsed.data.mode : 'ask' } } - }, - }, - { - method: 'GET', - path: `/api/session-sandbox/${sessionID}`, - respond: () => ({ json: sandboxState }), - }, - { - method: 'PUT', - path: `/api/session-sandbox/${sessionID}`, - respond: () => { - if (fixture.sandboxError) { - return { status: fixture.sandboxError.status, json: { error: fixture.sandboxError.message } } - } - return { json: sandboxState } - }, - }, - { method: 'GET', path: '/api/settings', respond: () => ({ json: makeSettingsResponse() }) }, - ] - const props = { - sessionID, - directory: '/repo', - goalArmed: fixture.goalArmed ?? false, - goalDisabled: fixture.goalDisabled ?? false, - goalLabel: fixture.goalLabel ?? 'Goal mode: the next message becomes the objective', - onToggleGoal: vi.fn(), - onAttachFile: vi.fn(), - } - const options = { auth: false, theme: false, toaster: false, fetchRoutes: routes } as const - const result = fixture.remote - ? renderWithProviders(, { ...options, serverId: 'srv_remote' }) - : renderWithProviders(, options) - const scopeSuffix = fixture.remote ? ['srv_remote'] : [] - await waitFor(() => { - expect(result.queryClient.getQueryData(['session-permission-mode', sessionID, ...scopeSuffix])).toBeDefined() - }) - if (!fixture.remote) { - await waitFor(() => expect(result.queryClient.getQueryData(['session-sandbox', sessionID])).toBeDefined()) - } - return { ...result, ...props, user, sessionID } -} - -async function openMenu(user: ReturnType) { - await user.click(await screen.findByRole('button', { name: 'Composer options' })) -} - -describe('ComposerToolsMenu', () => { - it('does not highlight the trigger when no tool is active', async () => { - const { user } = await renderMenu() - - expect(screen.getByRole('button', { name: 'Composer options' })).not.toHaveClass('bg-highlight') - await openMenu(user) - expect(await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })).toHaveAttribute('aria-checked', 'false') - }) - - it.each([ - ['permissions accept everything', { permission: { mode: 'auto' } }], - ['goal mode is armed', { goalArmed: true }], - ['commands are sandboxed', { sandbox: { sandboxed: true } }], - ] satisfies Array<[string, MenuFixture]>)('highlights the trigger while %s', async (_case, fixture) => { - await renderMenu(fixture) - - expect(screen.getByRole('button', { name: 'Composer options' })).toHaveClass('bg-highlight') - }) - - it('switches permissions to accept everything', async () => { - const { user, fetchFake, sessionID } = await renderMenu() - await openMenu(user) - - const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ }) - await user.click(item) - - expect(fetchFake.lastRequest('PUT', `/api/session-permission-modes/${sessionID}`)?.body).toMatchObject({ - directory: '/repo', - mode: 'auto', - }) - }) - - it('offers permission and goal controls on a remote server without sandbox controls', async () => { - const { user } = await renderMenu({ remote: true }) - await openMenu(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 renderMenu({ permission: { lockedReason: 'child' } }) - await openMenu(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('shows the sandbox item checked while commands are sandboxed', async () => { - const { user } = await renderMenu({ sandbox: { sandboxed: true } }) - await openMenu(user) - - expect(await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })).toHaveAttribute('aria-checked', 'true') - }) - - it('toggles sandboxing through the sandbox endpoint', async () => { - const { user, fetchFake, sessionID } = await renderMenu() - await openMenu(user) - - const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }) - expect(item).toHaveAttribute('aria-checked', 'false') - await user.click(item) - - expect(fetchFake.lastRequest('PUT', `/api/session-sandbox/${sessionID}`)?.body).toMatchObject({ sandboxed: true }) - }) - - it('hides the sandbox item when sandboxing is unavailable', async () => { - const { user } = await renderMenu({ sandbox: { available: false } }) - await openMenu(user) - - expect(screen.queryByRole('menuitemcheckbox', { name: /Sandbox commands/ })).not.toBeInTheDocument() - }) - - it('shows why sandboxing cannot be changed', async () => { - const { user } = await renderMenu({ sandbox: { lockedReason: 'child' } }) - await openMenu(user) - - const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }) - - expect(item).toHaveAttribute('aria-disabled', 'true') - expect(item).toHaveTextContent('Inherited from parent session') - }) - - it('toggles goal mode', async () => { - const { user, onToggleGoal } = await renderMenu() - await openMenu(user) - - await user.click(await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ })) - - expect(onToggleGoal).toHaveBeenCalledTimes(1) - }) - - it('shows why goal mode is unavailable', async () => { - const { user } = await renderMenu({ goalDisabled: true, goalLabel: 'A goal is already active for this session' }) - await openMenu(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', async () => { - const { user, onAttachFile } = await renderMenu() - await openMenu(user) - - await user.click(await screen.findByRole('menuitem', { name: 'Attach image or PDF' })) - - expect(onAttachFile).toHaveBeenCalledTimes(1) - }) - - it('uses the 44px control size for the trigger', async () => { - await renderMenu() - - const trigger = await screen.findByRole('button', { name: 'Composer options' }) - expect(trigger).toHaveClass('size-11', 'p-0') - expect(trigger).not.toHaveClass('p-2') - }) -}) - -describe('ComposerToolsMenu sandbox resources', () => { - async function openResources(fixture: MenuFixture) { - const result = await renderMenu({ ...fixture, sandbox: { sandboxed: true, ...fixture.sandbox } }) - await openMenu(result.user) - const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ }) - await result.user.click(item) - await screen.findByRole('dialog') - return result - } - - it('hides the resources item when the session is not sandboxed', async () => { - const { user } = await renderMenu({ sandbox: { sandboxed: false } }) - await openMenu(user) - await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }) - - expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument() - }) - - it('hides the resources item for a child session', async () => { - const { user } = await renderMenu({ sandbox: { sandboxed: true, lockedReason: 'child' } }) - await openMenu(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 renderMenu({ sandbox: { sandboxed: true, available: false } }) - await openMenu(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 renderMenu({ - sandbox: { sandboxed: true, resources: { cpus: 8, memoryMib: 2048 }, effectiveResources: { cpus: 8, memoryMib: 2048 } }, - }) - await openMenu(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('prefills the dialog from the effective values without an override', async () => { - await openResources({ sandbox: { resources: null, effectiveResources: { cpus: 2, memoryMib: 4096 } } }) - - expect(screen.getByLabelText('CPUs')).toHaveValue(2) - expect(screen.getByLabelText('Memory (GiB)')).toHaveValue(4) - }) - - it('saves the entered resources', async () => { - const { fetchFake, sessionID, 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/${sessionID}`)?.body).toMatchObject({ - resources: { cpus: 4, memoryMib: 3072 }, - }) - }) - - it('clears the override with Use defaults', async () => { - const { fetchFake, sessionID, 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/${sessionID}`)?.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 } }, - sandboxError: { status: 400, message: 'Requested resources exceed the host' }, - }) - - await user.click(screen.getByRole('button', { name: 'Save' })) - - expect(await screen.findByRole('alert')).toHaveTextContent('Requested resources exceed the host') - }) -}) diff --git a/frontend/src/components/message/ComposerToolsMenu.tsx b/frontend/src/components/message/ComposerToolsMenu.tsx deleted file mode 100644 index c9c868ad..00000000 --- a/frontend/src/components/message/ComposerToolsMenu.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { useState } from 'react' -import { Paperclip, Plus, Shield, ShieldCheck, Target } from 'lucide-react' -import { - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu' -import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button' -import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/opencode-server-context' -import { usePermissionModeToggle } from '@/hooks/usePermissionModeToggle' -import { useSandboxToggle } from '@/hooks/useSandboxToggle' -import { shouldShowSandboxResources } from '@/lib/sandboxResources' -import { cn } from '@/lib/utils' -import { SandboxMenuItems } from './SandboxMenuItems' -import { ToolMenuItemContent } from './ToolMenuItemContent' -import { SessionSandboxResourcesDialog } from './SessionSandboxResourcesDialog' - -interface ComposerToolsMenuProps { - sessionID: string - directory: string - goalArmed: boolean - goalDisabled: boolean - goalLabel: string - onToggleGoal: () => void - onAttachFile: () => void -} - -export function ComposerToolsMenu({ - sessionID, - directory, - goalArmed, - goalDisabled, - goalLabel, - onToggleGoal, - onAttachFile, -}: ComposerToolsMenuProps) { - const isLocalServer = isLocalOpenCodeServer(useOpenCodeServerId()) - const permission = usePermissionModeToggle(sessionID, directory) - const sandbox = useSandboxToggle(sessionID, { enabled: isLocalServer }) - const [resourcesOpen, setResourcesOpen] = useState(false) - - return ( - <> - - - - - - - : } - title="Accept all permissions" - detail={permission.disabled ? permission.label : undefined} - /> - - {isLocalServer && ( - setResourcesOpen(true)} /> - )} - - } - title="Goal mode" - detail={goalDisabled ? goalLabel : undefined} - /> - - - - } title="Attach image or PDF" /> - - - - {shouldShowSandboxResources(sandbox) ? ( - - ) : null} - - ) -} diff --git a/frontend/src/components/message/PromptInput.command.test.tsx b/frontend/src/components/message/PromptInput.command.test.tsx index 428b7fc1..340cabe6 100644 --- a/frontend/src/components/message/PromptInput.command.test.tsx +++ b/frontend/src/components/message/PromptInput.command.test.tsx @@ -215,17 +215,18 @@ describe('PromptInput command submission', () => { expect(screen.queryByText('The selected model has no variants')).not.toBeInTheDocument() }) - it('opens the model picker through the imperative handle while the session is active', async () => { + it('opens the config surface in the model view through the imperative handle while the session is active', async () => { const ref = createRef() await renderCommandInput({ promptRef: ref, isSessionActive: true }) - expect(screen.queryByText('Select model')).not.toBeInTheDocument() + expect(screen.queryByRole('heading', { name: 'Model' })).not.toBeInTheDocument() act(() => { ref.current?.openModelPicker() }) - expect(await screen.findByText('Select model')).toBeInTheDocument() + expect(await screen.findByRole('heading', { name: 'Model' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /More models/ })).toBeInTheDocument() }) it('resets bash mode through the imperative clearPrompt', async () => { diff --git a/frontend/src/components/message/PromptInput.composer.test.tsx b/frontend/src/components/message/PromptInput.composer.test.tsx index db876d3c..06c38654 100644 --- a/frontend/src/components/message/PromptInput.composer.test.tsx +++ b/frontend/src/components/message/PromptInput.composer.test.tsx @@ -1,12 +1,13 @@ import { describe, expect, it } from 'vitest' -import { act, fireEvent, screen, waitFor } from '@testing-library/react' +import { act, fireEvent, screen, waitFor, within } from '@testing-library/react' import { useSessionStatus } from '@/stores/sessionStatusStore' import { connectTestEventStream } from '@/test/render' import { promptTextarea, renderPromptInput } from '@/test/promptInput' import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode' const submitButton = () => document.querySelector('[data-submit-prompt]') -const controlsRow = () => screen.getByTestId('composer-controls-row') +const inputRow = () => screen.getByTestId('composer-input-row') +const keysRow = () => screen.queryByTestId('composer-keys-row') const voiceMicButton = () => screen.queryByRole('button', { name: 'Start voice conversation' }) const keyButtons = () => screen.queryAllByRole('toolbar', { name: 'Insert' }) @@ -23,15 +24,30 @@ function assistantUsageMessage(tokens: SessionMessageAssistant['tokens']): Sessi } describe('PromptInput composer layout', () => { - it('anchors the activity bar in the gap above the controls row', async () => { + it('anchors the activity bar in the gap above the input row', async () => { useSessionStatus.getState().setStatus('test-session', { type: 'busy' }) await renderPromptInput() const bar = await screen.findByRole('progressbar', { name: 'Session working' }) - expect(controlsRow()).toContainElement(bar) - expect(controlsRow().firstElementChild).toBe(bar) + expect(inputRow()).toContainElement(bar) + expect(inputRow().firstElementChild).toBe(bar) expect(bar).toHaveClass('absolute', 'bottom-full') - expect(promptTextarea().compareDocumentPosition(bar) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(bar.compareDocumentPosition(promptTextarea()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + }) + + it('holds only the config trigger, the input and the action buttons in the input row', async () => { + await renderPromptInput() + + fireEvent.change(await screen.findByPlaceholderText('Send a message...'), { target: { value: 'hello' } }) + + const config = screen.getByRole('button', { name: /^Session config:/ }) + expect(within(inputRow()).getAllByRole('button')).toEqual([config, submitButton()]) + expect(promptTextarea().previousElementSibling).toBe(config) + expect(screen.queryByRole('button', { name: /^Agent:/ })).toBeNull() + expect(screen.queryByRole('button', { name: /permission/i })).toBeNull() + expect(screen.queryByRole('button', { name: /goal/i })).toBeNull() + expect(screen.queryByRole('button', { name: /sandbox/i })).toBeNull() + expect(screen.queryByRole('button', { name: /attach|upload/i })).toBeNull() }) describe('primary action placement', () => { @@ -53,7 +69,7 @@ describe('PromptInput composer layout', () => { expect(button.parentElement).toBe(textarea.parentElement) expect(textarea.nextElementSibling).toBe(button) - expect(button.parentElement?.contains(controlsRow())).toBe(false) + expect(button.parentElement).toBe(inputRow()) }) it('sends the typed prompt from the row button', async () => { @@ -101,30 +117,29 @@ describe('PromptInput composer layout', () => { it.each([true, false])('keeps the model selector visible while the session is active (mobile: %s)', async (mobile) => { await renderPromptInput({ isSessionActive: true, mobile }) - expect(await screen.findByRole('button', { name: /Claude Sonnet 4\.5/ })).toBeInTheDocument() + expect(await screen.findByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5/ })).toBeInTheDocument() }) }) - describe('model pill context usage', () => { - it('shows the percentage with its tone and the meter on the model pill', async () => { + describe('config trigger context usage', () => { + it('shows the percentage with its tone and the meter on the config trigger', async () => { await renderPromptInput({ transcript: { messages: [assistantUsageMessage({ input: 80000, output: 4000, reasoning: 0, cache: { read: 0, write: 0 } })], }, }) - const pill = await screen.findByRole('button', { name: /Claude Sonnet 4\.5, context 42% used/ }) - const usage = screen.getByTestId('model-pill-context-usage') + const trigger = await screen.findByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5, context 42% used/ }) + const meter = screen.getByTestId('context-usage-meter') - expect(pill).toContainElement(usage) - expect(usage).toHaveTextContent('42%') - expect(usage).toHaveClass('text-success') + expect(trigger).toContainElement(meter) expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '42%' }) + expect(screen.getByTestId('context-usage-meter-fill')).toHaveClass('bg-success') }) it.each([ - [100000, 'text-warning', '50%'], - [176000, 'text-destructive', '88%'], + [100000, 'bg-warning', 'context 50% used'], + [176000, 'bg-destructive', 'context 88% used'], ])('tints the usage from %i total tokens', async (totalTokens, tone, label) => { await renderPromptInput({ transcript: { @@ -132,9 +147,8 @@ describe('PromptInput composer layout', () => { }, }) - const usage = await screen.findByTestId('model-pill-context-usage') - expect(usage).toHaveClass(tone) - expect(usage).toHaveTextContent(label) + expect(await screen.findByRole('button', { name: new RegExp(`^Session config: .*${label}`) })).toBeInTheDocument() + expect(screen.getByTestId('context-usage-meter-fill')).toHaveClass(tone) }) it('caps the meter at full width when usage exceeds the context window', async () => { @@ -144,7 +158,7 @@ describe('PromptInput composer layout', () => { }, }) - await screen.findByTestId('model-pill-context-usage') + await screen.findByRole('button', { name: /^Session config: .*context 130% used/ }) expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '100%' }) }) @@ -156,7 +170,7 @@ describe('PromptInput composer layout', () => { }, }) - expect(await screen.findByTestId('model-pill-context-usage')).toHaveTextContent('12k') + expect(await screen.findByRole('button', { name: /^Session config: .*context 12k tokens used/ })).toBeInTheDocument() expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '0%' }) }) @@ -171,82 +185,80 @@ describe('PromptInput composer layout', () => { }, }) - const usage = await screen.findByTestId('model-pill-context-usage') - expect(usage).toHaveTextContent('42%') + expect(await screen.findByRole('button', { name: /^Session config: .*context 42% used/ })).toBeInTheDocument() }) it('hides the usage without context data', async () => { await renderPromptInput() - expect(await screen.findByRole('button', { name: 'Claude Sonnet 4.5' })).toBeInTheDocument() - expect(screen.queryByTestId('model-pill-context-usage')).not.toBeInTheDocument() + expect(await screen.findByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5/ })).toBeInTheDocument() expect(screen.queryByTestId('context-usage-meter')).not.toBeInTheDocument() }) }) describe('mobile key bar', () => { - it('replaces the agent and model selectors with keys in the controls row while focused', async () => { + it('mounts the key bar below the input row while focused and keeps the config trigger', async () => { await renderPromptInput({ mobile: true }) expect(await screen.findByPlaceholderText('Send a message...')).toBeInTheDocument() expect(keyButtons()).toHaveLength(0) - expect(screen.getByRole('button', { name: /Claude Sonnet 4\.5/ })).toBeInTheDocument() + expect(keysRow()).toBeNull() + const config = screen.getByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5/ }) + expect(inputRow()).toContainElement(config) fireEvent.focus(promptTextarea()) expect(keyButtons()).toHaveLength(1) - expect(controlsRow().firstElementChild).toContainElement(keyButtons()[0]) + expect(keysRow()).toContainElement(keyButtons()[0]) + expect(inputRow()).not.toContainElement(keyButtons()[0]) expect(screen.getByRole('button', { name: 'cmd /' })).toBeInTheDocument() expect(screen.getByRole('button', { name: 'mention @' })).toBeInTheDocument() expect(screen.getByRole('button', { name: 'bash !' })).toBeInTheDocument() - expect(screen.queryByRole('button', { name: /Claude Sonnet 4\.5/ })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5/ })).toBe(config) }) - it('restores the agent and model selectors after the prompt blurs', async () => { + it('removes the key bar after the prompt blurs', async () => { await renderPromptInput({ mobile: true }) fireEvent.focus(await screen.findByPlaceholderText('Send a message...')) - expect(screen.queryByRole('button', { name: /Claude Sonnet 4\.5/ })).not.toBeInTheDocument() + expect(keyButtons()).toHaveLength(1) fireEvent.blur(promptTextarea()) - await waitFor(() => { - expect(screen.queryByRole('toolbar', { name: 'Insert' })).not.toBeInTheDocument() - }) - expect(screen.getByRole('button', { name: /Claude Sonnet 4\.5/ })).toBeInTheDocument() + await waitFor(() => expect(keysRow()).toBeNull()) + expect(screen.getByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5/ })).toBeInTheDocument() }) - it('keeps the composer tools button at the bottom of the transcript', async () => { + it('keeps the session config button at the bottom of the transcript', async () => { await renderPromptInput({ mobile: true }) - expect(await screen.findByRole('button', { name: 'Composer options' })).toBeInTheDocument() + expect(await screen.findByRole('button', { name: /^Session config/ })).toBeInTheDocument() expect(screen.queryByRole('button', { name: 'Scroll to bottom' })).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: 'Jump to latest' })).not.toBeInTheDocument() }) - it('keeps the voice button and composer tools on the right side of the controls row', async () => { + it('keeps the voice button and the session config in the input row', async () => { await renderPromptInput({ mobile: true }) - fireEvent.focus(await screen.findByPlaceholderText('Send a message...')) + await screen.findByPlaceholderText('Send a message...') + const config = screen.getByRole('button', { name: /^Session config/ }) - const actions = controlsRow().lastElementChild - if (!(actions instanceof HTMLElement)) throw new Error('actions row is missing') - expect(actions).toContainElement(voiceMicButton()) - expect(actions).toContainElement(screen.getByRole('button', { name: 'Composer options' })) + expect(within(inputRow()).getAllByRole('button')).toEqual([config, voiceMicButton()]) }) }) describe('mobile voice button', () => { - it('renders the mobile mic alongside Send when the prompt has content', async () => { + it('replaces the mic with Send once the prompt has content', async () => { await renderPromptInput({ mobile: true }) - fireEvent.change(await screen.findByPlaceholderText('Send a message...'), { target: { value: 'hello' } }) + await screen.findByPlaceholderText('Send a message...') + expect(voiceMicButton()).not.toBeNull() + + fireEvent.change(promptTextarea(), { target: { value: 'hello' } }) expect(submitButton()).not.toBeNull() - expect(voiceMicButton()).not.toBeNull() - const actions = controlsRow().lastElementChild - if (!(actions instanceof HTMLElement)) throw new Error('actions row is missing') - expect(actions).toContainElement(voiceMicButton()) + expect(voiceMicButton()).toBeNull() + expect(inputRow()).toContainElement(submitButton()) }) it('hides the mic while a permission is pending', async () => { @@ -268,6 +280,34 @@ describe('PromptInput composer layout', () => { }) }) + describe('stop action', () => { + it.each([true, false])('shows Stop in the input row while a turn runs and hides the mic (mobile: %s)', async (mobile) => { + const { rerenderWith } = await renderPromptInput({ mobile, isSessionActive: true }) + + await screen.findByPlaceholderText('Send a message...') + const stop = screen.getByTitle('Stop') + expect(inputRow()).toContainElement(stop) + expect(voiceMicButton()).toBeNull() + if (mobile) { + expect(stop).toHaveClass('min-h-11', 'min-w-11') + } + + await rerenderWith({ isSessionActive: false }) + + expect(screen.queryByTitle('Stop')).toBeNull() + expect(voiceMicButton()).not.toBeNull() + }) + + it('keeps Stop next to Queue while the prompt has text during a turn', async () => { + await renderPromptInput({ isSessionActive: true, isStreamingResponse: true }) + + fireEvent.change(await screen.findByPlaceholderText('Send a message...'), { target: { value: 'follow-up' } }) + + const queue = screen.getByTitle('Queue message') + expect(queue.nextElementSibling).toBe(screen.getByTitle('Stop')) + }) + }) + describe('control sizing', () => { it('keeps the mic at 44px before and after the prompt gains focus on mobile', async () => { await renderPromptInput({ mobile: true }) diff --git a/frontend/src/components/message/PromptInput.config.test.tsx b/frontend/src/components/message/PromptInput.config.test.tsx new file mode 100644 index 00000000..3f2d89a2 --- /dev/null +++ b/frontend/src/components/message/PromptInput.config.test.tsx @@ -0,0 +1,550 @@ +import { createRef } from 'react' +import { describe, expect, it, vi } from 'vitest' +import { act, fireEvent, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { SessionGoalRead, SessionMessageAssistant } 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 } +} + +function assistantUsageMessage(tokens: SessionMessageAssistant['tokens']): SessionMessageAssistant { + return { + id: 'msg_assistant', + type: 'assistant', + agent: 'build', + model: { providerID: 'anthropic', id: 'claude-sonnet-4-5' }, + content: [{ type: 'text', text: 'A reply' }], + time: { created: 1, completed: 2 }, + tokens, + } +} + +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') + expect(trigger).toHaveClass('shrink-0', 'p-0') + if (mobile) { + expect(trigger).not.toHaveClass('bg-highlight') + expect(trigger).toHaveClass('size-11') + } else { + expect(trigger).toHaveClass('size-9') + } + + await openConfig(user) + expect(await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })).toHaveAttribute('aria-checked', 'false') + }) + + it('summarises agent, model, variant and context inside the trigger', async () => { + await renderConfig(mobile, { + agents: [makeAgent({ id: 'build', mode: 'primary' })], + models: [ + { + id: 'claude-sonnet-4-5', + providerID: 'anthropic', + name: 'Claude Sonnet 4.5', + variants: ['high', 'low'], + }, + ], + modelState: { variant: { 'anthropic/claude-sonnet-4-5': 'high' } }, + transcript: { + messages: [assistantUsageMessage({ input: 80000, output: 4000, reasoning: 0, cache: { read: 0, write: 0 } })], + }, + }) + + const trigger = await configTrigger() + + expect(trigger).toHaveAccessibleName(/^Session config: Build, Claude Sonnet 4\.5, high variant, context 42% used/) + expect(within(trigger).getByText('Build')).toBeInTheDocument() + expect(within(trigger).getByText('· Claude Sonnet 4.5')).toBeInTheDocument() + expect(within(trigger).getByText('High')).toBeInTheDocument() + expect(within(trigger).getByText('42%')).toBeInTheDocument() + expect(within(trigger).getByTestId('context-usage-meter')).toBeInTheDocument() + if (mobile) { + expect(trigger).not.toHaveClass('@min-[86rem]/composer:absolute') + } else { + expect(trigger).toHaveClass('@min-[86rem]/composer:absolute', '@min-[86rem]/composer:h-10') + } + }) + + 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 from the agent view 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) + + await user.click(await screen.findByRole('menuitem', { name: /Change agent: Build/ })) + + 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(await screen.findByRole('menuitem', { name: /Change agent: Plan/ })).toBeInTheDocument() + + 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 view in the config surface 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('heading', { name: 'Model' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /More models/ })).toBeInTheDocument() + expect(screen.queryByRole('menuitem', { name: /Change agent/ })).not.toBeInTheDocument() + }) + + it('selects a model from the model view and returns to the main view', async () => { + const { user, fetchFake } = await renderConfig(mobile, { + models: [ + { id: 'claude-sonnet-4-5', providerID: 'anthropic', name: 'Claude Sonnet 4.5' }, + { id: 'claude-opus-5', providerID: 'anthropic', name: 'Claude Opus 5' }, + ], + }) + await openConfig(user) + + await user.click(await screen.findByRole('menuitem', { name: /Change model/ })) + await user.click(await screen.findByRole('button', { name: /Claude Opus 5/ })) + + expect(await screen.findByRole('menuitem', { name: /Change model: Claude Opus 5/ })).toBeInTheDocument() + await waitFor(() => + expect(fetchFake.lastRequest('POST', '/api/providers/model-state')?.body).toMatchObject({ + recent: { providerID: 'anthropic', modelID: 'claude-opus-5' }, + }), + ) + }) + + 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('moves focus between menu items with the keyboard and exposes named sections', async () => { + const { user } = await renderConfig(mobile, { + agents: [makeAgent({ id: 'build', mode: 'primary' })], + }) + await openConfig(user) + + expect(await screen.findByRole('group', { name: 'Session' })).toBeInTheDocument() + expect(screen.getByRole('group', { name: 'Agent' })).toBeInTheDocument() + + const first = screen.getByRole('menuitem', { name: /Change agent: Build/ }) + first.focus() + await user.keyboard('{ArrowDown}') + expect(screen.getByRole('menuitem', { name: /Change model/ })).toHaveFocus() + + await user.keyboard('{End}') + expect(screen.getByRole('menuitem', { name: 'Attach image or PDF' })).toHaveFocus() + }) + + 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('prefills the dialog from the effective values without an override', async () => { + await openResources({ sandbox: { resources: null, effectiveResources: { cpus: 2, memoryMib: 4096 } } }) + + expect(screen.getByLabelText('CPUs')).toHaveValue(2) + expect(screen.getByLabelText('Memory (GiB)')).toHaveValue(4) + }) + + 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') + }) + }) +}) diff --git a/frontend/src/components/message/PromptInput.goal.test.tsx b/frontend/src/components/message/PromptInput.goal.test.tsx index c1dad119..af8805b9 100644 --- a/frontend/src/components/message/PromptInput.goal.test.tsx +++ b/frontend/src/components/message/PromptInput.goal.test.tsx @@ -6,9 +6,9 @@ import type { SessionGoalRead } from '@opencode-manager/shared/opencode' import { promptTextarea, renderPromptInput } from '@/test/promptInput' import type { FetchRouteResult } from '@/test/fetchFake' -const GOAL_BUTTON = 'Goal mode: the next message becomes the objective' -const OPEN_GOAL_BUTTON = 'A goal is already active for this session' -const UNSUPPORTED_GOAL_BUTTON = "This server's OpenCode has no goals" +const GOAL_DETAIL = 'Goal mode: the next message becomes the objective' +const OPEN_GOAL_DETAIL = 'A goal is already active for this session' +const UNSUPPORTED_GOAL_DETAIL = "This server's OpenCode has no goals" const idleGoal: SessionGoalRead = { supported: true, goal: null } @@ -43,8 +43,16 @@ function deferredCommand() { return { respond, resolve: (result: FetchRouteResult) => resolve(result) } } +async function openConfig() { + const user = userEvent.setup() + await user.click(await screen.findByRole('button', { name: /^Session config/ })) + return user +} + async function armGoal() { - fireEvent.click(await screen.findByRole('button', { name: GOAL_BUTTON })) + const user = await openConfig() + await user.click(await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ })) + await user.keyboard('{Escape}') } describe('PromptInput goal mode', () => { @@ -178,13 +186,21 @@ describe('PromptInput goal mode', () => { it('disables goal mode when the server has no goal support', async () => { await renderPromptInput({ goal: { supported: false } }) - expect(await screen.findByRole('button', { name: UNSUPPORTED_GOAL_BUTTON })).toBeDisabled() + await openConfig() + + const item = await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ }) + expect(item).toHaveAttribute('aria-disabled', 'true') + expect(item).toHaveTextContent(UNSUPPORTED_GOAL_DETAIL) }) it('disables goal mode while a goal is already active', async () => { await renderPromptInput({ goal: openGoal }) - expect(await screen.findByRole('button', { name: OPEN_GOAL_BUTTON })).toBeDisabled() + await openConfig() + + const item = await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ }) + expect(item).toHaveAttribute('aria-disabled', 'true') + expect(item).toHaveTextContent(OPEN_GOAL_DETAIL) }) it('keeps goal mode enabled on child sessions', async () => { @@ -193,44 +209,47 @@ describe('PromptInput goal mode', () => { permissionMode: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'child' }, }) - expect(await screen.findByRole('button', { name: GOAL_BUTTON })).toBeEnabled() + const user = await openConfig() + + const item = await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ }) + expect(item).not.toHaveAttribute('aria-disabled', 'true') + + await user.click(item) + expect(item).toHaveAttribute('aria-checked', 'true') }) - it('keeps permission and goal toggles inline on desktop', async () => { - await renderPromptInput({ goal: idleGoal }) + it.each([false, true])('keeps goal and permission controls inside the config surface only (mobile: %s)', async (mobile) => { + await renderPromptInput({ goal: idleGoal, mobile }) - expect(await screen.findByRole('button', { name: GOAL_BUTTON })).toBeInTheDocument() - expect(screen.getByRole('button', { name: /Permissions:/ })).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Composer options' })).not.toBeInTheDocument() + const user = await openConfig() + + expect(screen.queryByRole('button', { name: /^Permissions:/ })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: /^Goal mode/ })).not.toBeInTheDocument() + + const permission = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ }) + const goal = screen.getByRole('menuitemcheckbox', { name: /Goal mode/ }) + expect(permission).toBeInTheDocument() + expect(goal).not.toHaveAttribute('aria-disabled', 'true') + expect(goal).not.toHaveTextContent(GOAL_DETAIL) + + await user.keyboard('{Escape}') }) - it('moves permission and goal toggles into the composer options menu on mobile', async () => { - await renderPromptInput({ goal: idleGoal, mobile: true }) - - const menu = await screen.findByRole('button', { name: 'Composer options' }) - expect(menu).toHaveAttribute('title', 'Composer options') - expect(screen.queryByRole('button', { name: GOAL_BUTTON })).not.toBeInTheDocument() - expect(screen.queryByRole('button', { name: /Permissions:/ })).not.toBeInTheDocument() - }) - - it('runs the goal command when armed from the mobile composer options menu', async () => { - const user = userEvent.setup() + it('runs the goal command when armed from the config surface on mobile', async () => { const { fetchFake } = await renderPromptInput({ goal: idleGoal, mobile: true }) fireEvent.change(promptTextarea(), { target: { value: 'Ship the feature' } }) - await user.click(await screen.findByRole('button', { name: 'Composer options' })) - await user.click(await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ })) + await armGoal() fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(fetchFake.lastRequest('POST', '/api/opencode/api/session/test-session/command')).toBeDefined()) expect(fetchFake.lastRequest('POST', '/api/opencode/api/session/test-session/command')?.body).toMatchObject(goalCommandBody) }) - it('passes the open goal state to the mobile composer options menu', async () => { - const user = userEvent.setup() + it('passes the open goal state to the config surface', async () => { await renderPromptInput({ goal: openGoal, mobile: true }) - await user.click(await screen.findByRole('button', { name: 'Composer options' })) + await openConfig() expect(await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ })).toHaveAttribute('aria-disabled', 'true') }) diff --git a/frontend/src/components/message/PromptInput.stt.test.tsx b/frontend/src/components/message/PromptInput.stt.test.tsx index 9bc84480..9d80bb62 100644 --- a/frontend/src/components/message/PromptInput.stt.test.tsx +++ b/frontend/src/components/message/PromptInput.stt.test.tsx @@ -333,7 +333,7 @@ describe('PromptInput submission', () => { fireEvent.change(promptTextarea(), { target: { value: 'draft while active' } }) - expect(screen.getAllByTitle('Stop').length).toBeGreaterThan(0) + expect(screen.getAllByTitle('Stop')).toHaveLength(1) }) it('clears the draft store for the session after a successful send', async () => { diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index fa5f2178..ec6481ae 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -20,20 +20,15 @@ import { useMobile } from '@/hooks/useMobile' import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery' import { usePermissions } from '@/contexts/event-context' -import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/opencode-server-context' -import { Upload, X, Mic, Target } from 'lucide-react' +import { useOpenCodeServerId } from '@/contexts/opencode-server-context' +import { X, Mic } from 'lucide-react' import { SquareFill } from '@/components/ui/square-fill' -import { IconToggleButton } from '@/components/ui/icon-toggle-button' import { PromptSuggestions, type PromptSuggestion } from './PromptSuggestions' import { ComposerActivityBar } from './ComposerActivityBar' -import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect' +import { SessionConfigMenu } from './SessionConfigMenu' import { VoiceConversation, type VoiceConversationFactory, type VoiceConversationHandle } from './VoiceConversation' -import { PermissionModeToggle } from '@/components/session/PermissionModeToggle' -import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu' -import { ComposerModelPill } from './ComposerModelPill' -import { ComposerToolsMenu } from './ComposerToolsMenu' import { useSessionGoal, useSessionGoalCommand } from '@/hooks/useSessionGoals' import { detectMentionTrigger, parsePromptToInput, getFilename, getDirectory, type MentionItem, type ParsedPromptInput } from '@/lib/promptParser' import { matchText, rankByMatch, type MatchRange } from '@/lib/fuzzyMatch' @@ -253,7 +248,6 @@ export const PromptInput = memo(forwardRef( const sessionAgent = useSessionAgent(sessionID, directory) const hasBackgroundActivity = useHasBackgroundActivity(sessionID) const serverId = useOpenCodeServerId() - const isLocalServer = isLocalOpenCodeServer(serverId) const currentMode = localMode ?? sessionAgent.agent const setStoredAgent = useSessionAgentStore((s) => s.setAgent) const sendPrompt = useSendPrompt(directory) @@ -1031,9 +1025,8 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) }, [currentModel, model, providersData]) const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions() const hasPendingPermissionForSession = hasPermissionsForSession(sessionID) - const { hasVariants, currentVariant, cycleVariant } = useVariants(directory, modelSelectionSession) + const { hasVariants, cycleVariant } = useVariants(directory, modelSelectionSession) const isCompacting = useSessionStatusForSession(sessionID).type === 'compact' - const modelPillVariant = hasVariants && currentVariant ? currentVariant : null const handleCompact = useCallback(() => commandActions.compact(''), [commandActions]) const handleAgentChange = useCallback((agentId: string) => { @@ -1274,7 +1267,26 @@ return ( {!isVoiceActive && ( <> -
+
+ +