Files
opencode-manager/frontend/src/components/message/SessionConfigMenu.tsx
T

692 lines
24 KiB
TypeScript

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}
</>
)
})