feat(commands): align built-in slash commands with OpenCode v2

Replace the split built-in command name list and switch with one typed
registry, so a registered command without a handler is a compile error.
Remove the broken themes/share/unshare/editor entries and the hardcoded
init; server and custom commands now win on a name clash and built-ins
dispatch by registry identity.

Add /copy, /btw, /rename, /fork (message picker), /timeline, /model,
/agent, /variants, /mcp, /skills, /settings and /connect. Open the model
picker through state so /model and the select-model shortcut work while a
response is running, load full session history in the fork picker, and
keep attachments when a built-in command is submitted.

Extract shared clipboard and primary-agent helpers, reuse CopyButton in
the manager token settings, and update the Quick Start and chat docs.
This commit is contained in:
Chris Scott committed 2026-10-02 09:53:57 -04:00
1 parent 7cac8baade
commit 7e93eb4c34
35 files changed
+2291 -767

No files matched your search

@@ -10,6 +10,7 @@ import {
} from '@/components/ui/dropdown-menu'
import { useAgents } from '@/hooks/useOpenCode'
import { getAgentStyleVars } from '@/lib/agent-colors'
import { getPrimaryAgents } from '@/lib/primaryAgents'
interface AgentQuickSelectProps {
directory?: string
@@ -39,13 +40,7 @@ export function AgentQuickSelect({
}: AgentQuickSelectProps) {
const { data: agents = [] } = useAgents(directory)
const primaryAgents = useMemo(() => {
return agents.filter(
(agent) =>
(agent.mode === 'primary' || agent.mode === 'all') &&
!agent.hidden
)
}, [agents])
const primaryAgents = useMemo(() => getPrimaryAgents(agents), [agents])
const handleSelect = (agentId: string) => {
onAgentChange(agentId)
@@ -347,7 +347,8 @@ describe('MessagePart', () => {
const copyButton = screen.getByTitle('Copy output')
fireEvent.click(copyButton)
await expect(vi.waitFor(() => writeText.mock.calls[0]?.[0])).resolves.toBe(output)
await vi.waitFor(() => expect(writeText).toHaveBeenCalled())
expect(writeText).toHaveBeenCalledWith(output)
})
})
@@ -439,6 +439,20 @@ describe('MessageThread', () => {
expect(screen.getByText('You')).toBeInTheDocument()
})
it('exposes the message id on a rendered user message', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const { container } = render(
<MessageThread
sessionID="test-session"
messages={[userMessage('user-42', 'Hello')]}
pending={[]}
/>,
)
expect(container.querySelector('[data-message-id="user-42"]')).not.toBeNull()
})
it('renders a projected shell message from the fixtures', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
@@ -398,7 +398,7 @@ const MessageRow = memo(function MessageRow({
if (!hasRenderableContent(message, simpleChatMode, showReasoning)) return null
return (
<div className="flex flex-col group">
<div className="flex flex-col group" data-message-id={message.id}>
<div
className={`w-full rounded-lg p-1.5 ${
isEditingThisMessage
@@ -1,15 +1,28 @@
import { createRef } from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { PromptInput, type PromptInputHandle } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
import { createCommandActionsMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
runCommand: vi.fn(),
switchSessionModel: vi.fn(),
switchSessionAgent: vi.fn(),
compactSession: vi.fn(),
agents: [] as Array<{ name: string; description?: string }>,
agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>,
setAgent: vi.fn(),
cycleVariant: vi.fn(),
showToast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
loading: vi.fn(),
promise: vi.fn(),
dismiss: vi.fn(),
},
useSTT: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
@@ -27,7 +40,6 @@ vi.mock('@/api/opencode', async () => {
return {
...actual,
runCommand: mocks.runCommand,
compactSession: mocks.compactSession,
switchSessionModel: mocks.switchSessionModel,
switchSessionAgent: mocks.switchSessionAgent,
}
@@ -42,7 +54,6 @@ vi.mock('@/hooks/useOpenCode', async () => {
})
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
@@ -52,6 +63,7 @@ vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAge
vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash }))
vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore }))
vi.mock('@/stores/sendErrorStore', () => ({ useSendErrorStore: mocks.useSendErrorStore }))
vi.mock('@/lib/toast', () => ({ showToast: mocks.showToast }))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
@@ -65,7 +77,9 @@ vi.mock('@/components/agent/AgentQuickSelect', () => ({
}))
vi.mock('@/components/model/ModelQuickSelect', () => ({
ModelQuickSelect: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
ModelQuickSelect: ({ children, open }: { children?: React.ReactNode; open?: boolean }) => (
<div data-testid="model-quick-select" data-open={open ? 'true' : 'false'}>{children}</div>
),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
@@ -105,10 +119,7 @@ describe('PromptInput command submission', () => {
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
onShowSessionsDialog: vi.fn(),
onShowHelpDialog: vi.fn(),
onToggleDetails: vi.fn(),
onExportSession: vi.fn(),
commandActions: createCommandActionsMock(),
onPromptChange: vi.fn(),
}
@@ -134,7 +145,7 @@ describe('PromptInput command submission', () => {
mocks.runCommand.mockResolvedValue(undefined)
mocks.switchSessionModel.mockResolvedValue(undefined)
mocks.switchSessionAgent.mockResolvedValue(undefined)
mocks.agents = [{ name: 'reviewer', description: 'Reviewer' }]
mocks.agents = [{ id: 'reviewer', name: 'reviewer', description: 'Reviewer', mode: 'primary' }]
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
isRecording: false,
@@ -150,7 +161,11 @@ describe('PromptInput command submission', () => {
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({
filterCommands: (query: string) => query === 'review' ? [{ name: 'review', description: 'Review' }] : [],
filterCommands: (query: string) => {
if (query === 'review') return [{ name: 'review', description: 'Review' }]
const builtin = BUILTIN_COMMANDS.find((command) => command.name === query)
return builtin ? [builtin] : []
},
})
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
@@ -163,10 +178,10 @@ describe('PromptInput command submission', () => {
toggleFavorite: vi.fn(),
isModelStateLoading: false,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: vi.fn() })
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant })
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: mocks.setAgent }))
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
@@ -222,4 +237,88 @@ describe('PromptInput command submission', () => {
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled())
expect(input).toHaveValue('/review')
})
it('switches to the next primary agent for /agent without invoking runCommand', async () => {
mocks.agents = [
{ id: 'build', name: 'build', mode: 'primary' },
{ id: 'plan', name: 'plan', mode: 'primary' },
]
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/agent' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.setAgent).toHaveBeenCalledWith('test-session', 'plan'))
expect(mocks.runCommand).not.toHaveBeenCalled()
})
it('reports when /variants is used with a model that has no variants', async () => {
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant })
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/variants' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.showToast.info).toHaveBeenCalledWith('The selected model has no variants'))
expect(mocks.cycleVariant).not.toHaveBeenCalled()
})
it('cycles variants for /variants when the model has them', async () => {
mocks.useVariants.mockReturnValue({ hasVariants: true, currentVariant: 'high', cycleVariant: mocks.cycleVariant })
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/variants' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.cycleVariant).toHaveBeenCalled())
expect(mocks.showToast.info).not.toHaveBeenCalled()
})
it('opens the model picker through the imperative handle while the session is active', () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo())
const ref = createRef<PromptInputHandle>()
render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} ref={ref} isSessionActive />
</QueryClientProvider>
)
expect(screen.getByTestId('model-quick-select')).toHaveAttribute('data-open', 'false')
act(() => {
ref.current?.openModelPicker()
})
expect(screen.getByTestId('model-quick-select')).toHaveAttribute('data-open', 'true')
})
it('keeps attachments and clears only the text when a built-in command is submitted', async () => {
const { container } = renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
await attachImage(container)
fireEvent.change(input, { target: { value: '/btw hi' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.showToast.info).toHaveBeenCalledWith('Built-in commands do not use attachments; they were kept'))
expect(input).toHaveValue('')
expect(screen.getByText('pic.png')).toBeInTheDocument()
})
it('clears the prompt for a built-in command without attachments', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/btw hi' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(input).toHaveValue(''))
expect(mocks.showToast.info).not.toHaveBeenCalled()
})
})
@@ -3,13 +3,13 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
import { createCommandActionsMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
sendPrompt: vi.fn(),
switchSessionModel: vi.fn(),
switchSessionAgent: vi.fn(),
runCommand: vi.fn(),
compactSession: vi.fn(),
agents: [] as Array<{ name: string; description?: string }>,
useSTT: vi.fn(),
useMobile: vi.fn(),
@@ -29,7 +29,6 @@ vi.mock('@/api/opencode', async () => {
...actual,
sendPrompt: mocks.sendPrompt,
runCommand: mocks.runCommand,
compactSession: mocks.compactSession,
switchSessionModel: mocks.switchSessionModel,
switchSessionAgent: mocks.switchSessionAgent,
}
@@ -44,7 +43,6 @@ vi.mock('@/hooks/useOpenCode', async () => {
})
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
@@ -112,10 +110,7 @@ describe('PromptInput agent mention submission', () => {
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
onShowSessionsDialog: vi.fn(),
onShowHelpDialog: vi.fn(),
onToggleDetails: vi.fn(),
onExportSession: vi.fn(),
commandActions: createCommandActionsMock(),
onPromptChange: vi.fn(),
}
@@ -142,7 +137,6 @@ describe('PromptInput agent mention submission', () => {
mocks.switchSessionModel.mockResolvedValue(undefined)
mocks.switchSessionAgent.mockResolvedValue(undefined)
mocks.runCommand.mockResolvedValue(undefined)
mocks.compactSession.mockResolvedValue(undefined)
mocks.agents = [{ name: 'reviewer', description: 'Reviewer' }]
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
@@ -3,6 +3,7 @@ import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
import { createCommandActionsMock } from '@/test/test-utils'
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
@@ -141,11 +142,7 @@ describe('PromptInput STT Gesture Tests', () => {
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
onShowSessionsDialog: vi.fn(),
onShowModelsDialog: vi.fn(),
onShowHelpDialog: vi.fn(),
onToggleDetails: vi.fn(),
onExportSession: vi.fn(),
commandActions: createCommandActionsMock(),
onPromptChange: vi.fn(),
}
+85 -56
View File
@@ -27,6 +27,7 @@ import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay'
import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { randomId } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { formatModelName } from '@/api/providers'
@@ -35,6 +36,7 @@ import { useProviders } from '@/hooks/useProviders'
import type { CommandInfo, ModelRef } from '@opencode-manager/shared/opencode'
import type { FileAttachmentInfo, ImageAttachment } from '@/api/types'
import { isBuiltinCommand, type CommandActions, type PageCommandActions } from '@/lib/builtinCommands'
const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"]
@@ -58,6 +60,7 @@ export interface PromptInputHandle {
setPromptValue: (value: string) => void
clearPrompt: () => void
triggerFileUpload: () => void
openModelPicker: () => void
}
interface PromptInputProps {
@@ -67,12 +70,7 @@ interface PromptInputProps {
isSessionActive?: boolean
isStreamingResponse?: boolean
onScrollToBottom: () => void
onShowSessionsDialog?: () => void
onShowHelpDialog?: () => void
onToggleDetails?: () => boolean
onExportSession?: () => void
onUndo?: () => void | Promise<void>
onRedo?: () => void | Promise<void>
commandActions: PageCommandActions
onPromptChange?: (hasContent: boolean) => void
}
@@ -83,12 +81,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
isSessionActive = false,
isStreamingResponse = false,
onScrollToBottom,
onShowSessionsDialog,
onShowHelpDialog,
onToggleDetails,
onExportSession,
onUndo,
onRedo,
commandActions,
onPromptChange
}, ref) {
const [prompt, setPrompt] = useState('')
@@ -98,6 +91,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileAttachmentInfo>())
const [imageAttachments, setImageAttachments] = useState<ImageAttachment[]>([])
const [isDragging, setIsDragging] = useState(false)
const [isModelPickerOpen, setIsModelPickerOpen] = useState(false)
const [showMentionSuggestions, setShowMentionSuggestions] = useState(false)
const [mentionQuery, setMentionQuery] = useState('')
const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null)
@@ -156,7 +150,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
imageAttachmentsRef.current = imageAttachments
}, [attachedFiles, imageAttachments, prompt])
const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map<string, FileAttachmentInfo>, submittedImageAttachments: ImageAttachment[]) => {
const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map<string, FileAttachmentInfo>, submittedImageAttachments: ImageAttachment[], options?: { keepAttachments?: boolean }) => {
if (
promptRef.current !== submittedPrompt ||
attachedFilesRef.current !== submittedAttachedFiles ||
@@ -166,9 +160,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
setPrompt('')
setAttachedFiles(new Map())
revokeBlobUrls(submittedImageAttachments)
setImageAttachments([])
if (!options?.keepAttachments) {
setAttachedFiles(new Map())
revokeBlobUrls(submittedImageAttachments)
setImageAttachments([])
}
clearSTT()
}, [clearSTT])
@@ -206,6 +202,9 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
},
triggerFileUpload: () => {
fileInputRef.current?.click()
},
openModelPicker: () => {
setIsModelPickerOpen(true)
}
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState])
const sessionAgent = useSessionAgent(sessionID, directory)
@@ -348,9 +347,14 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
agents: parsed.agents,
skills: parsed.skills,
}).then((shouldClear) => {
if (shouldClear) {
clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments)
if (!shouldClear) return
const keepAttachments = isBuiltinCommand(command) && (submittedAttachedFiles.size > 0 || submittedImageAttachments.length > 0)
if (keepAttachments) {
clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments, { keepAttachments: true })
showToast.info('Built-in commands do not use attachments; they were kept')
return
}
clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments)
})
return
}
@@ -499,15 +503,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
setMentionRange(null)
}
const handleAgentChange = (agentId: string) => {
setLocalMode(agentId)
setStoredAgent(sessionID, agentId)
const agent = agents.find(a => a.id === agentId)
if (agent?.model) {
setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.id })
}
}
const startVoiceRecording = async () => {
if (isRecording || isProcessing || isTogglingRecording) {
return
@@ -985,9 +980,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
clearSTT()
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') {
e.preventDefault()
if (hasVariants) {
cycleVariant()
}
handleCycleVariant()
}
}
@@ -1089,18 +1082,48 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
: undefined,
[model, currentVariant],
)
const handleAgentChange = useCallback((agentId: string) => {
setLocalMode(agentId)
setStoredAgent(sessionID, agentId)
const agent = agents.find(a => a.id === agentId)
if (agent?.model) {
setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.id })
}
}, [agents, sessionID, setStoredAgent, setStoredModel])
const handleCycleVariant = useCallback(() => {
if (!hasVariants) {
showToast.info('The selected model has no variants')
return
}
cycleVariant()
}, [hasVariants, cycleVariant])
const handleCycleAgent = useCallback(() => {
const next = getNextPrimaryAgentId(agents, currentMode)
if (!next) {
showToast.info('No primary agents available')
return
}
handleAgentChange(next)
}, [agents, currentMode, handleAgentChange])
const commandActionsWithPrompt = useMemo<CommandActions>(
() => ({
...commandActions,
cycleAgent: handleCycleAgent,
cycleVariant: handleCycleVariant,
}),
[commandActions, handleCycleAgent, handleCycleVariant],
)
const { executeCommand } = useCommandHandler({
sessionID,
directory,
model: modelRef,
currentAgent: currentMode,
onShowSessionsDialog,
onShowModelsDialog: undefined,
onShowHelpDialog,
onToggleDetails,
onExportSession,
onUndo,
onRedo
actions: commandActionsWithPrompt,
})
const showStopButton = isSessionActive
const hideSecondaryButtons = isMobile && isSessionActive
@@ -1298,6 +1321,11 @@ return (
<SessionStatusIndicator sessionID={sessionID} showLabel />
</div>
)}
<ModelQuickSelect
directory={directory}
open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen}
/>
</>
) : (
<>
@@ -1307,26 +1335,27 @@ return (
onAgentChange={handleAgentChange}
isBashMode={isBashMode}
/>
{isSessionActive ? (
<div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]">
<SessionStatusIndicator sessionID={sessionID} showLabel />
</div>
) : (
!hideSecondaryButtons && (
<ModelQuickSelect
directory={directory}
>
<button
className="px-2.5 py-0.5 md:px-3 min-h-[36px] 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 max-w-[110px] md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
>
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
{hasVariants && currentVariant && (
<span className="text-[10px] text-highlight truncate w-full text-center capitalize">{currentVariant}</span>
)}
</button>
</ModelQuickSelect>
)
{isSessionActive && (
<div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]">
<SessionStatusIndicator sessionID={sessionID} showLabel />
</div>
)}
<ModelQuickSelect
directory={directory}
open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen}
>
{!isSessionActive && !hideSecondaryButtons && (
<button
className="px-2.5 py-0.5 md:px-3 min-h-[36px] 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 max-w-[110px] md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
>
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
{hasVariants && currentVariant && (
<span className="text-[10px] text-highlight truncate w-full text-center capitalize">{currentVariant}</span>
)}
</button>
)}
</ModelQuickSelect>
</>
)}
</div>
@@ -87,3 +87,38 @@ describe('ModelQuickSelect theme tokens', () => {
expect(findDarkOnlyClassOffenders(dialog)).toEqual([])
})
})
describe('ModelQuickSelect controlled open', () => {
it('uses the controlled open prop as the source of truth', () => {
const onOpenChange = vi.fn()
const { rerender } = render(<ModelQuickSelect open={false} onOpenChange={onOpenChange} />)
expect(screen.queryByRole('dialog', { name: 'Select model' })).not.toBeInTheDocument()
rerender(<ModelQuickSelect open onOpenChange={onOpenChange} />)
expect(screen.getByRole('dialog', { name: 'Select model' })).toBeInTheDocument()
})
it('renders only the sheet without a trigger when no children are provided', () => {
render(<ModelQuickSelect open />)
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 () => {
const user = userEvent.setup()
const onOpenChange = vi.fn()
render(<ModelQuickSelect open onOpenChange={onOpenChange} />)
await user.click(screen.getByRole('button', { name: /More models/ }))
expect(screen.getByPlaceholderText('Search providers...')).toBeInTheDocument()
await user.keyboard('{Escape}')
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(screen.getByRole('button', { name: /More models/ })).toBeInTheDocument()
expect(screen.queryByPlaceholderText('Search providers...')).not.toBeInTheDocument()
})
})
@@ -18,7 +18,9 @@ import type { Model, Provider } from '@/api/providers'
interface ModelQuickSelectProps {
directory?: string
disabled?: boolean
children: React.ReactNode
children?: React.ReactNode
open?: boolean
onOpenChange?: (open: boolean) => void
}
interface ModelListItem {
@@ -189,8 +191,11 @@ export function ModelQuickSelect({
directory,
disabled,
children,
open,
onOpenChange,
}: ModelQuickSelectProps) {
const [isOpen, setIsOpen] = useState(false)
const [internalIsOpen, setInternalIsOpen] = useState(false)
const isOpen = open ?? internalIsOpen
const [showAllModels, setShowAllModels] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
const deferredSearchQuery = useDeferredValue(searchQuery)
@@ -416,13 +421,16 @@ export function ModelQuickSelect({
setSelectedProviderId(null)
}
const handleOpenChange = (open: boolean) => {
setIsOpen(open)
if (!open) {
const handleOpenChange = (nextOpen: boolean) => {
if (open === undefined) {
setInternalIsOpen(nextOpen)
}
if (!nextOpen) {
setShowAllModels(false)
setSearchQuery('')
setSelectedProviderId(null)
}
onOpenChange?.(nextOpen)
}
const handleProviderSelect = (providerID: string) => {
@@ -567,9 +575,11 @@ export function ModelQuickSelect({
return (
<>
<span onClick={() => !disabled && handleOpenChange(true)} data-model-select-trigger>
{children}
</span>
{children && (
<span onClick={() => !disabled && handleOpenChange(true)}>
{children}
</span>
)}
<BottomSheet
isOpen={isOpen}
onClose={() => handleOpenChange(false)}
@@ -20,6 +20,7 @@ import {
type SchedulePreset,
} from '@/components/schedules/schedule-utils'
import { getRepoDisplayName } from '@/lib/utils'
import { getPrimaryAgents } from '@/lib/primaryAgents'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME } from '@opencode-manager/shared/utils'
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS } from '@opencode-manager/shared/schemas'
import { Loader2 } from 'lucide-react'
@@ -186,13 +187,11 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
}, [providerModels, configDefaultModel])
const agentOptions = useMemo<ComboboxOption[]>(() => {
return agents
.filter((agent) => agent.mode !== 'subagent' && !agent.hidden)
.map((agent) => ({
value: agent.id,
label: agent.name,
description: agent.description,
}))
return getPrimaryAgents(agents).map((agent) => ({
value: agent.id,
label: agent.name,
description: agent.description,
}))
}, [agents])
const selectedAgentSlug = agentsLoaded && !agentOptions.some((option) => option.value === agentSlug) ? '' : agentSlug
@@ -0,0 +1,98 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { SessionMessagePickerDialog } from './SessionMessagePickerDialog'
function userMessage(id: string, text: string, created = 1000): SessionMessageInfo {
return { id, type: 'user', text, time: { created } } as SessionMessageInfo
}
function assistantMessage(id: string, text: string): SessionMessageInfo {
return { id, type: 'assistant', text, time: { created: 1000 } } as unknown as SessionMessageInfo
}
const renderPicker = (
props: Partial<React.ComponentProps<typeof SessionMessagePickerDialog>> = {},
) =>
render(
<SessionMessagePickerDialog
open
onOpenChange={vi.fn()}
title="Fork session"
messages={[]}
onSelect={vi.fn()}
{...props}
/>,
)
describe('SessionMessagePickerDialog', () => {
it('lists only user messages, newest first', () => {
renderPicker({
messages: [
userMessage('old', 'older prompt', 1000),
assistantMessage('assistant', 'reply'),
userMessage('new', 'newer prompt', 2000),
],
})
const older = screen.getByText('older prompt')
const newer = screen.getByText('newer prompt')
expect(screen.queryByText('reply')).not.toBeInTheDocument()
expect(
newer.compareDocumentPosition(older) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy()
})
it('narrows the rows with the search query', () => {
renderPicker({
messages: [userMessage('a', 'alpha prompt'), userMessage('b', 'beta prompt')],
})
expect(screen.getByText('alpha prompt')).toBeInTheDocument()
expect(screen.getByText('beta prompt')).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Search messages'), {
target: { value: 'beta' },
})
expect(screen.queryByText('alpha prompt')).not.toBeInTheDocument()
expect(screen.getByText('beta prompt')).toBeInTheDocument()
})
it('calls onSelect with the message id when a row is clicked', () => {
const onSelect = vi.fn()
renderPicker({ messages: [userMessage('msg-1', 'hello')], onSelect })
fireEvent.click(screen.getByText('hello'))
expect(onSelect).toHaveBeenCalledWith('msg-1')
})
it('calls onSelect with undefined from the leading row', () => {
const onSelect = vi.fn()
renderPicker({
messages: [userMessage('msg-1', 'hello')],
leadingOptionLabel: 'Entire conversation',
onSelect,
})
fireEvent.click(screen.getByText('Entire conversation'))
expect(onSelect).toHaveBeenCalledWith(undefined)
})
it('shows an empty state when no messages match', () => {
renderPicker({ messages: [assistantMessage('a', 'reply')] })
expect(screen.getByText('No messages')).toBeInTheDocument()
})
it('shows a loading state instead of the rows while loading', () => {
renderPicker({ messages: [userMessage('msg-1', 'hello')], loading: true })
expect(screen.getByText('Loading messages…')).toBeInTheDocument()
expect(screen.queryByText('hello')).not.toBeInTheDocument()
expect(screen.queryByText('No messages')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,99 @@
import { useEffect, useMemo, useState } from 'react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
const MESSAGE_PREVIEW_MAX_LENGTH = 200
interface SessionMessagePickerDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
title: string
messages: SessionMessageInfo[]
leadingOptionLabel?: string
loading?: boolean
onSelect: (messageID: string | undefined) => void
}
function messagePreview(text: string): string {
const singleLine = text.replace(/\s+/g, ' ').trim()
return singleLine.length > MESSAGE_PREVIEW_MAX_LENGTH
? singleLine.slice(0, MESSAGE_PREVIEW_MAX_LENGTH)
: singleLine
}
export function SessionMessagePickerDialog({
open,
onOpenChange,
title,
messages,
leadingOptionLabel,
loading = false,
onSelect,
}: SessionMessagePickerDialogProps) {
const [query, setQuery] = useState('')
useEffect(() => {
if (open) setQuery('')
}, [open])
const items = useMemo(() => {
const userMessages = messages.filter(
(message): message is Extract<SessionMessageInfo, { type: 'user' }> =>
message.type === 'user' && message.text.trim().length > 0,
)
const normalizedQuery = query.trim().toLowerCase()
const filtered = normalizedQuery
? userMessages.filter((message) => message.text.toLowerCase().includes(normalizedQuery))
: userMessages
return [...filtered].reverse()
}, [messages, query])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogTitle>{title}</DialogTitle>
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search messages"
autoFocus
className="mt-4"
/>
<div className="flex flex-col gap-1 max-h-[60vh] overflow-y-auto mt-4">
{leadingOptionLabel && (
<button
type="button"
onClick={() => onSelect(undefined)}
className="w-full rounded-md border border-border px-3 py-2 text-left text-sm hover:bg-accent"
>
{leadingOptionLabel}
</button>
)}
{loading ? (
<span className="px-3 py-2 text-sm text-muted-foreground">Loading messages…</span>
) : (
<>
{items.map((message) => (
<button
key={message.id}
type="button"
onClick={() => onSelect(message.id)}
className="w-full rounded-md border border-border px-3 py-2 text-left hover:bg-accent"
>
<span className="block text-sm truncate">{messagePreview(message.text)}</span>
<span className="block text-xs text-muted-foreground">
{new Date(message.time.created).toLocaleTimeString([], { timeStyle: 'short' })}
</span>
</button>
))}
{items.length === 0 && (
<span className="px-3 py-2 text-sm text-muted-foreground">No messages</span>
)}
</>
)}
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,181 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { SideQuestionDialog } from './SideQuestionDialog'
const mocks = vi.hoisted(() => ({
askSideQuestion: vi.fn(),
}))
vi.mock('@/api/opencode', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/opencode')>()),
askSideQuestion: mocks.askSideQuestion,
}))
const renderDialog = (props: Partial<React.ComponentProps<typeof SideQuestionDialog>> = {}) =>
render(
<SideQuestionDialog
open
onOpenChange={vi.fn()}
sessionID="ses_1"
initialQuestion=""
{...props}
/>,
)
describe('SideQuestionDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('asks a non-empty initial question once on mount and renders the answer', async () => {
mocks.askSideQuestion.mockResolvedValue('**42**')
renderDialog({ initialQuestion: 'what is the answer?' })
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(1))
expect(mocks.askSideQuestion).toHaveBeenCalledWith(
'ses_1',
'what is the answer?',
expect.any(AbortSignal),
)
expect(await screen.findByText('42')).toBeInTheDocument()
})
it('asks nothing until the user types and submits when the initial question is empty', async () => {
mocks.askSideQuestion.mockResolvedValue('because')
renderDialog()
expect(mocks.askSideQuestion).not.toHaveBeenCalled()
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
target: { value: 'why?' },
})
fireEvent.click(screen.getByRole('button', { name: 'Ask' }))
await waitFor(() =>
expect(mocks.askSideQuestion).toHaveBeenCalledWith('ses_1', 'why?', expect.any(AbortSignal)),
)
expect(await screen.findByText('because')).toBeInTheDocument()
})
it('shows Retry on failure and asks again when clicked', async () => {
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
renderDialog({ initialQuestion: 'why?' })
await screen.findByText('Failed to get an answer')
mocks.askSideQuestion.mockResolvedValueOnce('retried answer')
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith('ses_1', 'why?', expect.any(AbortSignal))
expect(await screen.findByText('retried answer')).toBeInTheDocument()
})
it('retries the failed question even when the draft was edited to another value', async () => {
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
renderDialog({ initialQuestion: 'question A' })
await screen.findByText('Failed to get an answer')
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
target: { value: 'question B' },
})
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
'ses_1',
'question A',
expect.any(AbortSignal),
)
})
it('retries the failed question even when the draft was cleared', async () => {
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
renderDialog({ initialQuestion: 'question A' })
await screen.findByText('Failed to get an answer')
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
target: { value: '' },
})
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
'ses_1',
'question A',
expect.any(AbortSignal),
)
})
it('cancels the pending request when a replacement question is submitted', async () => {
let resolveA: (value: string) => void = () => {}
let resolveB: (value: string) => void = () => {}
let signalA: AbortSignal | undefined
let signalB: AbortSignal | undefined
mocks.askSideQuestion
.mockImplementationOnce((_sessionID: string, _question: string, signal?: AbortSignal) => {
signalA = signal
return new Promise<string>((resolve) => {
resolveA = resolve
})
})
.mockImplementationOnce((_sessionID: string, _question: string, signal?: AbortSignal) => {
signalB = signal
return new Promise<string>((resolve) => {
resolveB = resolve
})
})
renderDialog({ initialQuestion: 'question A' })
await waitFor(() => expect(signalA).toBeDefined())
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
target: { value: 'question B' },
})
fireEvent.click(screen.getByRole('button', { name: 'Ask' }))
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
'ses_1',
'question B',
expect.any(AbortSignal),
)
expect(signalB).toBeDefined()
expect(signalA?.aborted).toBe(true)
resolveB('answer B')
expect(await screen.findByText('answer B')).toBeInTheDocument()
resolveA('answer A')
await waitFor(() => expect(screen.queryByText('answer A')).not.toBeInTheDocument())
expect(screen.getByText('answer B')).toBeInTheDocument()
})
it('aborts the in-flight request when unmounted', async () => {
let capturedSignal: AbortSignal | undefined
mocks.askSideQuestion.mockImplementation(
(_sessionID: string, _question: string, signal?: AbortSignal) => {
capturedSignal = signal
return new Promise<string>(() => {})
},
)
const { unmount } = renderDialog({ initialQuestion: 'why?' })
await waitFor(() => expect(capturedSignal).toBeDefined())
expect(capturedSignal?.aborted).toBe(false)
unmount()
expect(capturedSignal?.aborted).toBe(true)
})
})
@@ -0,0 +1,115 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { Loader2 } from 'lucide-react'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { CopyButton } from '@/components/ui/copy-button'
import { TextPart } from '@/components/message/TextPart'
import { askSideQuestion } from '@/api/opencode'
interface SideQuestionDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
sessionID: string
initialQuestion?: string
}
export function SideQuestionDialog({
open,
onOpenChange,
sessionID,
initialQuestion = '',
}: SideQuestionDialogProps) {
const [question, setQuestion] = useState(initialQuestion)
const [answer, setAnswer] = useState('')
const [error, setError] = useState(false)
const [pending, setPending] = useState(false)
const controllerRef = useRef<AbortController | null>(null)
const requestRef = useRef(0)
const lastQuestionRef = useRef('')
const ask = useCallback(async (value: string) => {
const trimmed = value.trim()
if (!trimmed) return
lastQuestionRef.current = trimmed
controllerRef.current?.abort()
const controller = new AbortController()
controllerRef.current = controller
const requestId = ++requestRef.current
setPending(true)
setError(false)
setAnswer('')
try {
const result = await askSideQuestion(sessionID, trimmed, controller.signal)
if (requestRef.current !== requestId || controller.signal.aborted) return
setAnswer(result)
setPending(false)
} catch {
if (requestRef.current !== requestId || controller.signal.aborted) return
setError(true)
setPending(false)
}
}, [sessionID])
useEffect(() => {
if (initialQuestion.trim()) {
void ask(initialQuestion)
}
return () => {
controllerRef.current?.abort()
}
}, [ask, initialQuestion])
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
void ask(question)
}
const handleRetry = () => {
void ask(lastQuestionRef.current)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogTitle>Side question</DialogTitle>
<form onSubmit={handleSubmit} className="flex items-center gap-2 mt-4">
<Input
value={question}
onChange={(event) => setQuestion(event.target.value)}
placeholder="Ask a side question"
autoFocus
/>
<Button type="submit" disabled={!question.trim()}>
Ask
</Button>
</form>
{pending && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Thinking...</span>
</div>
)}
{error && !pending && (
<div className="flex items-center gap-3">
<span className="text-sm text-destructive">Failed to get an answer</span>
<Button type="button" variant="outline" size="sm" onClick={handleRetry}>
Retry
</Button>
</div>
)}
{answer && !pending && (
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1 max-h-[50vh] overflow-y-auto">
<TextPart text={answer} />
</div>
<CopyButton content={answer} title="Copy answer" />
</div>
)}
</DialogContent>
</Dialog>
)
}
@@ -1,9 +1,10 @@
import { useState } from 'react'
import { useManagerToken } from '@/hooks/useManagerToken'
import { Button } from '@/components/ui/button'
import { Button, buttonVariants } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertTriangle, Check, Copy, Eye, EyeOff, RefreshCw } from 'lucide-react'
import { AlertTriangle, Eye, EyeOff, RefreshCw } from 'lucide-react'
import { CopyButton } from '@/components/ui/copy-button'
import { SettingsDisclosure } from './SettingsDisclosure'
interface ManagerTokenSettingsProps {
@@ -14,23 +15,11 @@ interface ManagerTokenSettingsProps {
export function ManagerTokenSettings({ isOpen: controlledOpen, onToggle }: ManagerTokenSettingsProps = {}) {
const { token, isLoading, rotate } = useManagerToken()
const [showToken, setShowToken] = useState(false)
const [copied, setCopied] = useState(false)
const [confirmRotate, setConfirmRotate] = useState(false)
const [uncontrolledOpen, setUncontrolledOpen] = useState(true)
const isOpen = controlledOpen ?? uncontrolledOpen
const handleToggle = onToggle ?? (() => setUncontrolledOpen((open) => !open))
const handleCopy = async () => {
if (!token) return
try {
await navigator.clipboard.writeText(token)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch {
// clipboard may be unavailable; user can copy manually from the input
}
}
const handleRotate = () => {
if (!confirmRotate) {
setConfirmRotate(true)
@@ -73,15 +62,11 @@ export function ManagerTokenSettings({ isOpen: controlledOpen, onToggle }: Manag
{showToken ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
<Button
variant="outline"
size="icon"
type="button"
onClick={handleCopy}
disabled={!token}
>
{copied ? <Check className="h-4 w-4 text-success" /> : <Copy className="h-4 w-4" />}
</Button>
<CopyButton
content={token ?? ''}
title="Copy"
className={buttonVariants({ variant: 'outline', size: 'icon' })}
/>
<Button
variant={confirmRotate ? 'destructive' : 'outline'}
size="icon"
+2 -19
View File
@@ -1,6 +1,7 @@
import { useState } from 'react'
import { Copy, Check } from 'lucide-react'
import { cn } from '@/lib/utils'
import { copyTextToClipboard } from '@/lib/clipboard'
interface CopyButtonProps {
content: string
@@ -23,28 +24,10 @@ export function CopyButton({
const handleCopy = async () => {
if (!content.trim()) return
try {
await navigator.clipboard.writeText(content)
if (await copyTextToClipboard(content)) {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
onCopy?.()
} catch {
const textArea = document.createElement('textarea')
textArea.value = content
textArea.style.position = 'fixed'
textArea.style.left = '-9999px'
document.body.appendChild(textArea)
textArea.select()
try {
const successful = document.execCommand('copy')
if (successful) {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
onCopy?.()
}
} finally {
document.body.removeChild(textArea)
}
}
}