feat(frontend): condense the prompt composer into one session config surface

This commit is contained in:
Chris Scott committed 2026-11-27 21:58:57 -05:00
1 parent 86794e896b
commit c586bcb4ad
12 files changed
+875 -889

No files matched your search

@@ -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 () => {
@@ -130,17 +130,16 @@ describe('PromptInput composer layout', () => {
})
const trigger = await screen.findByRole('button', { name: /^Session config: .*Claude Sonnet 4\.5, context 42% used/ })
const usage = screen.getByTestId('composer-config-context-usage')
const meter = screen.getByTestId('context-usage-meter')
expect(trigger).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: {
@@ -148,9 +147,8 @@ describe('PromptInput composer layout', () => {
},
})
const usage = await screen.findByTestId('composer-config-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 () => {
@@ -160,7 +158,7 @@ describe('PromptInput composer layout', () => {
},
})
await screen.findByTestId('composer-config-context-usage')
await screen.findByRole('button', { name: /^Session config: .*context 130% used/ })
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '100%' })
})
@@ -172,7 +170,7 @@ describe('PromptInput composer layout', () => {
},
})
expect(await screen.findByTestId('composer-config-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%' })
})
@@ -187,15 +185,13 @@ describe('PromptInput composer layout', () => {
},
})
const usage = await screen.findByTestId('composer-config-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: /^Session config: .*Claude Sonnet 4\.5/ })).toBeInTheDocument()
expect(screen.queryByTestId('composer-config-context-usage')).not.toBeInTheDocument()
expect(screen.queryByTestId('context-usage-meter')).not.toBeInTheDocument()
})
})
@@ -1,8 +1,8 @@
import { createRef } from 'react'
import { describe, expect, it, vi } from 'vitest'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { SessionGoalRead } from '@opencode-manager/shared/opencode'
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'
@@ -56,6 +56,18 @@ function withSandbox(overrides: Partial<SessionSandboxState> = {}): SessionSandb
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
@@ -86,15 +98,50 @@ describe.each([
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', 'p-0')
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 } }],
@@ -265,19 +312,20 @@ describe.each([
expect(click).toHaveBeenCalledTimes(1)
})
it('switches the agent radio and sends with the selected agent', async () => {
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(plan).toHaveAttribute('aria-checked', 'true')
expect(build).toHaveAttribute('aria-checked', 'false')
expect(await screen.findByRole('menuitem', { name: /Change agent: Plan/ })).toBeInTheDocument()
await user.keyboard('{Escape}')
fireEvent.change(promptTextarea(), { target: { value: 'hello' } })
@@ -290,13 +338,35 @@ describe.each([
)
})
it('opens the model picker from the model action', async () => {
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('dialog', { name: 'Select model' })).toBeInTheDocument()
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 () => {
@@ -1,5 +1,5 @@
import { Fragment, memo, useState, type ReactNode } from 'react'
import { Box, Cpu, Paperclip, Shield, ShieldCheck, SlidersHorizontal, Target } from 'lucide-react'
import { memo, useEffect, useState, type CSSProperties, 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'
@@ -19,23 +19,12 @@ import {
formatContextUsage,
} from '@/lib/contextUsage'
import { cn } from '@/lib/utils'
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { 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 { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { ModelPicker } from '@/components/model/ModelPicker'
import { SessionSandboxResourcesDialog } from './SessionSandboxResourcesDialog'
import { ToolMenuItemContent } from './ToolMenuItemContent'
interface SessionConfigMenuProps {
sessionID: string
@@ -56,37 +45,113 @@ interface SessionConfigMenuProps {
onAttachFile: () => void
}
interface SessionConfigEntryBase {
key: string
title: string
detail?: string
disabled?: boolean
icon?: ReactNode
className?: string
}
type SessionConfigEntry =
| (SessionConfigEntryBase & { kind: 'radio'; checked: boolean; onSelect: () => void })
| (SessionConfigEntryBase & { kind: 'checkbox'; checked: boolean; onSelect: () => void })
| (SessionConfigEntryBase & { kind: 'action'; onSelect: () => void })
interface SessionConfigSection {
key: string
label: string
entries: SessionConfigEntry[]
}
type SelectableAgent = Pick<AgentInfo, 'id' | 'name' | 'color' | 'description'>
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 EMPTY_ICON = <span aria-hidden="true" className="block h-4 w-4" />
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 TRIGGER_CLASS =
'relative px-2.5 py-0.5 md:px-3 min-h-11 md:min-h-9 min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[260px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden'
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',
)
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) {
return (
<div className="flex flex-col gap-1">
{label ? (
<div role="presentation" 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,
@@ -118,8 +183,15 @@ export const SessionConfigMenu = memo(function SessionConfigMenu({
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(
@@ -137,247 +209,382 @@ export const SessionConfigMenu = memo(function SessionConfigMenu({
contextUsage ? contextUsageAccessibleLabel(contextUsage) : null,
].filter(Boolean).join(', ')}`
const sections: SessionConfigSection[] = [
{
key: 'agent',
label: 'Agent',
entries: getPrimaryAgents(agents).map((agent) => ({
kind: 'radio',
key: `agent:${agent.id}`,
title: capitalize(agent.name),
detail: agent.description || undefined,
checked: agent.id.toLowerCase() === currentAgent.toLowerCase(),
onSelect: () => onAgentChange(agent.id),
})),
},
{
key: 'model',
label: 'Model',
entries: [
{
kind: 'action',
key: 'model',
title: modelName || 'Select model',
detail: 'Change model',
onSelect: () => {
setOpen(false)
setTimeout(() => onModelPickerOpenChange(true), 0)
},
},
],
},
]
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 }> = []
if (hasVariants) {
sections.push({
key: 'variant',
label: 'Variant',
entries: [
{
kind: 'radio',
key: 'variant:default',
title: 'Default',
checked: currentVariant === undefined,
onSelect: clearVariant,
},
...availableVariants.map((variant) => ({
kind: 'radio' as const,
key: `variant:${variant}`,
title: variant,
className: 'capitalize',
checked: currentVariant === variant,
onSelect: () => setVariant(variant),
})),
],
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: 'context',
label: 'Context',
entries: [
{
kind: 'action',
key: 'context',
title: 'Compact session',
detail: contextUsage ? contextUsageAccessibleLabel(contextUsage) : undefined,
disabled: isCompacting,
onSelect: () => {
onCompact()
setOpen(false)
},
},
],
})
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 (directory !== undefined) {
const sessionEntries: SessionConfigEntry[] = [
{
kind: 'checkbox',
key: 'permission',
title: 'Accept all permissions',
detail: permission.disabled ? permission.label : undefined,
checked: permission.isAuto,
disabled: permission.disabled,
icon: permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />,
onSelect: permission.toggle,
},
]
if (isLocalServer && sandbox.available) {
sessionEntries.push({
kind: 'checkbox',
key: 'sandbox',
title: 'Sandbox commands',
detail: sandbox.disabled ? sandbox.label : undefined,
checked: sandbox.isSandboxed,
disabled: sandbox.disabled,
icon: <Box className="h-4 w-4" />,
onSelect: sandbox.toggle,
if (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>
),
})
if (shouldShowSandboxResources(sandbox)) {
sessionEntries.push({
kind: 'action',
key: 'sandbox-resources',
title: 'Sandbox resources…',
detail: `${formatSandboxResources(sandbox.effectiveResources!)}${sandbox.resources ? ' · custom' : ''}`,
icon: <Cpu className="h-4 w-4" />,
onSelect: () => {
setOpen(false)
setTimeout(() => setResourcesOpen(true), 0)
},
})
}
}
sessionEntries.push({
kind: 'checkbox',
key: 'goal',
title: 'Goal mode',
detail: goalDisabled ? goalLabel : undefined,
checked: goalArmed,
disabled: goalDisabled,
icon: <Target className="h-4 w-4" />,
onSelect: onToggleGoal,
sections.push({
key: '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>
),
})
sections.push({ key: 'session', label: 'Session', entries: sessionEntries })
}
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>
sections.push({
key: 'attach',
label: '',
entries: [
{
kind: 'action',
key: 'attach',
title: 'Attach image or PDF',
icon: <Paperclip className="h-4 w-4" />,
onSelect: () => {
onAttachFile()
setOpen(false)
},
},
],
})
{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}
const renderDesktopEntry = (entry: SessionConfigEntry) => {
const fallbackClass = entry.kind === 'action' ? 'pl-8' : undefined
{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}
if (entry.kind === 'radio') {
return (
<DropdownMenuRadioItem
key={entry.key}
value={entry.key}
disabled={entry.disabled}
className={cn(fallbackClass, entry.className)}
onSelect={(event) => event.preventDefault()}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</DropdownMenuRadioItem>
)
<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>
),
})
}
if (entry.kind === 'checkbox') {
return (
<DropdownMenuCheckboxItem
key={entry.key}
checked={entry.checked}
disabled={entry.disabled}
className={cn(fallbackClass, entry.className)}
onSelect={(event) => event.preventDefault()}
onCheckedChange={() => entry.onSelect()}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</DropdownMenuCheckboxItem>
)
}
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 (
<DropdownMenuItem
key={entry.key}
disabled={entry.disabled}
className={cn(fallbackClass, entry.className)}
onSelect={() => entry.onSelect()}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</DropdownMenuItem>
<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 renderDesktopSection = (section: SessionConfigSection) => {
const checkedKey = section.entries.find((entry) => entry.kind === 'radio' && entry.checked)?.key
const hasRadio = section.entries.some((entry) => entry.kind === 'radio')
if (hasRadio) {
return (
<DropdownMenuRadioGroup
value={checkedKey}
onValueChange={(value) => {
section.entries.find((entry) => entry.kind === 'radio' && entry.key === value)?.onSelect()
}}
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"
>
{section.entries.map(renderDesktopEntry)}
</DropdownMenuRadioGroup>
)
}
<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">
{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>
)
return section.entries.map(renderDesktopEntry)
}
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 desktopTrigger = (
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}
className={TRIGGER_CLASS}
onClick={onClick}
className={cn(
getIconToggleButtonClassName(isAnySessionToggleActive),
'relative flex shrink-0 items-center justify-center overflow-hidden p-0',
isMobile ? 'size-11' : 'size-9',
gutterCardClassName,
)}
>
<span className="flex w-full min-w-0 items-center gap-1 text-left">
<SlidersHorizontal className={cn('h-3.5 w-3.5 shrink-0', isAnySessionToggleActive && 'text-highlight')} />
<span className="truncate">
<span style={{ color: agentStyleVars['--agent-color'] }}>{agentLabel}</span>
<span> · {modelName || 'Select model'}</span>
<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>
{(showVariant || usageLabel) && (
<span className="flex w-full min-w-0 items-center gap-1 text-[10px] leading-tight">
{showVariant && <span className="truncate capitalize text-highlight">{currentVariant}</span>}
{showVariant && usageLabel && (
<span aria-hidden="true" className="text-muted-foreground">·</span>
)}
{usageLabel && (
<span data-testid="composer-config-context-usage" className={cn('shrink-0 font-medium', usageTone)}>
{usageLabel}
</span>
)}
</span>
)}
{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>
)
@@ -386,87 +593,58 @@ export const SessionConfigMenu = memo(function SessionConfigMenu({
<>
{isMobile ? (
<>
<button
type="button"
aria-label={configName}
title={configName}
data-active={isAnySessionToggleActive ? 'true' : undefined}
onClick={() => setOpen(true)}
className={cn(
getIconToggleButtonClassName(isAnySessionToggleActive),
'relative flex items-center justify-center size-11 p-0 overflow-hidden',
)}
>
<SlidersHorizontal className="h-5 w-5" />
{meter}
</button>
{renderTrigger(() => {
setView('main')
setOpen(true)
})}
<BottomSheet
isOpen={open}
onClose={() => setOpen(false)}
onClose={() => handleOpenChange(false)}
ariaLabel="Session config"
heightClass="h-auto max-h-[85dvh]"
heightClass="h-[70dvh] max-h-[720px]"
>
<BottomSheetHeader title="Session config" />
<BottomSheetContent>
<div role="menu" aria-label="Session config">
{sections.map((section, index) => (
<div key={section.key} className={index > 0 ? 'mt-2 border-t border-border pt-2' : ''}>
{section.label ? (
<div role="presentation" className="px-2 py-1 text-sm font-semibold text-muted-foreground">
{section.label}
</div>
) : null}
{section.entries.map((entry) => (
<button
key={entry.key}
type="button"
role={entry.kind === 'radio' ? 'menuitemradio' : entry.kind === 'checkbox' ? 'menuitemcheckbox' : 'menuitem'}
aria-checked={entry.kind === 'action' ? undefined : entry.checked}
disabled={entry.disabled}
aria-disabled={entry.disabled ? 'true' : undefined}
onClick={entry.onSelect}
className={cn(
'flex w-full min-h-11 items-center rounded-lg px-2 py-2 text-left text-sm hover:bg-accent',
entry.className,
)}
>
<ToolMenuItemContent icon={entry.icon ?? EMPTY_ICON} title={entry.title} detail={entry.detail} />
</button>
))}
</div>
))}
</div>
<BottomSheetContent
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">
{renderMainView(true)}
</div>
) : view === 'agent' ? (
renderAgentView(true)
) : (
renderModelView()
)}
</BottomSheetContent>
</BottomSheet>
</>
) : (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>{desktopTrigger}</DropdownMenuTrigger>
<DropdownMenuContent
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>{renderTrigger()}</PopoverTrigger>
<PopoverContent
side="top"
align="start"
collisionPadding={8}
className="w-72 max-h-[70vh] overflow-y-auto"
avoidCollisions={false}
className="h-[min(70vh,560px)] w-[22rem] max-w-[calc(100vw-1rem)] overflow-hidden p-0"
>
{sections.map((section, index) => (
<Fragment key={section.key}>
{index > 0 ? <DropdownMenuSeparator /> : null}
{section.label ? <DropdownMenuLabel>{section.label}</DropdownMenuLabel> : null}
{renderDesktopSection(section)}
</Fragment>
))}
</DropdownMenuContent>
</DropdownMenu>
{view === 'main' ? (
<div role="menu" aria-label="Session config" 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>
)}
<ModelQuickSelect
directory={directory}
open={modelPickerOpen}
onOpenChange={onModelPickerOpenChange}
session={modelSelectionSession}
contextUsage={contextUsage}
isCompacting={isCompacting}
onCompact={onCompact}
/>
{shouldShowSandboxResources(sandbox) ? (
<SessionSandboxResourcesDialog
sessionID={sessionID}
@@ -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)
@@ -344,11 +277,11 @@ export const ModelQuickSelect = memo(function ModelQuickSelect({
const navigableItems = useMemo((): ModelListItem[] => {
if (showAllModels) {
if (isSearching) return searchResults
if (isMobile && !selectedProviderId) return EMPTY_MODELS
if (!selectedProviderId) return EMPTY_MODELS
return browseModels
}
return quickSections.flatMap((section) => section.models)
}, [showAllModels, isSearching, isMobile, selectedProviderId, searchResults, browseModels, quickSections])
}, [showAllModels, isSearching, selectedProviderId, searchResults, browseModels, quickSections])
const quickSectionOffsets = useMemo(() => {
const offsets = new Map<string, number>()
@@ -360,7 +293,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 +330,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 +379,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 +452,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 +470,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 +480,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>
)
})
+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 }