Session config surface replaces the row controls

This commit is contained in:
Chris Scott committed 2026-11-26 23:48:09 -05:00
1 parent 750faf1361
commit 13eca93b92
16 files changed
+1035 -1102

No files matched your search

@@ -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<AgentInfo, 'id' | 'name' | 'color' | 'description' | 'mode' | 'hidden'>
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 = (
<button
style={{ ...styleVars }}
className="px-2 md:px-3.5 py-1 h-11 md:h-9 rounded-lg text-sm font-medium border min-w-[56px] max-w-[80px] md:max-w-[100px] flex-shrink-0 flex items-center justify-center transition-all duration-200 active:scale-95 hover:scale-105 shadow-md text-[var(--agent-color)] bg-[var(--agent-bg)] border-[var(--agent-border)] hover:bg-[var(--agent-bg-hover)] hover:border-[var(--agent-border-hover)] shadow-[var(--agent-shadow)] hover:shadow-[var(--agent-shadow-hover)]"
>
<span className="truncate">{displayName}</span>
</button>
)
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
{buttonContent}
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-64">
{primaryAgents.map((agent) => {
const apiColor = agent.color
const itemStyleVars = getAgentStyleVars(agent.id, apiColor)
const isSelected = agent.id.toLowerCase() === currentAgent.toLowerCase()
return (
<DropdownMenuItem
key={agent.id}
onClick={() => handleSelect(agent.id)}
className="group flex items-center justify-between"
>
<div className="flex flex-col min-w-0">
<span
className="font-medium"
style={{ color: itemStyleVars['--agent-color'] }}
>
{capitalize(agent.name)}
</span>
{agent.description && (
<span className="text-xs text-muted-foreground line-clamp-2 group-hover:line-clamp-none">
{agent.description}
</span>
)}
</div>
{isSelected && <Check className="h-4 w-4 flex-shrink-0 ml-2" />}
</DropdownMenuItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -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(
() => (
<button
aria-label={pillLabel}
className="relative px-2.5 py-0.5 md:px-3 min-h-11 md:min-h-9 min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
>
<span className="truncate w-full text-left">{modelName || 'Select model'}</span>
{(variant || pillUsage) && (
<span className="flex w-full min-w-0 items-center gap-1 text-[10px] leading-tight">
{variant && (
<span className="truncate text-left capitalize text-highlight">{variant}</span>
)}
{variant && pillUsage && (
<span aria-hidden="true" className="text-muted-foreground">·</span>
)}
{pillUsage && (
<span
data-testid="model-pill-context-usage"
className={cn('shrink-0 font-medium', pillUsageTone)}
>
{pillUsage}
</span>
)}
</span>
)}
{contextUsage && (
<ContextUsageMeter
percentage={contextUsage.usagePercentage}
className="absolute inset-x-0 bottom-0"
/>
)}
</button>
),
[contextUsage, modelName, pillLabel, pillUsage, pillUsageTone, variant],
)
return (
<ModelQuickSelect
directory={directory}
open={open}
onOpenChange={onOpenChange}
session={modelSelectionSession}
contextUsage={contextUsage}
isCompacting={isCompacting}
onCompact={onCompact}
>
{trigger}
</ModelQuickSelect>
)
})
@@ -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<SessionPermissionModeState>
sandbox?: Partial<SessionSandboxState>
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(<ComposerToolsMenu {...props} />, { ...options, serverId: 'srv_remote' })
: renderWithProviders(<ComposerToolsMenu {...props} />, 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<typeof userEvent.setup>) {
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')
})
})
@@ -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 (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label="Composer options"
title="Composer options"
className={cn(getIconToggleButtonClassName(permission.isAuto || sandbox.isSandboxed || goalArmed), 'flex items-center justify-center size-11 p-0')}
>
<Plus className="w-5 h-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="end" collisionPadding={8} className="w-64">
<DropdownMenuCheckboxItem
checked={permission.isAuto}
disabled={permission.disabled}
onCheckedChange={permission.toggle}
>
<ToolMenuItemContent
icon={permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
title="Accept all permissions"
detail={permission.disabled ? permission.label : undefined}
/>
</DropdownMenuCheckboxItem>
{isLocalServer && (
<SandboxMenuItems sandbox={sandbox} onOpenResources={() => setResourcesOpen(true)} />
)}
<DropdownMenuCheckboxItem checked={goalArmed} disabled={goalDisabled} onCheckedChange={onToggleGoal}>
<ToolMenuItemContent
icon={<Target className="h-4 w-4" />}
title="Goal mode"
detail={goalDisabled ? goalLabel : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={onAttachFile} className="pl-8">
<ToolMenuItemContent icon={<Paperclip className="h-4 w-4" />} title="Attach image or PDF" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{shouldShowSandboxResources(sandbox) ? (
<SessionSandboxResourcesDialog
sessionID={sessionID}
open={resourcesOpen}
onOpenChange={setResourcesOpen}
override={sandbox.resources}
effective={sandbox.effectiveResources!}
/>
) : null}
</>
)
}
@@ -101,22 +101,22 @@ 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 usage = screen.getByTestId('composer-config-context-usage')
expect(pill).toContainElement(usage)
expect(trigger).toContainElement(usage)
expect(usage).toHaveTextContent('42%')
expect(usage).toHaveClass('text-success')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '42%' })
@@ -132,7 +132,7 @@ describe('PromptInput composer layout', () => {
},
})
const usage = await screen.findByTestId('model-pill-context-usage')
const usage = await screen.findByTestId('composer-config-context-usage')
expect(usage).toHaveClass(tone)
expect(usage).toHaveTextContent(label)
})
@@ -144,7 +144,7 @@ describe('PromptInput composer layout', () => {
},
})
await screen.findByTestId('model-pill-context-usage')
await screen.findByTestId('composer-config-context-usage')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '100%' })
})
@@ -156,7 +156,7 @@ describe('PromptInput composer layout', () => {
},
})
expect(await screen.findByTestId('model-pill-context-usage')).toHaveTextContent('12k')
expect(await screen.findByTestId('composer-config-context-usage')).toHaveTextContent('12k')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '0%' })
})
@@ -171,26 +171,26 @@ describe('PromptInput composer layout', () => {
},
})
const usage = await screen.findByTestId('model-pill-context-usage')
const usage = await screen.findByTestId('composer-config-context-usage')
expect(usage).toHaveTextContent('42%')
})
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('composer-config-context-usage')).not.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('replaces the config trigger with keys in the controls row while focused', 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(screen.getByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5/ })).toBeInTheDocument()
fireEvent.focus(promptTextarea())
@@ -199,40 +199,42 @@ describe('PromptInput composer layout', () => {
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.queryByRole('button', { name: /^Session config/ })).not.toBeInTheDocument()
})
it('restores the agent and model selectors after the prompt blurs', async () => {
it('restores the config trigger 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(screen.queryByRole('button', { name: /^Session config/ })).not.toBeInTheDocument()
fireEvent.blur(promptTextarea())
await waitFor(() => {
expect(screen.queryByRole('toolbar', { name: 'Insert' })).not.toBeInTheDocument()
})
expect(screen.getByRole('button', { name: /Claude Sonnet 4\.5/ })).toBeInTheDocument()
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 on the right and the session config in the controls row', async () => {
await renderPromptInput({ mobile: true })
fireEvent.focus(await screen.findByPlaceholderText('Send a message...'))
await screen.findByPlaceholderText('Send a message...')
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' }))
const config = screen.getByRole('button', { name: /^Session config/ })
expect(controlsRow()).toContainElement(config)
expect(actions).not.toContainElement(config)
})
})
@@ -0,0 +1,452 @@
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<SessionPermissionModeState>
sandbox?: Partial<SessionSandboxState>
}
function withPermission(overrides: Partial<SessionPermissionModeState> = {}): SessionPermissionModeState {
return { ...basePermissionState, ...overrides }
}
function withSandbox(overrides: Partial<SessionSandboxState> = {}): 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<typeof userEvent.setup>) {
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<PromptInputHandle>()
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')
})
})
})
@@ -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')
})
+22 -63
View File
@@ -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<PromptInputHandle, PromptInputProps>(
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) => {
@@ -1345,39 +1338,24 @@ return (
<ComposerActivityBar sessionID={sessionID} />
<div className="flex flex-1 md:flex-initial gap-1.5 md:gap-2 items-center min-w-0">
{showMobileKeys ? renderMobileKeys() : (
<>
<AgentQuickSelect
directory={directory}
currentAgent={currentMode}
onAgentChange={handleAgentChange}
isBashMode={isBashMode}
/>
{directory && !isMobile ? (
<>
<PermissionModeToggle sessionID={sessionID} directory={directory} />
{isLocalServer && <SessionSandboxMenu sessionID={sessionID} />}
<IconToggleButton
active={isGoalArmed}
label={goalButtonLabel}
disabled={isGoalModeDisabled}
onClick={toggleGoalArmed}
>
<Target className="w-5 h-5" />
</IconToggleButton>
</>
) : null}
<ComposerModelPill
directory={directory}
sessionID={sessionID}
modelName={displayModelName}
variant={modelPillVariant}
modelSelectionSession={modelSelectionSession}
open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen}
isCompacting={isCompacting}
onCompact={handleCompact}
/>
</>
<SessionConfigMenu
sessionID={sessionID}
directory={directory}
currentAgent={currentMode}
isBashMode={isBashMode}
onAgentChange={handleAgentChange}
modelName={displayModelName}
modelSelectionSession={modelSelectionSession}
modelPickerOpen={isModelPickerOpen}
onModelPickerOpenChange={setIsModelPickerOpen}
isCompacting={isCompacting}
onCompact={handleCompact}
goalArmed={isGoalArmed}
goalDisabled={isGoalModeDisabled}
goalLabel={goalButtonLabel}
onToggleGoal={toggleGoalArmed}
onAttachFile={openFilePicker}
/>
)}
</div>
<div className="flex items-center gap-1.5 md:gap-2 flex-shrink-0">
@@ -1397,26 +1375,7 @@ return (
className="hidden"
onChange={handleFileInputChange}
/>
<button
type="button"
onClick={openFilePicker}
className="hidden md:block p-2 rounded-lg bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border border-border"
title="Upload image or PDF"
>
<Upload className="w-5 h-5" />
</button>
{showVoiceMic && renderVoiceMic()}
{isMobile && directory && (
<ComposerToolsMenu
sessionID={sessionID}
directory={directory}
goalArmed={isGoalArmed}
goalDisabled={isGoalModeDisabled}
goalLabel={goalButtonLabel}
onToggleGoal={toggleGoalArmed}
onAttachFile={openFilePicker}
/>
)}
</div>
</div>
</>
@@ -1,38 +0,0 @@
import { Box, Cpu } from 'lucide-react'
import { DropdownMenuCheckboxItem, DropdownMenuItem } from '@/components/ui/dropdown-menu'
import { formatSandboxResources, shouldShowSandboxResources, type SandboxToggleState } from '@/lib/sandboxResources'
import { ToolMenuItemContent } from './ToolMenuItemContent'
interface SandboxMenuItemsProps {
sandbox: SandboxToggleState
onOpenResources: () => void
}
export function SandboxMenuItems({ sandbox, onOpenResources }: SandboxMenuItemsProps) {
return (
<>
{sandbox.available ? (
<DropdownMenuCheckboxItem
checked={sandbox.isSandboxed}
disabled={sandbox.disabled}
onCheckedChange={sandbox.toggle}
>
<ToolMenuItemContent
icon={<Box className="h-4 w-4" />}
title="Sandbox commands"
detail={sandbox.disabled ? sandbox.label : undefined}
/>
</DropdownMenuCheckboxItem>
) : null}
{shouldShowSandboxResources(sandbox) ? (
<DropdownMenuItem className="pl-8" aria-haspopup="dialog" onSelect={() => setTimeout(onOpenResources, 0)}>
<ToolMenuItemContent
icon={<Cpu className="h-4 w-4" />}
title="Sandbox resources…"
detail={`${formatSandboxResources(sandbox.effectiveResources!)}${sandbox.resources ? ' · custom' : ''}`}
/>
</DropdownMenuItem>
) : null}
</>
)
}
@@ -0,0 +1,481 @@
import { Fragment, memo, useState, type ReactNode } from 'react'
import { Box, Cpu, Paperclip, Shield, ShieldCheck, SlidersHorizontal, Target } from 'lucide-react'
import type { AgentInfo } from '@opencode-manager/shared/opencode'
import { useAgents, useSession } from '@/hooks/useOpenCode'
import { useContextUsage } from '@/hooks/useContextUsage'
import { useVariants } from '@/hooks/useVariants'
import type { ModelSelectionSession } from '@/hooks/useModelSelection'
import { useMobile } from '@/hooks/useMobile'
import { usePermissionModeToggle } from '@/hooks/usePermissionModeToggle'
import { useSandboxToggle } from '@/hooks/useSandboxToggle'
import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/opencode-server-context'
import { getPrimaryAgents } from '@/lib/primaryAgents'
import { getAgentStyleVars } from '@/lib/agent-colors'
import { shouldShowSandboxResources, formatSandboxResources } from '@/lib/sandboxResources'
import {
CONTEXT_USAGE_TEXT_CLASS,
contextUsageAccessibleLabel,
contextUsageTone,
formatContextUsage,
} from '@/lib/contextUsage'
import { cn } from '@/lib/utils'
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { ContextUsageMeter } from '@/components/session/ContextUsageMeter'
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { SessionSandboxResourcesDialog } from './SessionSandboxResourcesDialog'
import { ToolMenuItemContent } from './ToolMenuItemContent'
interface SessionConfigMenuProps {
sessionID: string
directory?: string
currentAgent: string
isBashMode: boolean
onAgentChange: (agentId: string) => void
modelName: string
modelSelectionSession?: ModelSelectionSession
modelPickerOpen: boolean
onModelPickerOpenChange: (open: boolean) => void
isCompacting: boolean
onCompact: () => void
goalArmed: boolean
goalDisabled: boolean
goalLabel: string
onToggleGoal: () => void
onAttachFile: () => void
}
interface SessionConfigEntryBase {
key: string
title: string
detail?: string
disabled?: boolean
icon?: ReactNode
className?: string
}
type SessionConfigEntry =
| (SessionConfigEntryBase & { kind: 'radio'; checked: boolean; onSelect: () => void })
| (SessionConfigEntryBase & { kind: 'checkbox'; checked: boolean; onSelect: () => void })
| (SessionConfigEntryBase & { kind: 'action'; onSelect: () => void })
interface SessionConfigSection {
key: string
label: string
entries: SessionConfigEntry[]
}
type SelectableAgent = Pick<AgentInfo, 'id' | 'name' | 'color' | 'description'>
const capitalize = (value: string) => value.charAt(0).toUpperCase() + value.slice(1).toLowerCase()
const findAgent = (agents: SelectableAgent[], agentId: string): SelectableAgent | undefined =>
agents.find((agent) => agent.id.toLowerCase() === agentId.toLowerCase())
const EMPTY_ICON = <span aria-hidden="true" className="block h-4 w-4" />
const TRIGGER_CLASS =
'relative px-2.5 py-0.5 md:px-3 min-h-11 md:min-h-9 min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[260px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden'
export const SessionConfigMenu = memo(function SessionConfigMenu({
sessionID,
directory,
currentAgent,
isBashMode,
onAgentChange,
modelName,
modelSelectionSession,
modelPickerOpen,
onModelPickerOpenChange,
isCompacting,
onCompact,
goalArmed,
goalDisabled,
goalLabel,
onToggleGoal,
onAttachFile,
}: SessionConfigMenuProps) {
const isMobile = useMobile()
const { data: agents = [] } = useAgents(directory)
const { hasVariants, availableVariants, currentVariant, setVariant, clearVariant } = useVariants(
directory,
modelSelectionSession,
)
const { data: session } = useSession(sessionID, directory)
const contextUsage = useContextUsage(sessionID, directory, session?.revert?.messageID)
const isLocalServer = isLocalOpenCodeServer(useOpenCodeServerId())
const permission = usePermissionModeToggle(sessionID, directory ?? '', { enabled: directory !== undefined })
const sandbox = useSandboxToggle(sessionID, { enabled: isLocalServer })
const [open, setOpen] = useState(false)
const [resourcesOpen, setResourcesOpen] = useState(false)
const currentAgentInfo = findAgent(agents, currentAgent)
const agentLabel = isBashMode ? 'Bash' : capitalize(currentAgentInfo?.name ?? currentAgent)
const agentStyleVars = getAgentStyleVars(
isBashMode ? 'plan' : currentAgent,
isBashMode ? undefined : currentAgentInfo?.color,
)
const usageLabel = contextUsage ? formatContextUsage(contextUsage) : null
const usageTone = CONTEXT_USAGE_TEXT_CLASS[contextUsageTone(contextUsage?.usagePercentage ?? null)]
const showVariant = hasVariants && Boolean(currentVariant)
const isAnySessionToggleActive = permission.isAuto || sandbox.isSandboxed || goalArmed
const configName = `Session config: ${[
agentLabel,
modelName || 'Select model',
showVariant ? `${currentVariant} variant` : null,
contextUsage ? contextUsageAccessibleLabel(contextUsage) : null,
].filter(Boolean).join(', ')}`
const sections: SessionConfigSection[] = [
{
key: 'agent',
label: 'Agent',
entries: getPrimaryAgents(agents).map((agent) => ({
kind: 'radio',
key: `agent:${agent.id}`,
title: capitalize(agent.name),
detail: agent.description || undefined,
checked: agent.id.toLowerCase() === currentAgent.toLowerCase(),
onSelect: () => onAgentChange(agent.id),
})),
},
{
key: 'model',
label: 'Model',
entries: [
{
kind: 'action',
key: 'model',
title: modelName || 'Select model',
detail: 'Change model',
onSelect: () => {
setOpen(false)
setTimeout(() => onModelPickerOpenChange(true), 0)
},
},
],
},
]
if (hasVariants) {
sections.push({
key: 'variant',
label: 'Variant',
entries: [
{
kind: 'radio',
key: 'variant:default',
title: 'Default',
checked: currentVariant === undefined,
onSelect: clearVariant,
},
...availableVariants.map((variant) => ({
kind: 'radio' as const,
key: `variant:${variant}`,
title: variant,
className: 'capitalize',
checked: currentVariant === variant,
onSelect: () => setVariant(variant),
})),
],
})
}
sections.push({
key: 'context',
label: 'Context',
entries: [
{
kind: 'action',
key: 'context',
title: 'Compact session',
detail: contextUsage ? contextUsageAccessibleLabel(contextUsage) : undefined,
disabled: isCompacting,
onSelect: () => {
onCompact()
setOpen(false)
},
},
],
})
if (directory !== undefined) {
const sessionEntries: SessionConfigEntry[] = [
{
kind: 'checkbox',
key: 'permission',
title: 'Accept all permissions',
detail: permission.disabled ? permission.label : undefined,
checked: permission.isAuto,
disabled: permission.disabled,
icon: permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />,
onSelect: permission.toggle,
},
]
if (isLocalServer && sandbox.available) {
sessionEntries.push({
kind: 'checkbox',
key: 'sandbox',
title: 'Sandbox commands',
detail: sandbox.disabled ? sandbox.label : undefined,
checked: sandbox.isSandboxed,
disabled: sandbox.disabled,
icon: <Box className="h-4 w-4" />,
onSelect: sandbox.toggle,
})
if (shouldShowSandboxResources(sandbox)) {
sessionEntries.push({
kind: 'action',
key: 'sandbox-resources',
title: 'Sandbox resources…',
detail: `${formatSandboxResources(sandbox.effectiveResources!)}${sandbox.resources ? ' · custom' : ''}`,
icon: <Cpu className="h-4 w-4" />,
onSelect: () => {
setOpen(false)
setTimeout(() => setResourcesOpen(true), 0)
},
})
}
}
sessionEntries.push({
kind: 'checkbox',
key: 'goal',
title: 'Goal mode',
detail: goalDisabled ? goalLabel : undefined,
checked: goalArmed,
disabled: goalDisabled,
icon: <Target className="h-4 w-4" />,
onSelect: onToggleGoal,
})
sections.push({ key: 'session', label: 'Session', entries: sessionEntries })
}
sections.push({
key: 'attach',
label: '',
entries: [
{
kind: 'action',
key: 'attach',
title: 'Attach image or PDF',
icon: <Paperclip className="h-4 w-4" />,
onSelect: () => {
onAttachFile()
setOpen(false)
},
},
],
})
const renderDesktopEntry = (entry: SessionConfigEntry) => {
const fallbackClass = entry.kind === 'action' ? 'pl-8' : undefined
if (entry.kind === 'radio') {
return (
<DropdownMenuRadioItem
key={entry.key}
value={entry.key}
disabled={entry.disabled}
className={cn(fallbackClass, entry.className)}
onSelect={(event) => event.preventDefault()}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</DropdownMenuRadioItem>
)
}
if (entry.kind === 'checkbox') {
return (
<DropdownMenuCheckboxItem
key={entry.key}
checked={entry.checked}
disabled={entry.disabled}
className={cn(fallbackClass, entry.className)}
onSelect={(event) => event.preventDefault()}
onCheckedChange={() => entry.onSelect()}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</DropdownMenuCheckboxItem>
)
}
return (
<DropdownMenuItem
key={entry.key}
disabled={entry.disabled}
className={cn(fallbackClass, entry.className)}
onSelect={() => entry.onSelect()}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</DropdownMenuItem>
)
}
const renderDesktopSection = (section: SessionConfigSection) => {
const checkedKey = section.entries.find((entry) => entry.kind === 'radio' && entry.checked)?.key
const hasRadio = section.entries.some((entry) => entry.kind === 'radio')
if (hasRadio) {
return (
<DropdownMenuRadioGroup
value={checkedKey}
onValueChange={(value) => {
section.entries.find((entry) => entry.kind === 'radio' && entry.key === value)?.onSelect()
}}
>
{section.entries.map(renderDesktopEntry)}
</DropdownMenuRadioGroup>
)
}
return section.entries.map(renderDesktopEntry)
}
const meter = contextUsage
? <ContextUsageMeter percentage={contextUsage.usagePercentage} className="absolute inset-x-0 bottom-0" />
: null
const desktopTrigger = (
<button
type="button"
aria-label={configName}
title={configName}
data-active={isAnySessionToggleActive ? 'true' : undefined}
className={TRIGGER_CLASS}
>
<span className="flex w-full min-w-0 items-center gap-1 text-left">
<SlidersHorizontal className={cn('h-3.5 w-3.5 shrink-0', isAnySessionToggleActive && 'text-highlight')} />
<span className="truncate">
<span style={{ color: agentStyleVars['--agent-color'] }}>{agentLabel}</span>
<span> · {modelName || 'Select model'}</span>
</span>
</span>
{(showVariant || usageLabel) && (
<span className="flex w-full min-w-0 items-center gap-1 text-[10px] leading-tight">
{showVariant && <span className="truncate capitalize text-highlight">{currentVariant}</span>}
{showVariant && usageLabel && (
<span aria-hidden="true" className="text-muted-foreground">·</span>
)}
{usageLabel && (
<span data-testid="composer-config-context-usage" className={cn('shrink-0 font-medium', usageTone)}>
{usageLabel}
</span>
)}
</span>
)}
{meter}
</button>
)
return (
<>
{isMobile ? (
<>
<button
type="button"
aria-label={configName}
title={configName}
data-active={isAnySessionToggleActive ? 'true' : undefined}
onClick={() => setOpen(true)}
className={cn(
getIconToggleButtonClassName(isAnySessionToggleActive),
'relative flex items-center justify-center size-11 p-0 overflow-hidden',
)}
>
<SlidersHorizontal className="h-5 w-5" />
{meter}
</button>
<BottomSheet
isOpen={open}
onClose={() => setOpen(false)}
ariaLabel="Session config"
heightClass="h-auto max-h-[85dvh]"
>
<BottomSheetHeader title="Session config" />
<BottomSheetContent>
<div role="menu" aria-label="Session config">
{sections.map((section, index) => (
<div key={section.key} className={index > 0 ? 'mt-2 border-t border-border pt-2' : ''}>
{section.label ? (
<div role="presentation" className="px-2 py-1 text-sm font-semibold text-muted-foreground">
{section.label}
</div>
) : null}
{section.entries.map((entry) => (
<button
key={entry.key}
type="button"
role={entry.kind === 'radio' ? 'menuitemradio' : entry.kind === 'checkbox' ? 'menuitemcheckbox' : 'menuitem'}
aria-checked={entry.kind === 'action' ? undefined : entry.checked}
disabled={entry.disabled}
aria-disabled={entry.disabled ? 'true' : undefined}
onClick={entry.onSelect}
className={cn(
'flex w-full min-h-11 items-center rounded-lg px-2 py-2 text-left text-sm hover:bg-accent',
entry.className,
)}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</button>
))}
</div>
))}
</div>
</BottomSheetContent>
</BottomSheet>
</>
) : (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>{desktopTrigger}</DropdownMenuTrigger>
<DropdownMenuContent
side="top"
align="start"
collisionPadding={8}
className="w-72 max-h-[70vh] overflow-y-auto"
>
{sections.map((section, index) => (
<Fragment key={section.key}>
{index > 0 ? <DropdownMenuSeparator /> : null}
{section.label ? <DropdownMenuLabel>{section.label}</DropdownMenuLabel> : null}
{renderDesktopSection(section)}
</Fragment>
))}
</DropdownMenuContent>
</DropdownMenu>
)}
<ModelQuickSelect
directory={directory}
open={modelPickerOpen}
onOpenChange={onModelPickerOpenChange}
session={modelSelectionSession}
contextUsage={contextUsage}
isCompacting={isCompacting}
onCompact={onCompact}
/>
{shouldShowSandboxResources(sandbox) ? (
<SessionSandboxResourcesDialog
sessionID={sessionID}
open={resourcesOpen}
onOpenChange={setResourcesOpen}
override={sandbox.resources}
effective={sandbox.effectiveResources!}
/>
) : null}
</>
)
})
@@ -1,102 +0,0 @@
import { describe, expect, it } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
SetSessionPermissionModeRequestSchema,
type SessionPermissionModeState,
} from '@opencode-manager/shared/schemas'
import type { FetchRoute, FetchRouteResult } from '@/test/fetchFake'
import { renderWithProviders } from '@/test/render'
import { PermissionModeToggle } from './PermissionModeToggle'
const baseState: SessionPermissionModeState = {
sessionId: 'ses_1',
rootSessionId: 'ses_1',
mode: 'ask',
lockedReason: null,
}
function renderToggle(initial: SessionPermissionModeState, getRespond?: FetchRoute['respond']) {
let state = initial
const modeUrl = `/api/session-permission-modes/${initial.sessionId}`
const routes: FetchRoute[] = [
{
method: 'GET',
path: modeUrl,
respond: getRespond ?? (() => ({ json: state })),
},
{
method: 'PUT',
path: modeUrl,
respond: (request) => {
const parsed = SetSessionPermissionModeRequestSchema.safeParse(request.body)
if (parsed.success) state = { ...state, mode: parsed.data.mode }
return { json: state }
},
},
]
return renderWithProviders(<PermissionModeToggle sessionID={initial.sessionId} directory="/repo" />, {
auth: false,
theme: false,
tts: false,
toaster: false,
serverId: 'srv_remote',
fetchRoutes: routes,
})
}
describe('PermissionModeToggle', () => {
it.each([
['ask', 'Permissions: follow configured rules', 'auto'],
['auto', 'Permissions: auto-accept all', 'ask'],
] as const)('switches a loaded %s mode to %s through the current server', async (mode, label, nextMode) => {
const user = userEvent.setup()
const { fetchFake } = renderToggle({ ...baseState, mode })
await user.click(await screen.findByRole('button', { name: label }))
await waitFor(() =>
expect(fetchFake.lastRequest('PUT', '/api/session-permission-modes/ses_1')?.body).toEqual({
directory: '/repo',
mode: nextMode,
serverId: 'srv_remote',
}),
)
})
it.each([
['child', 'Inherited from parent session'],
['schedule', "Scheduled runs use the schedule's permission configuration"],
] as const)('is disabled and labelled for %s-locked sessions', async (lockedReason, label) => {
renderToggle({ ...baseState, mode: 'auto', lockedReason })
expect(await screen.findByRole('button', { name: label })).toBeDisabled()
})
it('stays disabled and skips the write while the mode read is pending', async () => {
const user = userEvent.setup()
const { fetchFake } = renderToggle(
baseState,
() => new Promise<FetchRouteResult>(() => undefined),
)
const button = screen.getByRole('button', { name: 'Permissions: loading' })
expect(button).toBeDisabled()
await user.click(button)
expect(fetchFake.findRequests('PUT', '/api/session-permission-modes/ses_1')).toHaveLength(0)
})
it('stays disabled and reports unavailable when the mode read fails', async () => {
const user = userEvent.setup()
const { fetchFake } = renderToggle(baseState, () => ({ status: 500, json: { error: 'boom' } }))
const button = await screen.findByRole('button', { name: 'Permissions: unavailable' })
expect(button).toBeDisabled()
await user.click(button)
expect(fetchFake.findRequests('PUT', '/api/session-permission-modes/ses_1')).toHaveLength(0)
})
})
@@ -1,18 +0,0 @@
import { Shield, ShieldCheck } from 'lucide-react'
import { usePermissionModeToggle } from '@/hooks/usePermissionModeToggle'
import { IconToggleButton } from '@/components/ui/icon-toggle-button'
interface PermissionModeToggleProps {
sessionID: string
directory: string
}
export function PermissionModeToggle({ sessionID, directory }: PermissionModeToggleProps) {
const { isAuto, disabled, label, toggle } = usePermissionModeToggle(sessionID, directory)
return (
<IconToggleButton active={isAuto} label={label} disabled={disabled} onClick={toggle}>
{isAuto ? <ShieldCheck className="w-5 h-5" /> : <Shield className="w-5 h-5" />}
</IconToggleButton>
)
}
@@ -1,135 +0,0 @@
import { describe, expect, it } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
SetSessionSandboxRequestSchema,
type SessionSandboxState,
} from '@opencode-manager/shared/schemas'
import type { FetchRoute, FetchRouteResult } from '@/test/fetchFake'
import { renderWithProviders } from '@/test/render'
import { SessionSandboxMenu } from './SessionSandboxMenu'
const baseSandboxState: SessionSandboxState = {
sessionId: 'ses_1',
rootSessionId: 'ses_1',
sandboxed: false,
source: 'default',
resources: null,
effectiveResources: { cpus: 2, memoryMib: 4096 },
lockedReason: null,
available: true,
}
function renderMenu(overrides: Partial<SessionSandboxState> = {}, putRespond?: FetchRoute['respond']) {
let state: SessionSandboxState = { ...baseSandboxState, ...overrides }
const sandboxUrl = '/api/session-sandbox/ses_1'
const routes: FetchRoute[] = [
{ method: 'GET', path: sandboxUrl, respond: () => ({ json: state }) },
{
method: 'PUT',
path: sandboxUrl,
respond: (request) => {
if (putRespond) return putRespond(request)
const parsed = SetSessionSandboxRequestSchema.safeParse(request.body)
if (parsed.success) state = { ...state, ...parsed.data }
return { json: state }
},
},
]
return renderWithProviders(<SessionSandboxMenu sessionID="ses_1" />, {
auth: false,
theme: false,
tts: false,
toaster: false,
fetchRoutes: routes,
})
}
describe('SessionSandboxMenu', () => {
it('renders nothing when sandboxing is unavailable', async () => {
renderMenu({ available: false })
await waitFor(() =>
expect(screen.queryByRole('button', { name: /Sandbox:/ })).not.toBeInTheDocument(),
)
})
it.each([
[false, 'Sandbox: off'],
[true, 'Sandbox: on'],
] as const)('reflects the sandboxed=%s state in the trigger', async (sandboxed, label) => {
renderMenu({ sandboxed })
const trigger = await screen.findByRole('button', { name: label })
if (sandboxed) expect(trigger).toHaveClass('bg-highlight')
else expect(trigger).not.toHaveClass('bg-highlight')
})
it.each([
[false, 'Sandbox: off', 'false', { sandboxed: true }, 'Sandbox: on'],
[true, 'Sandbox: on', 'true', { sandboxed: false }, 'Sandbox: off'],
] as const)(
'toggles sandboxing from the %s state through the checkbox item',
async (sandboxed, label, checked, expectedBody, nextLabel) => {
const user = userEvent.setup()
const { fetchFake } = renderMenu({ sandboxed })
await user.click(await screen.findByRole('button', { name: label }))
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/ses_1')?.body).toEqual(expectedBody),
)
expect(await screen.findByRole('button', { name: nextLabel })).toBeInTheDocument()
},
)
it('hides the resources item when the session is not sandboxed', async () => {
const user = userEvent.setup()
renderMenu({ sandboxed: false })
await user.click(await screen.findByRole('button', { name: 'Sandbox: off' }))
await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
})
it('opens the resources dialog from the menu item', async () => {
const user = userEvent.setup()
renderMenu({ sandboxed: true, effectiveResources: { cpus: 2, memoryMib: 4096 } })
await user.click(await screen.findByRole('button', { name: 'Sandbox: on' }))
const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ })
await user.click(item)
expect(await screen.findByRole('dialog')).toBeInTheDocument()
expect(screen.getByLabelText('CPUs')).toHaveValue(2)
})
it('disables the checkbox and explains inheritance for a child session', async () => {
const user = userEvent.setup()
const { fetchFake } = renderMenu({ sandboxed: true, lockedReason: 'child' })
await user.click(await screen.findByRole('button', { name: /Inherited from parent session/ }))
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()
expect(fetchFake.findRequests('PUT', '/api/session-sandbox/ses_1')).toHaveLength(0)
})
it('keeps the trigger label when the toggle write fails', async () => {
const user = userEvent.setup()
renderMenu({ sandboxed: false }, () => new Promise<FetchRouteResult>(() => undefined))
await user.click(await screen.findByRole('button', { name: 'Sandbox: off' }))
await user.click(await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }))
await waitFor(() => expect(screen.getByRole('button', { name: 'Sandbox: off' })).toBeInTheDocument())
})
})
@@ -1,52 +0,0 @@
import { useState } from 'react'
import { Box } from 'lucide-react'
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { useSandboxToggle } from '@/hooks/useSandboxToggle'
import { shouldShowSandboxResources } from '@/lib/sandboxResources'
import { SandboxMenuItems } from '@/components/message/SandboxMenuItems'
import { SessionSandboxResourcesDialog } from '@/components/message/SessionSandboxResourcesDialog'
interface SessionSandboxMenuProps {
sessionID: string
}
export function SessionSandboxMenu({ sessionID }: SessionSandboxMenuProps) {
const sandbox = useSandboxToggle(sessionID)
const [resourcesOpen, setResourcesOpen] = useState(false)
if (!sandbox.available) return null
const label = `Sandbox: ${sandbox.isSandboxed ? 'on' : 'off'}${
sandbox.lockedReason === 'child' ? ` (${sandbox.label})` : ''
}`
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label={label}
title={label}
className={getIconToggleButtonClassName(sandbox.isSandboxed)}
>
<Box className="w-5 h-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" collisionPadding={8} className="w-64">
<SandboxMenuItems sandbox={sandbox} onOpenResources={() => setResourcesOpen(true)} />
</DropdownMenuContent>
</DropdownMenu>
{shouldShowSandboxResources(sandbox) ? (
<SessionSandboxResourcesDialog
sessionID={sessionID}
open={resourcesOpen}
onOpenChange={setResourcesOpen}
override={sandbox.resources}
effective={sandbox.effectiveResources!}
/>
) : null}
</>
)
}
@@ -1,13 +1,3 @@
import type { ReactNode } from 'react'
interface IconToggleButtonProps {
active: boolean
label: string
disabled?: boolean
onClick: () => void
children: ReactNode
}
export function getIconToggleButtonClassName(active: boolean): string {
return `p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 disabled:hover:scale-100 ${
active
@@ -15,19 +5,3 @@ export function getIconToggleButtonClassName(active: boolean): string {
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`
}
export function IconToggleButton({ active, label, disabled = false, onClick, children }: IconToggleButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-pressed={active}
aria-label={label}
title={label}
className={getIconToggleButtonClassName(active)}
>
{children}
</button>
)
}
+7 -3
View File
@@ -23,6 +23,7 @@ export interface PromptInputFixture {
isSessionActive?: boolean
isStreamingResponse?: boolean
mobile?: boolean
serverId?: string
stt?: 'enabled' | 'disabled' | 'unsupported'
settings?: Partial<UserPreferences>
agents?: AgentInfo[]
@@ -30,7 +31,9 @@ export interface PromptInputFixture {
commands?: CommandInfo[]
goal?: SessionGoalRead
permissionMode?: SessionPermissionModeState | null
permissionModeRead?: () => FetchRouteResult | Promise<FetchRouteResult>
sandbox?: SessionSandboxState
sandboxWrite?: () => FetchRouteResult | Promise<FetchRouteResult>
models?: RawModelFixture[]
deferProviders?: boolean
files?: string[]
@@ -259,7 +262,7 @@ export async function renderPromptInput(fixture: PromptInputFixture = {}) {
{
method: 'GET',
path: `/api/session-permission-modes/${sessionID}`,
respond: () => ({
respond: () => active.permissionModeRead?.() ?? ({
json: active.permissionMode ?? {
sessionId: sessionID,
rootSessionId: sessionID,
@@ -288,7 +291,7 @@ export async function renderPromptInput(fixture: PromptInputFixture = {}) {
{
method: 'PUT',
path: `/api/session-sandbox/${sessionID}`,
respond: () => ({ json: active.sandbox ?? { ...emptySandbox, sessionId: sessionID, rootSessionId: sessionID } }),
respond: () => active.sandboxWrite?.() ?? ({ json: active.sandbox ?? { ...emptySandbox, sessionId: sessionID, rootSessionId: sessionID } }),
},
]
@@ -297,13 +300,14 @@ export async function renderPromptInput(fixture: PromptInputFixture = {}) {
tts: true,
queryClient,
fetchRoutes: routes,
serverId: active.serverId,
})
const hasModels = (active.models ?? [DEFAULT_MODEL]).length > 0
if (active.deferProviders) {
await waitFor(() => expect(result.fetchFake.lastRequest('GET', '/api/opencode/api/provider')).toBeDefined())
} else if (hasModels) {
await screen.findByRole('button', { name: /context|Claude Sonnet 4\.5/ })
await screen.findByRole('button', { name: /context|Claude Sonnet 4\.5|^Session config/ })
} else {
await waitFor(() => {
expect(result.fetchFake.lastRequest('GET', '/api/opencode/api/model')).toBeDefined()