Merge pull request #494 from chriswritescode-dev/om-226-pwa-minimal-prompt-composer-with-a

feat(frontend): condense the prompt composer into one session config surface
This commit is contained in:
Chris Scott authored and GitHub committed 2026-11-27 22:09:09 -05:00
commit 5f4cf63f8b
27 files changed
+1752 -1741

No files matched your search

+1
View File
@@ -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",
@@ -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}
</>
)
}
@@ -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<PromptInputHandle>()
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 () => {
@@ -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 })
@@ -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<SessionPermissionModeState>
sandbox?: Partial<SessionSandboxState>
}
function withPermission(overrides: Partial<SessionPermissionModeState> = {}): SessionPermissionModeState {
return { ...basePermissionState, ...overrides }
}
function withSandbox(overrides: Partial<SessionSandboxState> = {}): 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<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')
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<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('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')
})
})
})
@@ -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')
})
@@ -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 () => {
+46 -90
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) => {
@@ -1274,7 +1267,26 @@ return (
{!isVoiceActive && (
<>
<div className="flex items-end gap-1.5 md:gap-2 mb-1.5 md:mb-2">
<div data-testid="composer-input-row" className="relative flex items-end gap-1.5 md:gap-2">
<ComposerActivityBar sessionID={sessionID} />
<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}
/>
<textarea
ref={textareaRef}
data-prompt-input
@@ -1318,10 +1330,27 @@ return (
<span className="whitespace-nowrap">{hasPendingPermissionForSession ? 'View' : (isStreamingResponse ? 'Queue' : 'Send')}</span>
</button>
)}
{showStopButton && (
<button
onClick={handleStop}
className="min-h-11 min-w-11 md:min-h-0 md:min-w-0 flex flex-shrink-0 items-center justify-center p-1.5 px-5 md:p-2 md:px-6 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 bg-destructive hover:bg-destructive/90 text-destructive-foreground border border-destructive/60 hover:border-destructive shadow-md shadow-destructive/30 hover:shadow-destructive/40 ring-1 ring-destructive/20 hover:ring-destructive/30"
title="Stop"
>
<SquareFill className="w-4 h-4 md:w-5 md:h-5" />
</button>
)}
<input
ref={fileInputRef}
type="file"
accept={ACCEPTED_FILE_TYPES.join(',')}
className="hidden"
onChange={handleFileInputChange}
/>
{showVoiceMic && !hasPromptContent && !showStopButton && renderVoiceMic()}
</div>
{imageAttachments.length > 0 && (
<div className="flex flex-wrap gap-2 px-2 py-2 mb-2">
<div className="mt-2 flex flex-wrap gap-2 px-2 py-2">
{imageAttachments.map((attachment) => (
<div
key={attachment.id}
@@ -1341,84 +1370,11 @@ return (
</div>
)}
<div data-testid="composer-controls-row" className="relative flex gap-1.5 md:gap-2 items-center justify-between">
<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}
/>
</>
)}
{showMobileKeys && (
<div data-testid="composer-keys-row" className="mt-1.5 flex">
{renderMobileKeys()}
</div>
<div className="flex items-center gap-1.5 md:gap-2 flex-shrink-0">
{showStopButton && (
<button
onClick={handleStop}
className="hidden md:block p-1.5 px-5 md:p-2 md:px-6 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 bg-destructive hover:bg-destructive/90 text-destructive-foreground border border-destructive/60 hover:border-destructive shadow-md shadow-destructive/30 hover:shadow-destructive/40 ring-1 ring-destructive/20 hover:ring-destructive/30"
title="Stop"
>
<SquareFill className="w-4 h-4 md:w-5 md:h-5" />
</button>
)}
<input
ref={fileInputRef}
type="file"
accept={ACCEPTED_FILE_TYPES.join(',')}
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,691 @@
import { memo, useEffect, useId, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'
import { Box, Check, ChevronLeft, ChevronRight, 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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { ContextUsageMeter } from '@/components/session/ContextUsageMeter'
import { ModelPicker } from '@/components/model/ModelPicker'
import { SessionSandboxResourcesDialog } from './SessionSandboxResourcesDialog'
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
}
type SelectableAgent = Pick<AgentInfo, 'id' | 'name' | 'color' | 'description'>
type SessionMenuView = 'main' | 'agent' | 'model'
type SessionMenuItemRole = 'menuitem' | 'menuitemradio' | 'menuitemcheckbox'
const BACK_BUTTON_CLASS =
'flex shrink-0 items-center justify-center rounded-full border border-border bg-muted text-foreground/80 hover:bg-accent'
const backButtonClassName = (mobile: boolean) => cn(BACK_BUTTON_CLASS, mobile ? 'h-11 w-11' : 'h-9 w-9')
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 chipClassName = (mobile: boolean) =>
cn(
'inline-flex shrink-0 items-center justify-center rounded-md border text-xs font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring',
mobile ? 'min-h-9 px-3' : 'h-7 px-2',
)
const rowClassName = (mobile: boolean) =>
cn(
'flex w-full min-w-0 items-center gap-2 rounded-md pl-2 pr-2 text-left text-sm text-foreground outline-none transition-colors hover:bg-accent focus:bg-accent',
mobile ? 'min-h-11 py-2' : 'py-1.5',
)
const menuItems = (container: HTMLElement) =>
Array.from(container.querySelectorAll<HTMLElement>('[role^="menuitem"]')).filter(
(item) => !item.matches(':disabled') && item.getAttribute('aria-disabled') !== 'true',
)
const handleMenuKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const items = menuItems(event.currentTarget)
if (items.length === 0) return
const currentIndex = items.findIndex((item) => item === document.activeElement)
const lastIndex = items.length - 1
let nextIndex: number | null = null
if (event.key === 'ArrowDown') {
nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % items.length
} else if (event.key === 'ArrowUp') {
nextIndex = currentIndex < 0 ? lastIndex : (currentIndex + items.length - 1) % items.length
} else if (event.key === 'Home') {
nextIndex = 0
} else if (event.key === 'End') {
nextIndex = lastIndex
}
if (nextIndex === null) return
event.preventDefault()
items[nextIndex]?.focus()
}
interface SessionMenuItemProps {
role: SessionMenuItemRole
checked?: boolean
disabled?: boolean
onSelect: () => void
className?: string
style?: CSSProperties
title?: string
ariaLabel?: string
children: ReactNode
}
function SessionMenuItem({
role,
checked,
disabled,
onSelect,
className,
style,
title,
ariaLabel,
children,
}: SessionMenuItemProps) {
return (
<button
type="button"
role={role}
aria-checked={role === 'menuitem' ? undefined : checked}
aria-label={ariaLabel}
title={title}
disabled={disabled}
aria-disabled={disabled ? 'true' : undefined}
onClick={onSelect}
style={style}
className={cn('min-w-0', className)}
>
{children}
</button>
)
}
function SwitchPill({ checked }: { checked: boolean }) {
return (
<span
aria-hidden="true"
data-state={checked ? 'checked' : 'unchecked'}
className={cn(
'pointer-events-none inline-flex h-4 w-7 shrink-0 items-center rounded-full border transition-colors',
checked ? 'border-success bg-success' : 'border-border bg-input',
)}
>
<span
data-state={checked ? 'checked' : 'unchecked'}
className={cn(
'pointer-events-none block h-2.5 w-2.5 rounded-full bg-background shadow-sm transition-transform',
checked ? 'translate-x-3.5' : 'translate-x-0.5',
)}
/>
</span>
)
}
interface ConfigSectionProps {
label?: string
children: ReactNode
}
function ConfigSection({ label, children }: ConfigSectionProps) {
const labelId = useId()
return (
<div
role={label ? 'group' : undefined}
aria-labelledby={label ? labelId : undefined}
className="flex flex-col gap-1"
>
{label ? (
<div id={labelId} className="px-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
{label}
</div>
) : null}
{children}
</div>
)
}
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 [view, setView] = useState<SessionMenuView>('main')
const [resourcesOpen, setResourcesOpen] = useState(false)
useEffect(() => {
if (!modelPickerOpen) return
setOpen(true)
setView('model')
}, [modelPickerOpen])
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 primaryAgents = getPrimaryAgents(agents)
const handleOpenChange = (nextOpen: boolean) => {
setOpen(nextOpen)
if (nextOpen) return
setView('main')
onModelPickerOpenChange(false)
}
const handleModelBack = () => {
setView('main')
onModelPickerOpenChange(false)
}
const handleModelSelected = () => {
setView('main')
onModelPickerOpenChange(false)
}
const renderMainView = (mobile: boolean) => {
const sections: Array<{ key: string; node: ReactNode }> = []
sections.push({
key: 'agent',
node: (
<ConfigSection label="Agent">
<SessionMenuItem
role="menuitem"
ariaLabel={`Change agent: ${agentLabel}`}
onSelect={() => setView('agent')}
className={rowClassName(mobile)}
>
<span
aria-hidden="true"
className="h-2.5 w-2.5 shrink-0 rounded-full"
style={{ backgroundColor: agentStyleVars['--agent-color'] }}
/>
<span className="min-w-0 flex-1 truncate">{agentLabel}</span>
<ChevronRight aria-hidden="true" className="h-4 w-4 shrink-0 text-muted-foreground" />
</SessionMenuItem>
</ConfigSection>
),
})
sections.push({
key: 'model',
node: (
<ConfigSection label="Model">
<SessionMenuItem
role="menuitem"
ariaLabel={`Change model: ${modelName || 'Select model'}`}
onSelect={() => setView('model')}
className={rowClassName(mobile)}
>
<span className="min-w-0 flex-1 truncate">{modelName || 'Select model'}</span>
<ChevronRight aria-hidden="true" className="h-4 w-4 shrink-0 text-muted-foreground" />
</SessionMenuItem>
</ConfigSection>
),
})
if (hasVariants) {
sections.push({
key: 'variant',
node: (
<ConfigSection label="Variant">
<div className="flex flex-wrap gap-1 px-2">
<SessionMenuItem
role="menuitemradio"
checked={currentVariant === undefined}
onSelect={clearVariant}
className={cn(
chipClassName(mobile),
currentVariant === undefined
? 'border-primary bg-primary text-primary-foreground'
: 'border-border/60 text-muted-foreground hover:border-foreground/30 hover:text-foreground',
)}
>
Default
</SessionMenuItem>
{availableVariants.map((variant) => (
<SessionMenuItem
key={variant}
role="menuitemradio"
checked={currentVariant === variant}
onSelect={() => setVariant(variant)}
className={cn(
chipClassName(mobile),
'capitalize',
currentVariant === variant
? 'border-primary bg-primary text-primary-foreground'
: 'border-border/60 text-muted-foreground hover:border-foreground/30 hover:text-foreground',
)}
>
{variant}
</SessionMenuItem>
))}
</div>
</ConfigSection>
),
})
}
sections.push({
key: 'context',
node: (
<ConfigSection label="Context">
<div className="flex items-center gap-2 px-2">
<div className="flex min-w-0 flex-1 flex-col gap-1">
{usageLabel ? (
<>
<span className={cn('truncate text-xs font-medium', usageTone)}>{usageLabel}</span>
{contextUsage ? (
<ContextUsageMeter percentage={contextUsage.usagePercentage} className="h-1" />
) : null}
</>
) : (
<span className="text-xs text-muted-foreground">No context usage yet</span>
)}
</div>
<SessionMenuItem
role="menuitem"
ariaLabel="Compact session"
disabled={isCompacting}
onSelect={() => {
onCompact()
handleOpenChange(false)
}}
className={cn(
rowClassName(mobile),
'w-auto shrink-0 justify-center rounded-md border border-border/70 px-2 py-1 text-xs font-medium',
mobile ? 'min-h-9' : 'min-h-0',
)}
>
Compact
</SessionMenuItem>
</div>
</ConfigSection>
),
})
if (directory !== undefined) {
sections.push({
key: 'session',
node: (
<ConfigSection label="Session">
<SessionMenuItem
role="menuitemcheckbox"
checked={permission.isAuto}
disabled={permission.disabled}
onSelect={permission.toggle}
className={rowClassName(mobile)}
>
<span className="shrink-0 text-muted-foreground">
{permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">Accept all permissions</span>
{permission.disabled ? (
<span className="text-xs leading-snug text-muted-foreground">{permission.label}</span>
) : null}
</span>
<SwitchPill checked={permission.isAuto} />
</SessionMenuItem>
{isLocalServer && sandbox.available ? (
<SessionMenuItem
role="menuitemcheckbox"
checked={sandbox.isSandboxed}
disabled={sandbox.disabled}
onSelect={sandbox.toggle}
className={rowClassName(mobile)}
>
<span className="shrink-0 text-muted-foreground">
<Box className="h-4 w-4" />
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">Sandbox commands</span>
{sandbox.disabled ? (
<span className="text-xs leading-snug text-muted-foreground">{sandbox.label}</span>
) : null}
</span>
<SwitchPill checked={sandbox.isSandboxed} />
</SessionMenuItem>
) : null}
{isLocalServer && sandbox.available && shouldShowSandboxResources(sandbox) ? (
<SessionMenuItem
role="menuitem"
onSelect={() => {
handleOpenChange(false)
setTimeout(() => setResourcesOpen(true), 0)
}}
className={rowClassName(mobile)}
>
<span className="shrink-0 text-muted-foreground">
<Cpu className="h-4 w-4" />
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">Sandbox resources…</span>
<span className="text-xs leading-snug text-muted-foreground">
{formatSandboxResources(sandbox.effectiveResources!)}
{sandbox.resources ? ' · custom' : ''}
</span>
</span>
<ChevronRight aria-hidden="true" className="h-4 w-4 shrink-0 text-muted-foreground" />
</SessionMenuItem>
) : null}
<SessionMenuItem
role="menuitemcheckbox"
checked={goalArmed}
disabled={goalDisabled}
onSelect={onToggleGoal}
className={rowClassName(mobile)}
>
<span className="shrink-0 text-muted-foreground">
<Target className="h-4 w-4" />
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">Goal mode</span>
{goalDisabled ? (
<span className="text-xs leading-snug text-muted-foreground">{goalLabel}</span>
) : null}
</span>
<SwitchPill checked={goalArmed} />
</SessionMenuItem>
</ConfigSection>
),
})
}
sections.push({
key: 'attach',
node: (
<ConfigSection>
<SessionMenuItem
role="menuitem"
onSelect={() => {
onAttachFile()
handleOpenChange(false)
}}
className={rowClassName(mobile)}
>
<Paperclip aria-hidden="true" className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="truncate">Attach image or PDF</span>
</SessionMenuItem>
</ConfigSection>
),
})
return (
<div className="flex flex-col gap-2">
{sections.map((section, index) => (
<div key={section.key} className={index > 0 ? 'border-t border-border/50 pt-2' : undefined}>
{section.node}
</div>
))}
</div>
)
}
const renderAgentView = (mobile: boolean) => (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2 px-1 pb-1">
<button
type="button"
onClick={() => setView('main')}
className={backButtonClassName(mobile)}
aria-label="Back to session config"
>
<ChevronLeft className="h-5 w-5" />
</button>
<h2 className="truncate text-sm font-semibold text-foreground">Agent</h2>
</div>
<div role="menu" aria-label="Agent" onKeyDown={handleMenuKeyDown}>
{primaryAgents.map((agent) => {
const checked = agent.id.toLowerCase() === currentAgent.toLowerCase()
return (
<SessionMenuItem
key={agent.id}
role="menuitemradio"
checked={checked}
title={agent.description || undefined}
onSelect={() => {
onAgentChange(agent.id)
setView('main')
}}
className={rowClassName(mobile)}
>
<span
aria-hidden="true"
className="h-2.5 w-2.5 shrink-0 rounded-full"
style={{ backgroundColor: getAgentStyleVars(agent.id, agent.color)['--agent-color'] }}
/>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">{capitalize(agent.name)}</span>
{agent.description ? (
<span className="truncate text-xs leading-snug text-muted-foreground">{agent.description}</span>
) : null}
</span>
{checked ? <Check aria-hidden="true" className="h-4 w-4 shrink-0 text-highlight" /> : null}
</SessionMenuItem>
)
})}
</div>
</div>
)
const renderModelView = () => (
<ModelPicker
directory={directory}
session={modelSelectionSession}
onSelect={handleModelSelected}
onBack={handleModelBack}
active
/>
)
const meter = contextUsage
? <ContextUsageMeter percentage={contextUsage.usagePercentage} className="absolute inset-x-0 bottom-0" />
: null
const gutterCardClassName = isMobile
? undefined
: cn(
'@min-[86rem]/composer:absolute @min-[86rem]/composer:bottom-0 @min-[86rem]/composer:right-full @min-[86rem]/composer:mr-4',
'@min-[86rem]/composer:h-10 @min-[86rem]/composer:w-[min(22rem,calc((100cqw_-_56rem)/2_-_2.5rem))]',
'@min-[86rem]/composer:items-center @min-[86rem]/composer:justify-start',
'@min-[86rem]/composer:rounded-lg @min-[86rem]/composer:border-border @min-[86rem]/composer:bg-background/95',
'@min-[86rem]/composer:p-2.5 @min-[86rem]/composer:shadow-none',
'@min-[86rem]/composer:hover:scale-100 @min-[86rem]/composer:hover:bg-accent @min-[86rem]/composer:active:scale-100',
)
const renderTrigger = (onClick?: () => void) => (
<button
type="button"
aria-label={configName}
title={configName}
data-active={isAnySessionToggleActive ? 'true' : undefined}
onClick={onClick}
className={cn(
getIconToggleButtonClassName(isAnySessionToggleActive),
'relative flex shrink-0 items-center justify-center overflow-hidden p-0',
isMobile ? 'size-11' : 'size-9',
gutterCardClassName,
)}
>
<SlidersHorizontal
className={cn(isMobile ? 'h-5 w-5' : 'h-4 w-4', !isMobile && '@min-[86rem]/composer:hidden')}
/>
<span
className={cn(
'hidden w-full min-w-0 flex-row items-center gap-1.5 whitespace-nowrap text-left',
!isMobile && '@min-[86rem]/composer:flex',
)}
>
<span
aria-hidden="true"
className="h-2 w-2 shrink-0 rounded-full"
style={{ backgroundColor: agentStyleVars['--agent-color'] }}
/>
<span className="shrink-0 text-xs font-medium text-foreground">{agentLabel}</span>
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
· {modelName || 'Select model'}
</span>
{showVariant && currentVariant ? (
<span className="shrink-0 text-[11px] text-muted-foreground">{capitalize(currentVariant)}</span>
) : null}
<span className={cn('shrink-0 text-[11px] font-medium', usageLabel ? usageTone : 'text-muted-foreground')}>
{usageLabel ?? 'No context yet'}
</span>
</span>
{isAnySessionToggleActive ? (
<span aria-hidden="true" className="absolute right-1.5 top-1.5 h-1.5 w-1.5 rounded-full bg-highlight" />
) : null}
{meter}
</button>
)
return (
<>
{isMobile ? (
<>
{renderTrigger(() => {
setView('main')
setOpen(true)
})}
<BottomSheet
isOpen={open}
onClose={() => handleOpenChange(false)}
ariaLabel="Session config"
heightClass="h-[70dvh] max-h-[720px]"
>
<BottomSheetHeader title="Session config" />
<BottomSheetContent
className={view === 'model' ? 'flex min-h-0 flex-1 flex-col overflow-hidden p-0 pb-safe' : undefined}
>
{view === 'main' ? (
<div role="menu" aria-label="Session config" onKeyDown={handleMenuKeyDown}>
{renderMainView(true)}
</div>
) : view === 'agent' ? (
renderAgentView(true)
) : (
renderModelView()
)}
</BottomSheetContent>
</BottomSheet>
</>
) : (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>{renderTrigger()}</PopoverTrigger>
<PopoverContent
side="top"
align="start"
collisionPadding={8}
avoidCollisions={false}
className="h-[min(70vh,560px,var(--radix-popover-content-available-height))] w-[22rem] max-w-[calc(100vw-1rem)] overflow-hidden p-0"
>
{view === 'main' ? (
<div role="menu" aria-label="Session config" onKeyDown={handleMenuKeyDown} className="h-full overflow-y-auto p-1.5">
{renderMainView(false)}
</div>
) : view === 'agent' ? (
<div className="h-full overflow-y-auto p-1.5">
{renderAgentView(false)}
</div>
) : (
<div className="h-full overflow-hidden">
{renderModelView()}
</div>
)}
</PopoverContent>
</Popover>
)}
{shouldShowSandboxResources(sandbox) ? (
<SessionSandboxResourcesDialog
sessionID={sessionID}
open={resourcesOpen}
onOpenChange={setResourcesOpen}
override={sandbox.resources}
effective={sandbox.effectiveResources!}
/>
) : null}
</>
)
})
@@ -1,19 +0,0 @@
import type { ReactNode } from 'react'
interface ToolMenuItemContentProps {
icon: ReactNode
title: string
detail?: string
}
export function ToolMenuItemContent({ icon, title, detail }: ToolMenuItemContentProps) {
return (
<span className="flex items-start gap-2">
<span className="mt-0.5 shrink-0">{icon}</span>
<span className="flex min-w-0 flex-col">
<span>{title}</span>
{detail ? <span className="text-xs text-muted-foreground">{detail}</span> : null}
</span>
</span>
)
}
@@ -1,17 +1,16 @@
import { useState } from 'react'
import type { ComponentProps } from 'react'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { buildServerDirectoryKey } from '@opencode-manager/shared/schemas'
import { ModelQuickSelect } from './ModelQuickSelect'
import { ModelPicker } from './ModelPicker'
import { useModelStore, locationAgentKey } from '@/stores/modelStore'
import { installElementScrollMetrics, installWindowSize } from '@/test/browserFakes'
import { installElementScrollMetrics } from '@/test/browserFakes'
import { renderWithProviders } from '@/test/render'
import type { FetchRoute } from '@/test/fetchFake'
type QuickSelectProps = ComponentProps<typeof ModelQuickSelect>
type ModelPickerTestProps = ComponentProps<typeof ModelPicker>
interface Selection {
providerID: string
@@ -121,28 +120,10 @@ function selectionRoutes(state: QuickState): FetchRoute[] {
]
}
function QuickSelectHarness({
initial,
bind,
}: {
initial: Partial<QuickSelectProps>
bind: (update: (next: Partial<QuickSelectProps>) => void) => void
}) {
const [props, setProps] = useState(initial)
bind((next) => setProps((current) => ({ ...current, ...next })))
return <ModelQuickSelect {...props} open={props.open ?? true} />
}
async function renderQuickSelect(props: Partial<QuickSelectProps> = {}, state: QuickState = {}) {
async function renderModelPicker(props: Partial<ModelPickerTestProps> = {}, state: QuickState = {}) {
if (state.model) useModelStore.setState({ newSessionPicks: { [modelDirectoryKey]: state.model } })
let update: (next: Partial<QuickSelectProps>) => void = () => undefined
const result = renderWithProviders(
<QuickSelectHarness
initial={props}
bind={(nextUpdate) => {
update = nextUpdate
}}
/>,
<ModelPicker active onBack={() => undefined} {...props} />,
{
auth: false,
theme: false,
@@ -153,14 +134,7 @@ async function renderQuickSelect(props: Partial<QuickSelectProps> = {}, state: Q
await waitFor(() => expect(result.fetchFake.lastRequest('GET', '/api/opencode/api/model')).toBeDefined())
await waitFor(() => expect(result.queryClient.isFetching()).toBe(0))
return {
...result,
update: async (next: Partial<QuickSelectProps>) => {
await act(async () => {
update(next)
})
},
}
return result
}
function selection(providerID: string, modelID: string): Selection {
@@ -190,19 +164,6 @@ function findDarkOnlyClassOffenders(root: HTMLElement) {
)
}
async function openSelector(user: ReturnType<typeof userEvent.setup>, state: QuickState = {}) {
renderWithProviders(
<ModelQuickSelect>
<span>Select model</span>
</ModelQuickSelect>,
{ auth: false, theme: false, toaster: false, fetchRoutes: selectionRoutes(state) },
)
await user.click(screen.getByText('Select model'))
return screen.findByRole('dialog', { name: 'Select model' })
}
function focusDetachedTextarea() {
const textarea = document.createElement('textarea')
document.body.appendChild(textarea)
@@ -210,24 +171,22 @@ function focusDetachedTextarea() {
return textarea
}
function mobileModelList() {
function providerModelList() {
const lists = Array.from(document.querySelectorAll('.overflow-y-auto.px-4.pb-4'))
const list = lists.find((element) => !element.classList.contains('pt-2'))
if (!list) throw new Error('No mobile model list found')
if (!list) throw new Error('No provider model list found')
return list
}
function lastModelStateRequest(fetchFake: Awaited<ReturnType<typeof renderQuickSelect>>['fetchFake']) {
function lastModelStateRequest(fetchFake: Awaited<ReturnType<typeof renderModelPicker>>['fetchFake']) {
return fetchFake.lastRequest('POST', '/api/providers/model-state')?.body
}
describe('ModelQuickSelect theme tokens', () => {
describe('ModelPicker theme tokens', () => {
it('renders the quick view with theme tokens instead of dark-only classes', async () => {
const user = userEvent.setup()
const dialog = await openSelector(user)
const { container } = await renderModelPicker()
expect(dialog).toHaveClass('bg-popover')
expect(findDarkOnlyClassOffenders(dialog)).toEqual([])
expect(findDarkOnlyClassOffenders(container)).toEqual([])
const moreModels = screen.getByRole('button', { name: /More models/ })
expect(moreModels).toHaveClass('text-foreground')
@@ -235,52 +194,44 @@ describe('ModelQuickSelect theme tokens', () => {
it('renders the provider view with theme tokens instead of dark-only classes', async () => {
const user = userEvent.setup()
const dialog = await openSelector(user)
const { container } = await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
expect(findDarkOnlyClassOffenders(dialog)).toEqual([])
expect(findDarkOnlyClassOffenders(container)).toEqual([])
})
})
describe('ModelQuickSelect controlled open', () => {
it('uses the controlled open prop as the source of truth', async () => {
const onOpenChange = vi.fn()
const { update } = await renderQuickSelect({ open: false, onOpenChange })
expect(screen.queryByRole('dialog', { name: 'Select model' })).not.toBeInTheDocument()
await update({ open: true })
expect(screen.getByRole('dialog', { name: 'Select model' })).toBeInTheDocument()
})
it('renders only the sheet without a trigger when no children are provided', async () => {
await renderQuickSelect({ open: true })
expect(screen.getByRole('dialog', { name: 'Select model' })).toBeInTheDocument()
expect(document.querySelector('[data-model-select-trigger]')).toBeNull()
})
it('resets the internal navigation state when the sheet is closed through the component', async () => {
describe('ModelPicker header', () => {
it('returns to the config panel from the quick list back arrow', async () => {
const user = userEvent.setup()
const onOpenChange = vi.fn()
await renderQuickSelect({ onOpenChange })
const onBack = vi.fn()
await renderModelPicker({ onBack })
await user.click(screen.getByRole('button', { name: 'Back to session config' }))
expect(onBack).toHaveBeenCalledTimes(1)
})
it('walks back from a provider to the provider list and then to the quick list', async () => {
const user = userEvent.setup()
await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
expect(screen.getByPlaceholderText('Search models...')).toBeInTheDocument()
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
expect(screen.getAllByText('Claude Sonnet 4').length).toBeGreaterThan(0)
await user.keyboard('{Escape}')
await user.click(screen.getByRole('button', { name: 'Back to quick models' }))
expect(screen.getByRole('button', { name: /Anthropic 2 models/ })).toBeInTheDocument()
expect(onOpenChange).toHaveBeenCalledWith(false)
await user.click(screen.getByRole('button', { name: 'Back to quick models' }))
expect(screen.getByRole('button', { name: /More models/ })).toBeInTheDocument()
expect(screen.queryByPlaceholderText('Search models...')).not.toBeInTheDocument()
})
})
describe('ModelQuickSelect quick view', () => {
describe('ModelPicker quick view', () => {
it('lists every valid favorite in catalog order', async () => {
await renderQuickSelect({}, { favorite: [selection('anthropic', 'claude-sonnet-4'), selection('openai', 'gpt-5')] })
await renderModelPicker({}, { favorite: [selection('anthropic', 'claude-sonnet-4'), selection('openai', 'gpt-5')] })
const section = sectionFor('Favorites')
expect(section.textContent).toContain('Claude Sonnet 4')
@@ -289,7 +240,7 @@ describe('ModelQuickSelect quick view', () => {
})
it('keeps a favorite listed when it is also the default model', async () => {
await renderQuickSelect(
await renderModelPicker(
{},
{
favorite: [selection('anthropic', 'claude-sonnet-4'), selection('openai', 'gpt-5')],
@@ -303,7 +254,7 @@ describe('ModelQuickSelect quick view', () => {
})
it('lists the valid recents that are not favorites', async () => {
await renderQuickSelect(
await renderModelPicker(
{},
{
favorite: [selection('anthropic', 'claude-sonnet-4')],
@@ -317,7 +268,7 @@ describe('ModelQuickSelect quick view', () => {
})
it('keeps the active model listed with its check mark', async () => {
await renderQuickSelect(
await renderModelPicker(
{},
{
favorite: [selection('anthropic', 'claude-sonnet-4')],
@@ -331,7 +282,7 @@ describe('ModelQuickSelect quick view', () => {
})
it('shows the first catalog models under Models when there are no favorites or recents', async () => {
await renderQuickSelect()
await renderModelPicker()
const section = sectionFor('Models')
expect(section.textContent).toContain('Go Model One')
@@ -340,22 +291,9 @@ describe('ModelQuickSelect quick view', () => {
expect(section.textContent).not.toContain('GPT-5')
})
it('shows the catalog name of an active model whose provider is not in the provider sections', async () => {
await renderQuickSelect(
{},
{
providers: [...defaultProviders, { id: 'legacy', name: 'Legacy', activation: 'disabled' }],
models: [...defaultModels, { id: 'gpt-5-legacy', providerID: 'legacy', name: 'GPT-5 Legacy' }],
model: selection('legacy', 'gpt-5-legacy'),
},
)
expect(screen.getByText('GPT-5 Legacy')).toBeInTheDocument()
})
it('writes the favorite and remove-recent changes to the server', async () => {
const user = userEvent.setup()
const { fetchFake } = await renderQuickSelect(
const { fetchFake } = await renderModelPicker(
{},
{
favorite: [selection('anthropic', 'claude-sonnet-4')],
@@ -379,10 +317,10 @@ describe('ModelQuickSelect quick view', () => {
})
})
describe('ModelQuickSelect more models', () => {
describe('ModelPicker more models', () => {
it('lists providers in catalog order', async () => {
const user = userEvent.setup()
await renderQuickSelect()
await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
@@ -394,7 +332,7 @@ describe('ModelQuickSelect more models', () => {
it('keeps a favorite visible in its provider list and count', async () => {
const user = userEvent.setup()
await renderQuickSelect({}, { favorite: [selection('openai', 'gpt-5')] })
await renderModelPicker({}, { favorite: [selection('openai', 'gpt-5')] })
await user.click(screen.getByRole('button', { name: /More models/ }))
@@ -408,7 +346,7 @@ describe('ModelQuickSelect more models', () => {
it('searches into one flat list with favorites first', async () => {
const user = userEvent.setup()
await renderQuickSelect({}, { favorite: [selection('openai', 'gpt-5')] })
await renderModelPicker({}, { favorite: [selection('openai', 'gpt-5')] })
await user.click(screen.getByRole('button', { name: /More models/ }))
await user.type(screen.getByPlaceholderText('Search models...'), '5')
@@ -422,7 +360,7 @@ describe('ModelQuickSelect more models', () => {
it('scopes the search to the selected provider', async () => {
const user = userEvent.setup()
await renderQuickSelect()
await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
@@ -432,9 +370,10 @@ describe('ModelQuickSelect more models', () => {
expect(screen.queryByText('GPT-5')).not.toBeInTheDocument()
})
it('selects a model and records it as recent', async () => {
it('selects a model, records it as recent and notifies the panel', async () => {
const user = userEvent.setup()
const { fetchFake } = await renderQuickSelect({}, { favorite: [selection('anthropic', 'claude-sonnet-4')] })
const onSelect = vi.fn()
const { fetchFake } = await renderModelPicker({ onSelect }, { favorite: [selection('anthropic', 'claude-sonnet-4')] })
const section = sectionFor('Favorites')
await user.click(within(section).getByRole('button', { name: /Claude Sonnet 4/ }))
@@ -442,12 +381,13 @@ describe('ModelQuickSelect more models', () => {
expect(lastModelStateRequest(fetchFake)).toEqual({
recent: selection('anthropic', 'claude-sonnet-4'),
})
expect(onSelect).toHaveBeenCalledTimes(1)
})
})
describe('ModelQuickSelect keyboard navigation', () => {
describe('ModelPicker keyboard navigation', () => {
it('moves the active quick row with ArrowDown and selects it with Enter', async () => {
const { fetchFake } = await renderQuickSelect({}, { model: selection('opencode-go', 'go-1') })
const { fetchFake } = await renderModelPicker({}, { model: selection('opencode-go', 'go-1') })
const textarea = focusDetachedTextarea()
@@ -460,20 +400,18 @@ describe('ModelQuickSelect keyboard navigation', () => {
})
it('clamps at the first quick row and jumps to the last with End', async () => {
const { fetchFake } = await renderQuickSelect({}, { model: selection('opencode-go', 'go-1') })
const { fetchFake } = await renderModelPicker({}, { model: selection('opencode-go', 'go-1') })
const dialog = screen.getByRole('dialog', { name: 'Select model' })
fireEvent.keyDown(dialog, { key: 'ArrowUp' })
fireEvent.keyDown(dialog, { key: 'Enter' })
fireEvent.keyDown(document.body, { key: 'ArrowUp' })
fireEvent.keyDown(document.body, { key: 'Enter' })
await waitFor(() =>
expect(lastModelStateRequest(fetchFake)).toEqual({ recent: selection('opencode-go', 'go-1') }),
)
fetchFake.reset()
fireEvent.keyDown(dialog, { key: 'End' })
fireEvent.keyDown(dialog, { key: 'Enter' })
fireEvent.keyDown(document.body, { key: 'End' })
fireEvent.keyDown(document.body, { key: 'Enter' })
await waitFor(() =>
expect(lastModelStateRequest(fetchFake)).toEqual({ recent: selection('anthropic', 'claude-sonnet-4') }),
)
@@ -481,7 +419,7 @@ describe('ModelQuickSelect keyboard navigation', () => {
it('navigates the search results with the arrow keys and Enter', async () => {
const user = userEvent.setup()
const { fetchFake } = await renderQuickSelect()
const { fetchFake } = await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
const searchInput = screen.getByPlaceholderText('Search models...')
@@ -496,7 +434,7 @@ describe('ModelQuickSelect keyboard navigation', () => {
})
it('does not select a model when Enter is pressed on a row button', async () => {
const { fetchFake } = await renderQuickSelect({}, { favorite: [selection('anthropic', 'claude-sonnet-4')] })
const { fetchFake } = await renderModelPicker({}, { favorite: [selection('anthropic', 'claude-sonnet-4')] })
const star = screen.getByRole('button', { name: /favorites/ })
star.focus()
@@ -506,8 +444,8 @@ describe('ModelQuickSelect keyboard navigation', () => {
expect(lastModelStateRequest(fetchFake)).toBeUndefined()
})
it('does not intercept arrow keys when the sheet is closed', async () => {
renderWithProviders(<ModelQuickSelect />, {
it('does not intercept arrow keys while inactive', async () => {
renderWithProviders(<ModelPicker active={false} onBack={() => undefined} />, {
auth: false,
theme: false,
toaster: false,
@@ -519,10 +457,9 @@ describe('ModelQuickSelect keyboard navigation', () => {
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
})
it('ignores keyboard navigation when the mobile provider list hides the models', async () => {
it('ignores keyboard navigation while the provider list hides the models', async () => {
const user = userEvent.setup()
installWindowSize(500)
const { fetchFake } = await renderQuickSelect()
const { fetchFake } = await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
@@ -534,10 +471,9 @@ describe('ModelQuickSelect keyboard navigation', () => {
expect(lastModelStateRequest(fetchFake)).toBeUndefined()
})
it('navigates the provider models that are visible on mobile', async () => {
it('navigates the provider models after drilling into a provider', async () => {
const user = userEvent.setup()
installWindowSize(500)
const { fetchFake } = await renderQuickSelect()
const { fetchFake } = await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
@@ -555,7 +491,7 @@ describe('ModelQuickSelect keyboard navigation', () => {
})
it('ignores keydown events while an IME composition is active', async () => {
const { fetchFake } = await renderQuickSelect({}, { model: selection('opencode-go', 'go-1') })
const { fetchFake } = await renderModelPicker({}, { model: selection('opencode-go', 'go-1') })
const textarea = focusDetachedTextarea()
@@ -567,7 +503,7 @@ describe('ModelQuickSelect keyboard navigation', () => {
it('does not select while the deferred search query is still catching up', async () => {
const user = userEvent.setup()
const { fetchFake } = await renderQuickSelect()
const { fetchFake } = await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
@@ -580,16 +516,15 @@ describe('ModelQuickSelect keyboard navigation', () => {
expect(lastModelStateRequest(fetchFake)).toBeUndefined()
})
it('scrolls the mobile provider model list to follow the active row', async () => {
it('scrolls the provider model list to follow the active row', async () => {
const user = userEvent.setup()
installWindowSize(500)
const scrollFake = installElementScrollMetrics({ clientHeight: 60 })
await renderQuickSelect()
await renderModelPicker()
await user.click(screen.getByRole('button', { name: /More models/ }))
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
const list = mobileModelList()
const list = providerModelList()
expect(scrollFake.getScrollTop(list)).toBe(0)
const textarea = focusDetachedTextarea()
@@ -599,80 +534,16 @@ describe('ModelQuickSelect keyboard navigation', () => {
})
})
describe('ModelQuickSelect context strip', () => {
const session = { id: 'ses_1' }
const usage = { totalTokens: 12000, usagePercentage: 6, contextLimit: 200000 }
it('shows the used and limit tokens with the percentage and meter', async () => {
await renderQuickSelect({ session, contextUsage: usage, onCompact: vi.fn() })
const summary = screen.getByTestId('context-usage-summary')
expect(summary).toHaveTextContent('12k / 200k · 6%')
expect(summary).toHaveClass('text-success')
expect(summary).toHaveAttribute('aria-label', 'context 6% used')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '6%' })
})
it('tints the summary with the warning and destructive tones', async () => {
const { update } = await renderQuickSelect({ session, contextUsage: { ...usage, usagePercentage: 60 } })
expect(screen.getByTestId('context-usage-summary')).toHaveClass('text-warning')
await update({ contextUsage: { ...usage, usagePercentage: 85 } })
expect(screen.getByTestId('context-usage-summary')).toHaveClass('text-destructive')
})
it('compacts the session from the strip', async () => {
const user = userEvent.setup()
const onCompact = vi.fn()
await renderQuickSelect({ session, contextUsage: usage, onCompact })
await user.click(screen.getByRole('button', { name: 'Compact session' }))
expect(onCompact).toHaveBeenCalledTimes(1)
})
it('disables compaction while compacting or without a session', async () => {
const onCompact = vi.fn()
const { update } = await renderQuickSelect({ session, contextUsage: usage, isCompacting: true, onCompact })
expect(screen.getByRole('button', { name: 'Compact session' })).toBeDisabled()
await update({ session: undefined })
expect(screen.getByRole('button', { name: 'Compact session' })).toBeDisabled()
expect(onCompact).not.toHaveBeenCalled()
})
it('falls back to tokens and an empty meter without a known limit', async () => {
await renderQuickSelect({
session,
contextUsage: { totalTokens: 12000, usagePercentage: null, contextLimit: null },
})
expect(screen.getByTestId('context-usage-summary')).toHaveTextContent('12k tokens')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '0%' })
})
it('omits the strip without context usage', async () => {
await renderQuickSelect({ session })
expect(screen.queryByTestId('context-usage-strip')).not.toBeInTheDocument()
})
})
describe('ModelQuickSelect model descriptions', () => {
describe('ModelPicker model descriptions', () => {
it('formats the context limit like the context strip', async () => {
await renderQuickSelect({}, { model: selection('anthropic', 'claude-sonnet-4') })
await renderModelPicker({}, { favorite: [selection('anthropic', 'claude-sonnet-4')] })
expect(screen.getByText('Anthropic · 200k context', { selector: 'p' })).toBeInTheDocument()
expect(screen.getByText('Anthropic · 200k context')).toBeInTheDocument()
})
it('formats million-token limits without a trailing decimal', async () => {
await renderQuickSelect({}, { model: selection('anthropic', 'claude-opus-5-5-fast') })
await renderModelPicker({}, { favorite: [selection('anthropic', 'claude-opus-5-5-fast')] })
expect(screen.getByText('Anthropic · 1M context', { selector: 'p' })).toBeInTheDocument()
expect(screen.getByText('Anthropic · 1M context')).toBeInTheDocument()
})
})
@@ -1,40 +1,21 @@
import { memo, useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { Check, ChevronDown, ChevronLeft, ChevronRight, Search, Star, Trash2, X, type LucideIcon } from 'lucide-react'
import type { ReactNode } from 'react'
import { Check, ChevronLeft, ChevronRight, Search, Star, Trash2, type LucideIcon } from 'lucide-react'
import { useModelSelection, type ModelSelectionSession } from '@/hooks/useModelSelection'
import { useMobile } from '@/hooks/useMobile'
import { useModelSections } from '@/hooks/useModelSections'
import { useVariants } from '@/hooks/useVariants'
import { modelSelectionRef, type Model } from '@/api/providers'
import { BottomSheet } from '@/components/ui/bottom-sheet'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { ContextUsageMeter } from '@/components/session/ContextUsageMeter'
import { buildModelSections, filterModelSections, type ModelOption } from '@/lib/modelSections'
import { isTextEntryElement } from '@/lib/domTargets'
import {
CONTEXT_USAGE_TEXT_CLASS,
contextUsageAccessibleLabel,
contextUsageTone,
formatCompactTokens,
type ContextUsage,
} from '@/lib/contextUsage'
import { cn } from '@/lib/utils'
import { formatCompactTokens } from '@/lib/contextUsage'
interface ModelQuickSelectProps {
interface ModelPickerProps {
directory?: string
disabled?: boolean
children?: React.ReactNode
open?: boolean
onOpenChange?: (open: boolean) => void
session?: ModelSelectionSession
contextUsage?: ContextUsage | null
isCompacting?: boolean
onCompact?: () => void
onSelect?: () => void
onBack: () => void
active: boolean
}
interface ModelListItem {
@@ -61,7 +42,7 @@ interface ProviderListItem {
interface VirtualizedListProps<T> {
items: T[]
itemHeight: number
renderItem: (item: T, index: number) => React.ReactNode
renderItem: (item: T, index: number) => ReactNode
getKey: (item: T) => string
emptyLabel: string
className?: string
@@ -75,52 +56,12 @@ const VIRTUAL_LIST_OVERSCAN = 8
const EMPTY_MODELS: ModelListItem[] = []
const EMPTY_PROVIDER_ITEMS: ProviderListItem[] = []
const ICON_BUTTON_CLASS =
'flex h-9 w-9 items-center justify-center rounded-full border border-border bg-muted text-foreground/80 hover:bg-accent'
'flex h-11 w-11 shrink-0 items-center justify-center rounded-full border border-border bg-muted text-foreground/80 hover:bg-accent md:h-9 md:w-9'
function formatModelCount(count: number) {
return `${count} ${count === 1 ? 'model' : 'models'}`
}
interface ContextUsageStripProps {
usage: ContextUsage
onCompact?: () => void
compactDisabled: boolean
}
function ContextUsageStrip({ usage, onCompact, compactDisabled }: ContextUsageStripProps) {
const percentage = usage.usagePercentage
const toneClass = CONTEXT_USAGE_TEXT_CLASS[contextUsageTone(percentage)]
const summary = usage.contextLimit === null || percentage === null
? `${formatCompactTokens(usage.totalTokens)} tokens`
: `${formatCompactTokens(usage.totalTokens)} / ${formatCompactTokens(usage.contextLimit)} · ${percentage}%`
return (
<div data-testid="context-usage-strip" className="shrink-0 border-b border-border px-4 pb-2">
<ContextUsageMeter percentage={percentage} />
<div className="mt-1.5 flex items-center gap-3">
<span
data-testid="context-usage-summary"
aria-label={contextUsageAccessibleLabel(usage)}
className={`min-w-0 truncate text-xs font-medium ${toneClass}`}
>
{summary}
</span>
{onCompact && (
<button
type="button"
onClick={onCompact}
disabled={compactDisabled}
aria-label="Compact session"
className="ml-auto shrink-0 rounded text-xs font-medium text-info hover:underline disabled:cursor-not-allowed disabled:opacity-40 disabled:no-underline"
>
Compact
</button>
)}
</div>
</div>
)
}
function VirtualizedList<T>({
items,
itemHeight,
@@ -220,28 +161,20 @@ function VirtualizedList<T>({
)
}
export const ModelQuickSelect = memo(function ModelQuickSelect({
export const ModelPicker = memo(function ModelPicker({
directory,
disabled,
children,
open,
onOpenChange,
session,
contextUsage,
isCompacting = false,
onCompact,
}: ModelQuickSelectProps) {
const [internalIsOpen, setInternalIsOpen] = useState(false)
const isOpen = open ?? internalIsOpen
onSelect,
onBack,
active,
}: ModelPickerProps) {
const [showAllModels, setShowAllModels] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
const deferredSearchQuery = useDeferredValue(searchQuery)
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
const [activeIndex, setActiveIndex] = useState(0)
const quickListRef = useRef<HTMLDivElement>(null)
const isMobile = useMobile()
const { model, modelString, info, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory, session)
const { modelString, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
const { providers, sections } = useModelSections(directory)
@@ -277,7 +210,6 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
const rowsByKey = new Map<string, ModelListItem>()
const modelsByProviderId = new Map<string, ModelListItem[]>()
const providerItems: ProviderListItem[] = []
const allModels: ModelListItem[] = []
for (const section of catalogSections) {
if (!section.providerID) continue
@@ -285,10 +217,9 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
for (const item of items) rowsByKey.set(item.key, item)
providerItems.push({ id: section.providerID, label: section.title, count: items.length })
modelsByProviderId.set(section.providerID, items)
allModels.push(...items)
}
return { rowsByKey, modelsByProviderId, providerItems, allModels }
return { rowsByKey, modelsByProviderId, providerItems }
}, [showAllModels, catalogSections, toModelListItem])
const quickSections = useMemo((): QuickModelSection[] => {
@@ -339,16 +270,14 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
[browseData, selectedProviderId]
)
const browseModels = selectedProviderId ? selectedProviderModels : browseData?.allModels ?? EMPTY_MODELS
const navigableItems = useMemo((): ModelListItem[] => {
if (showAllModels) {
if (isSearching) return searchResults
if (isMobile && !selectedProviderId) return EMPTY_MODELS
return browseModels
if (!selectedProviderId) return EMPTY_MODELS
return selectedProviderModels
}
return quickSections.flatMap((section) => section.models)
}, [showAllModels, isSearching, isMobile, selectedProviderId, searchResults, browseModels, quickSections])
}, [showAllModels, isSearching, selectedProviderId, searchResults, selectedProviderModels, quickSections])
const quickSectionOffsets = useMemo(() => {
const offsets = new Map<string, number>()
@@ -360,7 +289,7 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
return offsets
}, [quickSections])
const activeResetKey = `${isOpen}|${showAllModels}|${isSearching ? deferredSearchQuery : ''}|${selectedProviderId ?? ''}`
const activeResetKey = `${active}|${showAllModels}|${isSearching ? deferredSearchQuery : ''}|${selectedProviderId ?? ''}`
const navigableItemsRef = useRef(navigableItems)
navigableItemsRef.current = navigableItems
const modelStringRef = useRef(modelString)
@@ -397,10 +326,11 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
setShowAllModels(false)
setSearchQuery('')
setSelectedProviderId(null)
}, [setModel])
onSelect?.()
}, [setModel, onSelect])
useEffect(() => {
if (!isOpen) return
if (!active) return
const handleKeyDown = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey || event.altKey) return
@@ -445,30 +375,13 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
document.addEventListener('keydown', handleKeyDown, true)
return () => document.removeEventListener('keydown', handleKeyDown, true)
}, [isOpen, activeIndex, navigableItems, handleModelSelect])
const handleOpenChange = (nextOpen: boolean) => {
if (open === undefined) {
setInternalIsOpen(nextOpen)
}
if (!nextOpen) {
setShowAllModels(false)
setSearchQuery('')
setSelectedProviderId(null)
}
onOpenChange?.(nextOpen)
}
}, [active, activeIndex, navigableItems, handleModelSelect])
const handleProviderSelect = (providerID: string) => {
setSelectedProviderId(providerID)
setSearchQuery('')
}
const handleCompact = () => {
onCompact?.()
handleOpenChange(false)
}
const getDescription = (item: ModelListItem) => {
const context = item.model?.limit?.context
if (context) {
@@ -535,28 +448,14 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
)
}
const selectedModelItem = useMemo((): ModelListItem | null => {
if (!model) return null
const key = modelString ?? modelSelectionRef(model)
const option = catalogOptions.find((candidate) => candidate.value === key)
if (option) return toModelListItem(option)
const providerName = providers.find((provider) => provider.id === model.providerID)?.name ?? model.providerID
return {
providerID: model.providerID,
modelID: model.modelID,
key,
displayName: info?.name ?? model.modelID,
providerName,
}
}, [model, modelString, info, providers, catalogOptions, toModelListItem])
const renderProviderOption = (provider: ProviderListItem) => {
return (
<button
key={provider.id}
type="button"
onClick={() => handleProviderSelect(provider.id)}
className="flex w-full items-center gap-3 rounded-xl py-2.5 text-left transition-colors hover:bg-accent"
aria-label={`${provider.label} ${formatModelCount(provider.count)}`}
className="flex min-h-11 w-full items-center gap-3 rounded-xl py-2.5 text-left transition-colors hover:bg-accent"
>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">{provider.label}</span>
@@ -567,46 +466,6 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
)
}
const renderSidebarProviderOption = (provider: ProviderListItem) => {
return (
<button
key={provider.id}
type="button"
onClick={() => handleProviderSelect(provider.id)}
className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
selectedProviderId === provider.id
? 'bg-highlight/20 text-highlight font-medium'
: 'text-muted-foreground hover:bg-accent'
}`}
>
<div className="truncate">{provider.label}</div>
<div className="text-xs text-muted-foreground">{formatModelCount(provider.count)}</div>
</button>
)
}
const renderVariantMenuItems = () => {
if (!hasVariants) return null
return (
<>
<DropdownMenuLabel>Variant</DropdownMenuLabel>
<DropdownMenuItem onClick={() => clearVariant()} className={!currentVariant ? 'text-highlight' : ''}>
Default
{!currentVariant && <Check className="ml-auto h-4 w-4" />}
</DropdownMenuItem>
{availableVariants.map(variant => (
<DropdownMenuItem key={variant} onClick={() => setVariant(variant)} className={currentVariant === variant ? 'text-highlight' : ''}>
<span className="capitalize">{variant}</span>
{currentVariant === variant && <Check className="ml-auto h-4 w-4" />}
</DropdownMenuItem>
))}
</>
)
}
const selectedVariantLabel = currentVariant ? currentVariant : 'Default'
const handleMoreModelsBack = () => {
if (selectedProviderId) {
setSelectedProviderId(null)
@@ -617,184 +476,112 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
setShowAllModels(false)
}
const selectedModelLabel = selectedModelItem ? getPrimaryLabel(selectedModelItem) : 'Select model'
const selectedModelDescription = selectedModelItem ? getDescription(selectedModelItem) : 'Choose a model'
return (
<>
{children && (
<span className="contents" onClick={() => !disabled && handleOpenChange(true)}>
{children}
</span>
)}
<BottomSheet
isOpen={isOpen}
onClose={() => handleOpenChange(false)}
heightClass="h-[70dvh] max-h-[720px]"
className="z-[300] border-border bg-popover text-foreground shadow-2xl md:mx-auto md:max-w-lg"
ariaLabel="Select model"
>
{contextUsage && (
<ContextUsageStrip
usage={contextUsage}
onCompact={onCompact ? handleCompact : undefined}
compactDisabled={!session?.id || isCompacting}
/>
)}
<div className={`flex items-center justify-between gap-2 px-4 ${showAllModels ? 'pb-2 pt-2' : 'pb-3 pt-0'}`}>
{showAllModels ? (
<>
<button
type="button"
onClick={handleMoreModelsBack}
className={`${ICON_BUTTON_CLASS} shrink-0`}
aria-label="Back to quick models"
>
<ChevronLeft className="h-5 w-5" />
</button>
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="Search models..."
className="h-9 border-border bg-muted pl-9 text-sm text-foreground placeholder:text-placeholder"
autoComplete="off"
name="model-search"
/>
</div>
</>
) : (
<>
<button
type="button"
onClick={() => handleOpenChange(false)}
className={ICON_BUTTON_CLASS}
aria-label="Close model selector"
>
<X className="h-5 w-5" />
</button>
<div className="min-w-0 flex-1 px-3 text-center">
<h2 className="truncate text-base font-semibold tracking-tight">
{selectedModelLabel}
<span className="ml-1.5 inline-block h-2 w-2 rounded-full bg-highlight" />
</h2>
<p className="truncate text-xs text-muted-foreground">
{currentVariant ? `${selectedModelDescription} · ${currentVariant}` : selectedModelDescription}
</p>
</div>
{hasVariants && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
disabled={!model && !hasVariants}
className="flex h-9 w-24 items-center justify-center gap-1 rounded-md border border-border bg-muted px-1.5 text-sm font-medium capitalize text-muted-foreground hover:bg-accent disabled:opacity-30"
aria-label={`Current variant: ${selectedVariantLabel}`}
>
<span className="truncate">{selectedVariantLabel}</span>
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="z-[350] min-w-56">
{renderVariantMenuItems()}
</DropdownMenuContent>
</DropdownMenu>
)}
</>
)}
</div>
<div className="flex h-full min-h-0 flex-col overflow-hidden">
<div className={cn('flex shrink-0 items-center gap-2 px-4', showAllModels ? 'py-2' : 'pb-2 pt-2')}>
{showAllModels ? (
isSearching ? (
<div className="flex-1 overflow-hidden min-h-0">
<>
<button
type="button"
onClick={handleMoreModelsBack}
className={ICON_BUTTON_CLASS}
aria-label="Back to quick models"
>
<ChevronLeft className="h-5 w-5" />
</button>
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="Search models..."
className="h-11 border-border bg-muted pl-9 text-sm text-foreground placeholder:text-placeholder md:h-9"
autoComplete="off"
name="model-search"
/>
</div>
</>
) : (
<>
<button
type="button"
onClick={onBack}
className={ICON_BUTTON_CLASS}
aria-label="Back to session config"
>
<ChevronLeft className="h-5 w-5" />
</button>
<h2 className="truncate text-base font-semibold tracking-tight text-foreground">Model</h2>
</>
)}
</div>
{showAllModels ? (
isSearching ? (
<div className="flex-1 overflow-hidden min-h-0">
<VirtualizedList
items={searchResults}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item, index) => renderModelOption(item, index)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4 pt-2"
resetKey={`${selectedProviderId ?? 'all'}:${deferredSearchQuery}`}
activeIndex={activeIndex}
/>
</div>
) : (
<div className="flex-1 overflow-hidden min-h-0">
{selectedProviderId ? (
<VirtualizedList
items={searchResults}
items={selectedProviderModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item, index) => renderModelOption(item, index)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4 pt-2"
resetKey={`${selectedProviderId ?? 'all'}:${deferredSearchQuery}`}
className="px-4 pb-4"
resetKey={selectedProviderId}
activeIndex={activeIndex}
/>
</div>
) : (
<div className="flex-1 flex overflow-hidden min-h-0">
<div className="hidden md:flex md:flex-col w-48 lg:w-56 border-r border-border overflow-y-auto flex-shrink-0">
<div className="p-3 space-y-1">
{providerItems.map(renderSidebarProviderOption)}
) : (
<div className="h-full overflow-y-auto px-4 pb-4">
<div className="space-y-1">
{providerItems.map(renderProviderOption)}
</div>
{providerItems.length === 0 && (
<div className="py-10 text-center text-sm text-muted-foreground">No providers found</div>
)}
</div>
<div className="flex-1 flex flex-col overflow-hidden min-w-0">
<div className="hidden md:block flex-1 overflow-hidden min-h-0">
<VirtualizedList
items={browseModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item, index) => renderModelOption(item, index)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4 pt-2"
resetKey={selectedProviderId ?? 'all'}
activeIndex={activeIndex}
/>
</div>
<div className="md:hidden flex-1 overflow-hidden min-h-0">
{selectedProviderId ? (
<VirtualizedList
items={selectedProviderModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item, index) => renderModelOption(item, index)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4"
resetKey={selectedProviderId}
activeIndex={activeIndex}
/>
) : (
<div className="h-full overflow-y-auto px-4 pb-4">
<div className="space-y-1">
{providerItems.map(renderProviderOption)}
</div>
{providerItems.length === 0 && (
<div className="py-10 text-center text-sm text-muted-foreground">No providers found</div>
)}
</div>
)}
</div>
</div>
</div>
)
) : (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden pb-safe pt-0">
<div ref={quickListRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
{quickSections.map(section => (
<section key={section.title}>
<h3 className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
{section.icon ? <section.icon className="h-3.5 w-3.5" /> : null}
{section.title}
</h3>
<div className="space-y-1">
{section.models.map((item, index) => renderModelOption(item, (quickSectionOffsets.get(section.title) ?? 0) + index))}
</div>
</section>
))}
</div>
<div className="flex-shrink-0 border-t border-border">
<button
type="button"
onClick={() => setShowAllModels(true)}
className="flex w-full items-center justify-between bg-card px-6 py-4 text-left text-sm font-semibold text-foreground transition-colors hover:bg-accent active:bg-card"
>
<span>More models</span>
<ChevronRight className="h-5 w-5 text-muted-foreground" />
</button>
</div>
)}
</div>
)}
</BottomSheet>
</>
)
) : (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden pb-safe pt-0">
<div ref={quickListRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
{quickSections.map(section => (
<section key={section.title}>
<h3 className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
{section.icon ? <section.icon className="h-3.5 w-3.5" /> : null}
{section.title}
</h3>
<div className="space-y-1">
{section.models.map((item, index) => renderModelOption(item, (quickSectionOffsets.get(section.title) ?? 0) + index))}
</div>
</section>
))}
</div>
<div className="flex-shrink-0 border-t border-border">
<button
type="button"
onClick={() => setShowAllModels(true)}
className="flex w-full items-center justify-between bg-card px-6 py-4 text-left text-sm font-semibold text-foreground transition-colors hover:bg-accent active:bg-card"
>
<span>More models</span>
<ChevronRight className="h-5 w-5 text-muted-foreground" />
</button>
</div>
</div>
)}
</div>
)
})
@@ -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>
)
}
+28
View File
@@ -0,0 +1,28 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-[150] min-w-[8rem] rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent }
+1 -13
View File
@@ -6,7 +6,6 @@ import { MessageThread } from "@/components/message/MessageThread";
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
import { X, CornerUpLeft, GitBranch, ArrowDown, Server } from "lucide-react";
import { SquareFill } from "@/components/ui/square-fill";
import { Header } from "@/components/ui/header";
import { Badge } from "@/components/ui/badge";
import { getServerProjectPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
@@ -895,7 +894,7 @@ export function SessionDetail() {
<div
data-testid="prompt-overlay"
className={cn(
"absolute left-0 right-0 flex justify-center",
"@container/composer absolute left-0 right-0 flex justify-center",
isFormOpen && "top-0 flex-col items-center justify-end pointer-events-none md:pt-3",
)}
style={{ bottom: inputBottomOffset }}
@@ -935,17 +934,6 @@ export function SessionDetail() {
<span className="text-sm font-medium hidden sm:inline">Clear</span>
</button>
)}
{isSessionActive && (
<button
type="button"
onClick={handleInterruptSession}
title="Stop"
aria-label="Stop"
className="md:hidden p-3 rounded-xl transition-all duration-200 active:scale-95 hover:scale-105 bg-destructive hover:bg-destructive/90 text-destructive-foreground border border-destructive/60 shadow-lg shadow-destructive/30"
>
<SquareFill className="w-5 h-5" />
</button>
)}
</div>
)}
{showScrollButton && !isFormSheetOpen && (
@@ -322,13 +322,14 @@ describe('SessionDetail command actions', () => {
expect(screen.queryByPlaceholderText('Search messages')).not.toBeInTheDocument()
})
it('opens the model picker from the models command', async () => {
it('opens the config surface in the model view from the models command', async () => {
renderSessionPage({ session: baseSession() })
await waitForComposer()
submitComposer('/models')
expect(await screen.findByRole('dialog', { name: 'Select model' })).toBeInTheDocument()
expect(await screen.findByRole('heading', { name: 'Model' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /More models/ })).toBeInTheDocument()
})
it.each([
@@ -34,12 +34,15 @@ function paddingBottom() {
return transcriptContainer().style.paddingBottom
}
function floatingStopButton() {
const button = screen.getAllByTitle('Stop').find((candidate) => candidate.classList.contains('md:hidden'))
if (!button) throw new Error('the floating stop button is not rendered')
return button
function stopButton() {
return screen.getByTitle('Stop')
}
const VIEWPORTS = [
{ name: 'mobile', width: 480 },
{ name: 'desktop', width: 900 },
]
let scrollMetrics: ElementScrollMetricsFake
let resizeObserver: ResizeObserverFake
@@ -125,12 +128,13 @@ describe('SessionDetail scroll and composer affordances', () => {
})
})
it('interrupts the active session from the floating stop button', async () => {
it.each(VIEWPORTS)('interrupts the active session from the composer stop button on $name', async ({ width }) => {
installWindowSize(width)
const { fetchFake } = renderSessionPage({ activeSessions: ['session-1'] })
await waitForComposer()
await screen.findAllByTitle('Stop')
await screen.findByTitle('Stop')
fireEvent.click(floatingStopButton())
fireEvent.click(stopButton())
await waitFor(() => {
expect(
@@ -139,15 +143,18 @@ describe('SessionDetail scroll and composer affordances', () => {
})
})
it('shows the floating stop button while the session is active', async () => {
it.each(VIEWPORTS)('renders a single composer stop button while the session is active on $name', async ({ width }) => {
installWindowSize(width)
renderSessionPage({ activeSessions: ['session-1'] })
await waitForComposer()
await screen.findAllByTitle('Stop')
await screen.findByTitle('Stop')
expect(floatingStopButton()).toBeInTheDocument()
expect(screen.getAllByTitle('Stop')).toHaveLength(1)
expect(stopButton()).toBeInTheDocument()
})
it('hides the stop button while the session is idle', async () => {
it.each(VIEWPORTS)('hides the stop button while the session is idle on $name', async ({ width }) => {
installWindowSize(width)
renderSessionPage()
await waitForComposer()
+9 -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,16 @@ 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: active.serverId ? /context|Claude Sonnet 4\.5|^Session config/ : /context|Claude Sonnet 4\.5/,
})
} else {
await waitFor(() => {
expect(result.fetchFake.lastRequest('GET', '/api/opencode/api/model')).toBeDefined()
+68
View File
@@ -156,6 +156,9 @@ importers:
'@radix-ui/react-label':
specifier: ^2.1.7
version: 2.1.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-popover':
specifier: ^1.1.15
version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-select':
specifier: ^2.2.6
version: 2.2.6(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
@@ -1326,6 +1329,7 @@ packages:
resolution: {integrity: sha512-IG887NHjPJEw5D1dvNl9jPbcwNFREFKj2fnqEjdrwCnDRywtjNL7k7GgTo24NNlyMAZAq0OkoM0M0Sn6ex/Adg==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@opentui/core-linux-arm64@0.8.4':
resolution: {integrity: sha512-VGnBN3ItBwZog109wtPIou8pn93TseZwA5OZ05X2PYIYPw+IC6mVeO2Dn0qwwozLBDxeyH3ydbHMFlwzS4/fLg==}
@@ -1336,6 +1340,7 @@ packages:
resolution: {integrity: sha512-FAiH7wMt/ZbpP2w6TL62deNExTg5w6mujKUBSK89+gJV8FN4jk/K2xz9f522aYhC6SdbpyIKwS0oGIJldYLkcg==}
cpu: [x64]
os: [linux]
libc: [musl]
'@opentui/core-linux-x64@0.8.4':
resolution: {integrity: sha512-N/uxyaPpWkCZlDXz3fgHMfMuj1L3IVZ/xZ4JifUc4NW9bwa/CYWFJ5J5jBoy2QsAIqoqo8/OD3iFpXR4o12mNQ==}
@@ -1410,48 +1415,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxlint/binding-linux-arm64-musl@1.93.0':
resolution: {integrity: sha512-zM8Fd/K8sqGvsBcJBZ3oVZ3ctGWbszA08IaGt5gFFF5RcunppAI/ZnAXbouABvnWeJ//S44KKlfPZnDDbeiphg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxlint/binding-linux-ppc64-gnu@1.93.0':
resolution: {integrity: sha512-7qKCnvhZKDXJG2pdbLazd2hw4FxjJHbZOFrrbzyy5PdHfPLH9vnNUa1le01A8uItZuYKPBPncH+HCoEiFT4SgA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxlint/binding-linux-riscv64-gnu@1.93.0':
resolution: {integrity: sha512-2pgulxC6G8V5wE750NJE/fRkf9aO6i6yoj10wyaR2EdiNtan4OemsOtsQ0ZTXGdY8Q3IoTmlND3GYvjJsvikYg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxlint/binding-linux-riscv64-musl@1.93.0':
resolution: {integrity: sha512-yWsn6Gg2PnGG5jlyDz5+pHGiMTMiy4adaa4WRMzDgzB8efaShk1JMmTHIBSVLQMh0tYXRs4CN5uJCO79r4Mi4g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxlint/binding-linux-s390x-gnu@1.93.0':
resolution: {integrity: sha512-WCn5plwp/ezS2RDPQKp0/EXEVRr9/dDexUdRKmsMFqzNM5xBSZ1wbsi3PuMk1VfkMRnI5BuazCsziCWMXRDOlw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxlint/binding-linux-x64-gnu@1.93.0':
resolution: {integrity: sha512-F2CGjb9LAkzH+IYTZSzd1klQ1vk5z6Utjax64WeLByCkYXbVDbsun+Oy2hLfW2MDSKCvW+jwy/9ld0EPgdeu+A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxlint/binding-linux-x64-musl@1.93.0':
resolution: {integrity: sha512-plf5DE2objcG8Tf7mXRuRa8tT8rzDkpjqXQtKoGsKHWkpgsialbON1+cCtoSEUTVbQUjXvuAm8vV9+3rR0yCBw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxlint/binding-openharmony-arm64@1.93.0':
resolution: {integrity: sha512-Kp2yJrKvoTe9FfKdO/xwLNUbs2bYTMKx0+aoQD1s0h/Tx0kSgtHSdGmrk8tTKdluosjFbo88qYRIaNIX43AfFw==}
@@ -1705,6 +1718,19 @@ packages:
'@types/react-dom':
optional: true
'@radix-ui/react-popover@1.1.15':
resolution: {integrity: sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-popper@1.2.8':
resolution: {integrity: sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==}
peerDependencies:
@@ -2027,56 +2053,67 @@ packages:
resolution: {integrity: sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==}
cpu: [arm]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-arm-musleabihf@4.54.0':
resolution: {integrity: sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==}
cpu: [arm]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-arm64-gnu@4.54.0':
resolution: {integrity: sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-arm64-musl@4.54.0':
resolution: {integrity: sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-loong64-gnu@4.54.0':
resolution: {integrity: sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==}
cpu: [loong64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-ppc64-gnu@4.54.0':
resolution: {integrity: sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-riscv64-gnu@4.54.0':
resolution: {integrity: sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-riscv64-musl@4.54.0':
resolution: {integrity: sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-s390x-gnu@4.54.0':
resolution: {integrity: sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-x64-gnu@4.54.0':
resolution: {integrity: sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-x64-musl@4.54.0':
resolution: {integrity: sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==}
cpu: [x64]
os: [linux]
libc: [musl]
'@rollup/rollup-openharmony-arm64@4.54.0':
resolution: {integrity: sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==}
@@ -2233,24 +2270,28 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tailwindcss/oxide-linux-arm64-musl@4.1.18':
resolution: {integrity: sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tailwindcss/oxide-linux-x64-gnu@4.1.18':
resolution: {integrity: sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tailwindcss/oxide-linux-x64-musl@4.1.18':
resolution: {integrity: sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tailwindcss/oxide-wasm32-wasi@4.1.18':
resolution: {integrity: sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==}
@@ -3820,24 +3861,28 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
lightningcss-linux-arm64-musl@1.30.2:
resolution: {integrity: sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
lightningcss-linux-x64-gnu@1.30.2:
resolution: {integrity: sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
lightningcss-linux-x64-musl@1.30.2:
resolution: {integrity: sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
lightningcss-win32-arm64-msvc@1.30.2:
resolution: {integrity: sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==}
@@ -6763,6 +6808,29 @@ snapshots:
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-popover@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-context': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-id': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-slot': 1.2.3(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.7)(react@19.2.3)
aria-hidden: 1.2.6
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
react-remove-scroll: 2.7.2(@types/react@19.2.7)(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-popper@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@floating-ui/react-dom': 2.1.6(react-dom@19.2.3(react@19.2.3))(react@19.2.3)