Merge pull request #378 from chriswritescode-dev/feat/slash-command-parity

feat(commands): align built-in slash commands with OpenCode v2
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-02 19:54:04 -04:00
commit 4ee3e50af1
43 files changed
+2820 -782

No files matched your search

+4 -2
View File
@@ -30,7 +30,9 @@ Click the **model name** in the chat prompt area to open the quick model switche
## Slash Commands
Type `/` to see available commands. Built-in commands are covered in the [Quick Start](../getting-started/quickstart.md#useful-commands).
Type `/` to see available commands. Built-in commands are covered in the [Quick Start](../getting-started/quickstart.md#useful-commands). OpenCode's own commands, such as `/init` and `/review`, appear in the same list.
The fork keyboard shortcut opens the same message picker as `/fork`.
### Custom Commands
@@ -49,7 +51,7 @@ template: |
{{selection}}
```
Use with `/review` in chat.
Use with `/review` in chat. A custom command with the same name as a built-in command replaces the built-in.
## File Mentions
+6 -6
View File
@@ -163,12 +163,12 @@ This makes recurring jobs easy to review without digging through raw session dat
Every run creates or attaches to a normal OpenCode session.
Use **Open session** when you want to:
Use **Open session** to continue from the generated report, answer follow-up questions, or debug provider, permission, or tool issues.
- inspect the original conversation
- continue from the generated report
- answer follow-up questions from the agent
- debug provider, permission, or tool issues
What it opens depends on where the run worked:
- **In the repository, or still running**: the run's own session.
- **In a temporary worktree that has finished**: the worktree is removed when the run ends, so the original session can no longer do any work. Instead, a new session opens in the repository with the run's full output, any error, and the branch and commit holding the run's changes added as context. It uses your normal permissions rather than the run's unattended ones, and nothing is sent to the model until you write a message.
This keeps automation connected to the rest of the OpenCode Manager workflow instead of creating a separate silo.
@@ -186,7 +186,7 @@ This keeps automation connected to the rest of the OpenCode Manager workflow ins
1. Open the run from **Run History**
2. Check the **Error** tab for the failure message
3. Use **Open session** to inspect the underlying session
3. Use **Open session** to follow up on the failure with the agent
4. Verify provider credentials, model availability, and any pending agent questions or permissions
### No Assistant Output
+22 -4
View File
@@ -80,15 +80,32 @@ If you already used standalone OpenCode in those repositories, existing chats ap
1. Select your repository from the sidebar
2. Click **New Session** or type `/new`
3. Type your message
4. Press **Enter** to send
4. Press **Cmd+Enter** (`Ctrl+Enter` on other platforms) to send, or **Enter** on mobile
### Useful Commands
| Command | Description |
|---------|-------------|
| `/help` | Show available commands |
| `/new` | Start a new session |
| `/help`, `/settings` | Open settings |
| `/new`, `/clear` | Start a new session |
| `/sessions`, `/resume`, `/continue` | List and switch between sessions |
| `/model`, `/models` | Open the model picker, also while a response is running |
| `/agent` | Switch to the next primary agent |
| `/variants` | Cycle the model's reasoning variant |
| `/compact` | Reduce session context |
| `/rename [title]` | Rename the session; with no title, regenerate it |
| `/fork` | Fork the session from a chosen message, or the entire conversation |
| `/timeline` | Jump to a loaded message in the conversation |
| `/btw <question>` | Ask a side question without adding it to the conversation |
| `/copy` | Copy the full transcript as Markdown |
| `/export` | Download the full transcript as Markdown |
| `/undo`, `/redo` | Undo or redo the last message |
| `/details` | Toggle tool execution details |
| `/mcp` | Manage MCP servers |
| `/skills` | Load a skill |
| `/connect` | Connect a provider |
Press **Enter** to run a command once its name is complete; use **Shift+Enter** to continue its text on a new line. Built-in commands use only the command text. Attached files and images are kept in the composer for your next message.
### File Mentions
@@ -112,7 +129,8 @@ Now that you're set up, explore more features:
| Shortcut | Action |
|----------|--------|
| `Enter` | Send message |
| `Cmd+Enter` / `Ctrl+Enter` | Send message |
| `Enter` | Run a slash command, such as `/btw <question>`; otherwise a new line on desktop, send on mobile |
| `Shift+Enter` | New line |
The app uses a configurable leader key system (`Cmd+O` on Mac, `Ctrl+O` on other platforms) for additional shortcuts. Customize in Settings > Keyboard Shortcuts.
+57
View File
@@ -1,11 +1,14 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
activateSkill,
addSessionContext,
askSideQuestion,
cancelForm,
clearRevert,
commitRevert,
compactSession,
createSession,
createSessionWithContext,
deleteSession,
findFiles,
forkSession,
@@ -26,6 +29,7 @@ import {
stageRevert,
switchSessionAgent,
switchSessionModel,
SIDE_QUESTION_INSTRUCTIONS,
} from './opencode'
import { FetchError } from './fetchWrapper'
@@ -172,6 +176,45 @@ describe('OpenCode facade', () => {
expect(lastRequest().init.body).toBe(JSON.stringify({}))
})
it('adds context to a session without resuming the model', async () => {
fetchMock.mockResolvedValue(jsonResponse({ data: { id: 'inb_1' } }))
await expect(addSessionContext('ses_1', 'Run output')).resolves.toBeUndefined()
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/synthetic')
expect(lastRequest().init.method).toBe('POST')
expect(lastRequest().init.body).toBe(JSON.stringify({ text: 'Run output', resume: false }))
})
it('creates a session in a directory and seeds it with context', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') }))
.mockResolvedValueOnce(jsonResponse({ data: { id: 'inb_1' } }))
const session = await createSessionWithContext({ directory: '/abs/repos/my-repo', title: 'Run (continued)' }, 'Run output')
expect(session.id).toBe('ses_new')
const [createUrl, createInit] = fetchMock.mock.calls[0] ?? []
expect(String(createUrl)).toBe('http://localhost/api/opencode/api/session')
expect((createInit as RequestInit).body).toBe(JSON.stringify({ title: 'Run (continued)', location: { directory: '/abs/repos/my-repo' } }))
const [contextUrl, contextInit] = fetchMock.mock.calls[1] ?? []
expect(String(contextUrl)).toBe('http://localhost/api/opencode/api/session/ses_new/synthetic')
expect((contextInit as RequestInit).body).toBe(JSON.stringify({ text: 'Run output', resume: false }))
})
it('deletes the new session when seeding its context fails', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') }))
.mockResolvedValueOnce(new Response('nope', { status: 400 }))
.mockResolvedValueOnce(new Response(null, { status: 204 }))
await expect(createSessionWithContext({ directory: '/abs/repos/my-repo' }, 'Run output')).rejects.toBeInstanceOf(FetchError)
const [deleteUrl, deleteInit] = fetchMock.mock.calls[2] ?? []
expect(String(deleteUrl)).toBe('http://localhost/api/opencode/api/session/ses_new')
expect((deleteInit as RequestInit).method).toBe('DELETE')
})
it('finds files through the V2 filesystem route and returns paths', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
@@ -413,6 +456,20 @@ describe('OpenCode facade', () => {
expect(lastRequest().init.method).toBe('POST')
})
it('asks a side question through the session generate route with the shared instructions', async () => {
fetchMock.mockResolvedValue(jsonResponse({ data: { text: ' answer \n' } }))
const answer = await askSideQuestion('ses_1', 'why?')
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/generate')
expect(lastRequest().init.method).toBe('POST')
const body = JSON.parse(String(lastRequest().init.body))
expect(body.prompt).toBe(`${SIDE_QUESTION_INSTRUCTIONS}\n\nwhy?`)
expect(body.prompt.startsWith(SIDE_QUESTION_INSTRUCTIONS)).toBe(true)
expect(body.prompt.endsWith('\n\nwhy?')).toBe(true)
expect(answer).toBe('answer')
})
it('stages, commits, and clears a session revert', async () => {
fetchMock.mockResolvedValue(jsonResponse({ data: { messageID: 'msg_1' } }))
+32
View File
@@ -136,6 +136,21 @@ export async function forkSession(sessionID: string, before?: string): Promise<S
)
}
export async function addSessionContext(sessionID: string, text: string): Promise<void> {
await callOpenCode((api) => api.session.synthetic({ sessionID, text, resume: false }))
}
export async function createSessionWithContext(input: CreateSessionInput, context: string): Promise<SessionInfo> {
const session = await createSession(input)
try {
await addSessionContext(session.id, context)
} catch (error) {
await deleteSession(session.id).catch(() => undefined)
throw error
}
return session
}
export async function switchSessionModel(sessionID: string, model: ModelRef): Promise<void> {
await callOpenCode((api) => api.session.switchModel({ sessionID, model }))
}
@@ -167,6 +182,23 @@ export async function runShell(sessionID: string, command: string): Promise<void
await callOpenCode((api) => api.session.shell({ sessionID, command }))
}
export const SIDE_QUESTION_INSTRUCTIONS =
'The user is asking a quick side question about the conversation so far. Answer directly and concisely in markdown from what you already know. Do not call any tools and do not take any actions.'
export async function askSideQuestion(
sessionID: string,
question: string,
signal?: AbortSignal,
): Promise<string> {
const result = await callOpenCode((api) =>
api.session.generate(
{ sessionID, prompt: [SIDE_QUESTION_INSTRUCTIONS, question].join('\n\n') },
signal ? { signal } : undefined,
),
)
return result.text.trim()
}
export async function interruptSession(sessionID: string): Promise<void> {
await callOpenCode((api) => api.session.interrupt({ sessionID }))
}
@@ -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 { describe, it, expect, vi, beforeEach } from 'vitest'
import { createRef } from 'react'
import { describe, it, expect, vi, beforeEach, afterEach } 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, stubMatchMedia } 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,15 +178,48 @@ 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()
})
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('focuses the prompt on open with a fine pointer', async () => {
stubMatchMedia(true)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
expect(input).toHaveFocus()
})
it('does not focus the prompt on open on touch devices', async () => {
stubMatchMedia(false)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
expect(input).not.toHaveFocus()
})
it('does not take focus from an element that already has it', async () => {
stubMatchMedia(true)
const other = document.createElement('button')
document.body.appendChild(other)
other.focus()
renderComponent()
await screen.findByPlaceholderText('Send a message...')
expect(other).toHaveFocus()
other.remove()
})
it('sends parsed command attachments and offsets to runCommand without injecting the selected agent', async () => {
const { container } = renderComponent()
@@ -211,6 +259,53 @@ describe('PromptInput command submission', () => {
expect(call.skills).toEqual([])
})
it('runs a command whose arguments span multiple lines', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/review first line\nsecond line' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled())
expect(mocks.runCommand.mock.calls[0][0]).toMatchObject({
name: 'review',
text: 'first line\nsecond line',
})
})
it('submits on plain Enter when the prompt is a known command', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/btw first line\nsecond line' } })
fireEvent.keyDown(input, { key: 'Enter' })
await waitFor(() => expect(defaultProps.commandActions.askSideQuestion).toHaveBeenCalledWith('first line\nsecond line'))
})
it('does not submit a known command on Shift+Enter', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/btw hi' } })
fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled()
expect(input).toHaveValue('/btw hi')
})
it.each(['hello there', '/bt hi', '/unknown hi'])('does not submit %j on plain Enter', async (value) => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(input).toHaveValue(value)
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled()
})
it('preserves the submitted command text when the command submission fails', async () => {
mocks.runCommand.mockRejectedValueOnce(new Error('command failed'))
renderComponent()
@@ -222,4 +317,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(),
}
+110 -62
View File
@@ -14,6 +14,7 @@ import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useUIState } from '@/stores/uiStateStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { useMobile } from '@/hooks/useMobile'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
import { usePermissions } from '@/contexts/EventContext'
import { ArrowDown, Upload, X, Mic, MicOff } from 'lucide-react'
@@ -27,6 +28,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,9 +37,15 @@ 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"]
function parseCommandPrompt(value: string): { name: string; args?: string } | null {
const match = value.match(/^\/([a-zA-Z0-9_-]+)(?:\s+([\s\S]*))?$/)
return match ? { name: match[1], args: match[2] } : null
}
const revokeBlobUrls = (attachments: ImageAttachment[]) => {
attachments.forEach((attachment) => {
@@ -58,6 +66,7 @@ export interface PromptInputHandle {
setPromptValue: (value: string) => void
clearPrompt: () => void
triggerFileUpload: () => void
openModelPicker: () => void
}
interface PromptInputProps {
@@ -67,12 +76,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 +87,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 +97,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)
@@ -139,6 +139,14 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const textareaRef = useRef<HTMLTextAreaElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const voiceButtonContainerRef = useRef<HTMLDivElement | null>(null)
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
useEffect(() => {
if (!hasFinePointer) return
const activeElement = document.activeElement
if (activeElement && activeElement !== document.body) return
textareaRef.current?.focus()
}, [hasFinePointer, sessionID])
const resetVoiceGestureState = useCallback(() => {
voiceGestureStartYRef.current = null
@@ -156,7 +164,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 +174,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 +216,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)
@@ -216,6 +229,12 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending
const interruptSession = useInterruptSession()
const { filterCommands } = useCommands({ directory })
const isExactCommandPrompt = (value: string) => {
const commandPrompt = parseCommandPrompt(value)
if (!commandPrompt) return false
const [command] = filterCommands(commandPrompt.name)
return command?.name.toLowerCase() === commandPrompt.name.toLowerCase()
}
const { files: searchResults } = useFileSearch(
mentionQuery,
@@ -331,13 +350,12 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const commandMatch = prompt.match(/^\/([a-zA-Z0-9_-]+)(?:\s+(.*))?$/)
if (commandMatch) {
const [, commandName, commandArgs] = commandMatch
const command = filterCommands(commandName)[0]
const commandPrompt = parseCommandPrompt(prompt)
if (commandPrompt) {
const command = filterCommands(commandPrompt.name)[0]
if (command) {
const parsed = parsePromptToInput(commandArgs?.trim() || '', attachedFiles, agentNames, imageAttachments)
const parsed = parsePromptToInput(commandPrompt.args?.trim() || '', attachedFiles, agentNames, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
@@ -348,9 +366,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 +522,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
@@ -966,7 +980,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}
}
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey || (isMobile && !e.shiftKey))) {
if (e.key === 'Enter' && !e.nativeEvent.isComposing && (e.metaKey || e.ctrlKey || (!e.shiftKey && (isMobile || isExactCommandPrompt(prompt))))) {
e.preventDefault()
if (isMobile) {
textareaRef.current?.blur()
@@ -985,9 +999,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 +1101,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 +1340,11 @@ return (
<SessionStatusIndicator sessionID={sessionID} showLabel />
</div>
)}
<ModelQuickSelect
directory={directory}
open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen}
/>
</>
) : (
<>
@@ -1307,26 +1354,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)}
@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { RunDetailPanel } from './RunDetailPanel'
import type { Repo } from '@/api/types'
import type { ScheduleRun } from '@opencode-manager/shared/types'
@@ -11,10 +11,35 @@ const mocks = vi.hoisted(() => ({
useMarkScheduleRunViewed: vi.fn(),
}))
const apiMocks = vi.hoisted(() => ({
createSessionWithContext: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
getRepo: mocks.getRepo,
}))
vi.mock('@/api/opencode', () => ({
createSessionWithContext: apiMocks.createSessionWithContext,
}))
vi.mock('@/lib/toast', () => ({
showToast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
loading: vi.fn(),
promise: vi.fn(),
dismiss: vi.fn(),
},
}))
function LocationProbe() {
const location = useLocation()
return <div data-testid="location">{location.pathname}</div>
}
vi.mock('@/hooks/useSchedules', () => ({
useMarkScheduleRunViewed: mocks.useMarkScheduleRunViewed,
}))
@@ -71,6 +96,7 @@ function renderPanel(activeRun: ScheduleRun | null = run) {
onCancelRun={vi.fn()}
cancelRunPending={false}
/>
<LocationProbe />
</QueryClientProvider>
</MemoryRouter>,
)
@@ -155,3 +181,78 @@ describe('RunDetailPanel local link handling', () => {
expect(viewedMutate).not.toHaveBeenCalled()
})
})
describe('RunDetailPanel open session', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.getRepo.mockResolvedValue(repo)
})
async function clickOpenSession() {
await waitFor(() => expect(screen.getByRole('button', { name: 'Open session' })).toBeEnabled())
fireEvent.click(screen.getByRole('button', { name: 'Open session' }))
}
it('opens the original session for a run that worked in the repository', async () => {
renderPanel({ ...run, sessionId: 'ses_run', worktreePath: null })
await clickOpenSession()
await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_run'))
expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled()
})
it('opens the original session while a worktree run is still running', async () => {
renderPanel({ ...run, status: 'running', sessionId: 'ses_run', worktreePath: '/abs/worktrees/run-1' })
await clickOpenSession()
await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_run'))
expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled()
})
it('opens a new repo session seeded with the full output and branch for a finished worktree run', async () => {
apiMocks.createSessionWithContext.mockResolvedValue({ id: 'ses_new' })
renderPanel({
...run,
sessionId: 'ses_run',
sessionTitle: 'Daily recap',
finishedAt: Date.UTC(2026, 9, 2),
worktreePath: '/abs/worktrees/run-1',
runBranch: 'schedule/run-1',
commitHash: 'abc123',
})
await clickOpenSession()
await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_new'))
const [input, context] = apiMocks.createSessionWithContext.mock.calls[0] ?? []
expect(input).toEqual({ directory: '/abs/repos/my-repo', title: 'Daily recap (continued)' })
expect(context).toContain('scheduled run #1 "Daily recap", which completed and finished at 2026-10-02T00:00:00.000Z')
expect(context).toContain('branch `schedule/run-1` at commit `abc123`')
expect(context).toContain(`Run output:\n\n${run.responseText}`)
})
it('includes the error and notes no committed changes for a failed worktree run', async () => {
apiMocks.createSessionWithContext.mockResolvedValue({ id: 'ses_new' })
renderPanel({ ...run, status: 'failed', responseText: null, errorText: 'Model timed out', worktreePath: '/abs/worktrees/run-1' })
await clickOpenSession()
await waitFor(() => expect(apiMocks.createSessionWithContext).toHaveBeenCalled())
const [input, context] = apiMocks.createSessionWithContext.mock.calls[0] ?? []
expect(input).toEqual({ directory: '/abs/repos/my-repo', title: 'Scheduled run (continued)' })
expect(context).toContain('ended as failed')
expect(context).toContain('committed no changes')
expect(context).toContain('The run produced no output.')
expect(context).toContain('Run error:\n\nModel timed out')
})
it('shows a single open session button', async () => {
renderPanel({ ...run, sessionId: 'ses_run', worktreePath: '/abs/worktrees/run-1' })
await waitFor(() => expect(screen.getByRole('button', { name: 'Open session' })).toBeEnabled())
expect(screen.getAllByRole('button', { name: /session|repo/i })).toHaveLength(1)
})
})
@@ -6,9 +6,11 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { getRepo } from '@/api/repos'
import { createSessionWithContext } from '@/api/opencode'
import { getWorkspaceFilePath } from '@/lib/markdownLinks'
import { getSessionPath } from '@/lib/navigation'
import { getRepoDisplayName } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { useMarkScheduleRunViewed } from '@/hooks/useSchedules'
import { Loader2 } from 'lucide-react'
import type { ScheduleRun } from '@opencode-manager/shared/types'
@@ -24,6 +26,7 @@ interface RunDetailPanelProps {
export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) {
const navigate = useNavigate()
const [selectedFilePath, setSelectedFilePath] = useState<string | null>(null)
const [openingSession, setOpeningSession] = useState(false)
const { data: repo, isPending: repoPending, isError: repoError, refetch: refetchRepo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId),
@@ -67,6 +70,28 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
const { sessionId } = activeRun
const opensNewRepoSession = Boolean(activeRun.worktreePath) && activeRun.status !== 'running'
const handleOpenSession = async () => {
if (!opensNewRepoSession) {
if (sessionId) navigate(getSessionPath(repoId, sessionId))
return
}
if (!repo) return
setOpeningSession(true)
try {
const session = await createSessionWithContext(
{ directory: repo.fullPath, title: `${activeRun.sessionTitle ?? 'Scheduled run'} (continued)` },
buildRunContext(activeRun),
)
navigate(getSessionPath(repoId, session.id))
} catch (error) {
showToast.error(`Could not open a repository session for this run: ${error instanceof Error ? error.message : 'Unknown error'}`)
} finally {
setOpeningSession(false)
}
}
return (
<>
<Tabs key={`${activeRun.id}-${String(activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log')}`} defaultValue={activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log'} className="flex min-h-0 flex-1 flex-col overflow-hidden">
@@ -77,8 +102,9 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
<TabsTrigger value="error" disabled={!activeRun.errorText} className="rounded-none border-b-2 border-transparent px-3 py-2 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">{activeRun.status === 'cancelled' ? 'Details' : 'Error'}</TabsTrigger>
</TabsList>
<div className="flex items-center gap-2 py-1">
{sessionId && (
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => navigate(getSessionPath(repoId, sessionId))}>
{(sessionId || opensNewRepoSession) && (
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => { void handleOpenSession() }} disabled={openingSession || (opensNewRepoSession && !repo)}>
{openingSession ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : null}
Open session
</Button>
)}
@@ -138,3 +164,21 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
</>
)
}
function buildRunContext(run: ScheduleRun): string {
const finished = run.finishedAt ? ` and finished at ${new Date(run.finishedAt).toISOString()}` : ''
const sections = [
`Context from scheduled run #${run.id} "${run.sessionTitle ?? 'Scheduled run'}", which ${run.status === 'completed' ? 'completed' : `ended as ${run.status}`}${finished}.`,
describeRunChanges(run),
run.responseText ? `Run output:\n\n${run.responseText}` : 'The run produced no output.',
run.errorText ? `Run error:\n\n${run.errorText}` : null,
]
return sections.filter((section): section is string => section !== null).join('\n\n')
}
function describeRunChanges(run: ScheduleRun): string {
if (run.runBranch && run.commitHash) {
return `The run worked in a temporary worktree that has since been removed. Its changes were committed to branch \`${run.runBranch}\` at commit \`${run.commitHash}\`; they are not in this checkout unless that branch is checked out or merged.`
}
return 'The run worked in a temporary worktree that has since been removed and committed no changes.'
}
@@ -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,141 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
import { useState } from 'react'
import { render, screen, fireEvent, waitFor } 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}
/>,
)
function FocusHost() {
const [open, setOpen] = useState(false)
return (
<>
<textarea aria-label="prompt" />
<button type="button" onClick={() => setOpen(true)}>open</button>
{open && (
<SessionMessagePickerDialog
open
onOpenChange={(next) => {
if (!next) setOpen(false)
}}
title="Fork session"
messages={[]}
onSelect={vi.fn()}
/>
)}
</>
)
}
describe('SessionMessagePickerDialog', () => {
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('focuses its search on open and returns focus to the previous element on Escape', async () => {
stubMatchMedia(true)
render(<FocusHost />)
const prompt = screen.getByLabelText('prompt')
prompt.focus()
fireEvent.click(screen.getByText('open'))
const search = await screen.findByPlaceholderText('Search messages')
await waitFor(() => expect(search).toHaveFocus())
fireEvent.keyDown(search, { key: 'Escape' })
await waitFor(() => expect(prompt).toHaveFocus())
})
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,222 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { useState } from '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}
/>,
)
function FocusHost() {
const [open, setOpen] = useState(false)
return (
<>
<textarea aria-label="prompt" />
<button type="button" onClick={() => setOpen(true)}>open</button>
{open && (
<SideQuestionDialog
open
sessionID="ses_1"
onOpenChange={(next) => {
if (!next) setOpen(false)
}}
/>
)}
</>
)
}
describe('SideQuestionDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('focuses its input on open and returns focus to the previous element on Escape', async () => {
stubMatchMedia(true)
render(<FocusHost />)
const prompt = screen.getByLabelText('prompt')
prompt.focus()
fireEvent.click(screen.getByText('open'))
const input = await screen.findByPlaceholderText('Ask a side question')
await waitFor(() => expect(input).toHaveFocus())
fireEvent.keyDown(input, { key: 'Escape' })
await waitFor(() => expect(prompt).toHaveFocus())
})
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)
}
}
}
+75 -1
View File
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, act } from "@testing-library/react";
import { useState } from "react";
import { render, screen, act, fireEvent, waitFor } from "@testing-library/react";
import { stubMatchMedia } from "@/test/test-utils";
import {
Dialog,
DialogContent,
@@ -398,6 +400,78 @@ describe("DialogHeader", () => {
});
});
function ReturnFocusHost({ onCloseAutoFocus }: { onCloseAutoFocus?: (event: Event) => void }) {
const [open, setOpen] = useState(false)
return (
<>
<textarea aria-label="prompt" />
<button type="button" onClick={() => setOpen(true)}>open</button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent onCloseAutoFocus={onCloseAutoFocus}>
<DialogTitle>Focus Dialog</DialogTitle>
<input aria-label="dialog input" autoFocus />
</DialogContent>
</Dialog>
</>
)
}
async function openAndEscape(returnTarget: HTMLElement) {
returnTarget.focus()
fireEvent.click(screen.getByText('open'))
const input = await screen.findByLabelText('dialog input')
await waitFor(() => expect(input).toHaveFocus())
fireEvent.keyDown(input, { key: 'Escape' })
await waitFor(() => expect(screen.queryByLabelText('dialog input')).not.toBeInTheDocument())
await act(() => new Promise((resolve) => setTimeout(resolve, 0)))
}
describe('Dialog return focus', () => {
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('returns focus to the element focused before opening when there is no trigger', async () => {
stubMatchMedia(true)
render(<ReturnFocusHost />)
const prompt = screen.getByLabelText('prompt')
await openAndEscape(prompt)
expect(prompt).toHaveFocus()
})
it('does not refocus a text field on touch devices, so the keyboard stays closed', async () => {
stubMatchMedia(false)
render(<ReturnFocusHost />)
const prompt = screen.getByLabelText('prompt')
await openAndEscape(prompt)
expect(prompt).not.toHaveFocus()
})
it('refocuses a non-text element on touch devices', async () => {
stubMatchMedia(false)
render(<ReturnFocusHost />)
const opener = screen.getByText('open')
await openAndEscape(opener)
expect(opener).toHaveFocus()
})
it('lets a caller onCloseAutoFocus that prevents default take over', async () => {
stubMatchMedia(true)
render(<ReturnFocusHost onCloseAutoFocus={(event) => event.preventDefault()} />)
const prompt = screen.getByLabelText('prompt')
await openAndEscape(prompt)
expect(prompt).not.toHaveFocus()
})
})
function stubVisualViewport(height: number) {
const listeners = new Set<() => void>()
Object.defineProperty(window, 'visualViewport', {
+34 -2
View File
@@ -5,13 +5,37 @@ import { X } from "lucide-react"
import { cn } from "@/lib/utils"
import { useSwipeBack } from '@/hooks/useMobile'
import { useVisualViewport } from '@/hooks/useVisualViewport'
import { FINE_POINTER_MEDIA_QUERY } from '@/hooks/useMediaQuery'
const DialogOpenContext = React.createContext<boolean>(true)
const DialogReturnFocusContext = React.createContext<HTMLElement | null>(null)
function getFocusedElement(): HTMLElement | null {
return typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
? document.activeElement
: null
}
function canRestoreFocus(element: HTMLElement): boolean {
if (!element.isConnected || element === document.body) return false
if (!element.matches('input, textarea, [contenteditable="true"]')) return true
return typeof window.matchMedia === 'function' && window.matchMedia(FINE_POINTER_MEDIA_QUERY).matches
}
function Dialog({ open, ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
const [openState, setOpenState] = React.useState(() => ({
open,
returnFocus: open ? getFocusedElement() : null,
}))
if (openState.open !== open) {
setOpenState({ open, returnFocus: open ? getFocusedElement() : openState.returnFocus })
}
return (
<DialogOpenContext.Provider value={open ?? true}>
<DialogPrimitive.Root open={open} {...props} />
<DialogReturnFocusContext.Provider value={openState.returnFocus}>
<DialogPrimitive.Root open={open} {...props} />
</DialogReturnFocusContext.Provider>
</DialogOpenContext.Provider>
)
}
@@ -53,9 +77,16 @@ interface DialogContentProps
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, ...props }, ref) => {
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, onCloseAutoFocus, ...props }, ref) => {
const isMobileFullscreenMode = fullscreen || mobileFullscreen
const isDialogOpen = React.useContext(DialogOpenContext)
const returnFocus = React.useContext(DialogReturnFocusContext)
const handleCloseAutoFocus = (event: Event) => {
onCloseAutoFocus?.(event)
if (event.defaultPrevented || !returnFocus || !canRestoreFocus(returnFocus)) return
event.preventDefault()
returnFocus.focus()
}
const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false)
const shouldEnableMobileSwipe = mobileSwipeToClose !== false && isMobile && isDialogOpen
const shouldAnimateSwipe = shouldEnableMobileSwipe && isMobileFullscreenMode
@@ -118,6 +149,7 @@ const DialogContent = React.forwardRef<
)}
style={Object.keys(mergedStyle).length > 0 ? mergedStyle : undefined}
{...props}
onCloseAutoFocus={handleCloseAutoFocus}
>
{children}
{shouldEnableMobileSwipe && (
@@ -1433,6 +1433,26 @@ describe('EventProvider permissions and forms', () => {
expect(invalidateQueries).toHaveBeenCalledTimes(1)
})
it('invalidates the session list when a session is forked', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'session.forked', data: { sessionID: 'session-fork', parentID: 'session-9' }, directory: '/repo' })
})
await waitFor(() => {
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true)
})
})
it('invalidates only the session list for the event directory', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'sessions', '/repo-a'], { pages: [], pageParams: [] })
+1
View File
@@ -509,6 +509,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
break
}
case 'session.created':
case 'session.forked':
case 'session.renamed':
case 'session.moved':
case 'session.metadata.updated':
@@ -3,10 +3,18 @@ import { renderHook } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createElement } from 'react'
import { useCommandHandler } from '../useCommandHandler'
import { showToast } from '@/lib/toast'
import { createCommandActionsMock } from '@/test/test-utils'
import { BUILTIN_COMMANDS, type CommandActions } from '@/lib/builtinCommands'
const builtinCommand = (name: string) => {
const command = BUILTIN_COMMANDS.find((candidate) => candidate.name === name)
if (!command) throw new Error(`Unknown built-in command: ${name}`)
return command
}
const mocks = vi.hoisted(() => ({
runCommand: vi.fn(),
compactSession: vi.fn(),
switchSessionModel: vi.fn(),
switchSessionAgent: vi.fn(),
setStatus: vi.fn(),
@@ -17,7 +25,6 @@ vi.mock('@/api/opencode', async () => {
return {
...actual,
runCommand: mocks.runCommand,
compactSession: mocks.compactSession,
switchSessionModel: mocks.switchSessionModel,
switchSessionAgent: mocks.switchSessionAgent,
}
@@ -32,10 +39,6 @@ vi.mock('@/lib/toast', () => ({
},
}))
vi.mock('react-router-dom', () => ({
useNavigate: vi.fn(() => vi.fn()),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })),
}))
@@ -60,14 +63,17 @@ const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
describe('useCommandHandler', () => {
let queryClient: QueryClient
const renderHandler = (props: Record<string, unknown> = {}) =>
renderHook(
() => useCommandHandler({ sessionID: 'test-session-id', directory: '/test/dir', ...props }),
const renderHandler = (props: Record<string, unknown> = {}) => {
const actions = (props.actions as CommandActions | undefined) ?? createCommandActionsMock()
const rendered = renderHook(
() => useCommandHandler({ sessionID: 'test-session-id', directory: '/test/dir', ...props, actions }),
{
wrapper: ({ children }) =>
createElement(QueryClientProvider, { client: queryClient }, children),
},
)
return { ...rendered, actions }
}
const setSession = (session: Record<string, unknown>) => {
queryClient.setQueryData(
@@ -80,35 +86,87 @@ describe('useCommandHandler', () => {
vi.clearAllMocks()
queryClient = createTestQueryClient()
mocks.runCommand.mockResolvedValue(undefined)
mocks.compactSession.mockResolvedValue(undefined)
mocks.switchSessionModel.mockResolvedValue(undefined)
mocks.switchSessionAgent.mockResolvedValue(undefined)
})
it('themes command runs the V2 command without injecting an agent attachment', async () => {
setSession(sessionInfo({ agent: 'test-agent' }))
it('export dispatches the built-in action without running a server command', async () => {
setSession(sessionInfo())
const { result } = renderHandler({ currentAgent: 'test-agent' })
const themesCommand = { name: 'themes' }
const { result, actions } = renderHandler()
await result.current.executeCommand(themesCommand, { text: '' })
const cleared = await result.current.executeCommand(builtinCommand('export'), { text: '' })
expect(actions.exportSession).toHaveBeenCalledWith('')
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(cleared).toBe(true)
})
it('runs a server command that shares a built-in name through runCommand', async () => {
setSession(sessionInfo())
const { result, actions } = renderHandler()
await result.current.executeCommand({ name: 'export' }, { text: '' })
expect(mocks.runCommand).toHaveBeenCalledWith({
sessionID: 'test-session-id',
name: 'themes',
name: 'export',
text: '',
})
expect(actions.exportSession).not.toHaveBeenCalled()
})
it('compact command compacts the session', async () => {
it('clear dispatches the new-session built-in action', async () => {
setSession(sessionInfo())
const { result } = renderHandler()
const compactCommand = { name: 'compact' }
const { result, actions } = renderHandler()
await result.current.executeCommand(compactCommand, { text: '' })
await result.current.executeCommand(builtinCommand('clear'), { text: '' })
expect(mocks.compactSession).toHaveBeenCalledWith('test-session-id')
expect(actions.newSession).toHaveBeenCalled()
expect(mocks.runCommand).not.toHaveBeenCalled()
})
it('undo dispatches the built-in action and keeps the prompt', async () => {
setSession(sessionInfo())
const { result, actions } = renderHandler()
const cleared = await result.current.executeCommand(builtinCommand('undo'), { text: '' })
expect(actions.undo).toHaveBeenCalled()
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(cleared).toBe(false)
})
it('shows an error toast and keeps the prompt when a built-in action throws', async () => {
setSession(sessionInfo())
const actions = {
...createCommandActionsMock(),
exportSession: vi.fn().mockRejectedValue(new Error('boom')),
}
const { result } = renderHandler({ actions })
const cleared = await result.current.executeCommand(builtinCommand('export'), { text: '' })
expect(cleared).toBe(false)
expect(showToast.error).toHaveBeenCalledWith('Command failed: boom')
})
it('review command runs the V2 command without injecting an agent attachment', async () => {
setSession(sessionInfo({ agent: 'test-agent' }))
const { result } = renderHandler({ currentAgent: 'test-agent' })
await result.current.executeCommand({ name: 'review' }, { text: '' })
expect(mocks.runCommand).toHaveBeenCalledWith({
sessionID: 'test-session-id',
name: 'review',
text: '',
})
})
it('unknown command runs the V2 command with the parsed payload', async () => {
@@ -131,17 +189,6 @@ describe('useCommandHandler', () => {
})
})
it('sessions command opens sessions dialog without running a command', async () => {
const onShowSessionsDialog = vi.fn()
const { result } = renderHandler({ onShowSessionsDialog })
const sessionsCommand = { name: 'sessions' }
await result.current.executeCommand(sessionsCommand, { text: '' })
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(onShowSessionsDialog).toHaveBeenCalled()
})
it('switches model and agent before running the command when the selection changed', async () => {
setSession(sessionInfo({ agent: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } }))
@@ -195,30 +242,4 @@ describe('useCommandHandler', () => {
expect(cleared).toBe(false)
expect(mocks.runCommand).not.toHaveBeenCalled()
})
it('undo invokes the revert handler instead of running a command', async () => {
setSession(sessionInfo())
const onUndo = vi.fn()
const { result } = renderHandler({ onUndo })
const cleared = await result.current.executeCommand({ name: 'undo' }, { text: '' })
expect(onUndo).toHaveBeenCalled()
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(cleared).toBe(false)
})
it('redo invokes the revert handler instead of running a command', async () => {
setSession(sessionInfo())
const onRedo = vi.fn()
const { result } = renderHandler({ onRedo })
const cleared = await result.current.executeCommand({ name: 'redo' }, { text: '' })
expect(onRedo).toHaveBeenCalled()
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(cleared).toBe(false)
})
})
+28 -107
View File
@@ -1,11 +1,11 @@
import { useState, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { compactSession, runCommand } from '@/api/opencode'
import { useCallback } from 'react'
import { runCommand } from '@/api/opencode'
import type { PromptAgentInput, PromptFileInput, PromptSkillInput } from '@/api/opencode'
import { useCreateSession, useSyncSessionSelection } from '@/hooks/useOpenCode'
import { useSyncSessionSelection } from '@/hooks/useOpenCode'
import { showToast } from '@/lib/toast'
import type { CommandInfo, ModelRef } from '@opencode-manager/shared/opencode'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { isBuiltinCommand, type CommandActions } from '@/lib/builtinCommands'
interface CommandSubmission {
text: string
@@ -18,129 +18,50 @@ interface CommandHandlerProps {
sessionID: string
directory?: string
model?: ModelRef
onShowSessionsDialog?: () => void
onShowModelsDialog?: () => void
onShowHelpDialog?: () => void
onToggleDetails?: () => boolean
onExportSession?: () => void
onUndo?: () => void | Promise<void>
onRedo?: () => void | Promise<void>
currentAgent?: string
actions: CommandActions
}
export function useCommandHandler({
sessionID,
directory,
model,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog,
onToggleDetails,
onExportSession,
onUndo,
onRedo,
currentAgent
currentAgent,
actions,
}: CommandHandlerProps) {
const navigate = useNavigate()
const createSession = useCreateSession(directory)
const syncSelection = useSyncSessionSelection(directory)
const setSessionStatus = useSessionStatus((state) => state.setStatus)
const [loading, setLoading] = useState(false)
const executeCommand = useCallback(async (command: CommandInfo, submission: CommandSubmission = { text: '' }): Promise<boolean> => {
setLoading(true)
if (isBuiltinCommand(command)) {
try {
await actions[command.action](submission.text)
return !command.keepsPrompt
} catch (error) {
showToast.error(`Command failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
return false
}
}
try {
switch (command.name) {
case 'sessions':
case 'resume':
case 'continue':
onShowSessionsDialog?.()
return true
case 'models':
onShowModelsDialog?.()
return true
case 'help':
onShowHelpDialog?.()
return true
case 'new':
case 'clear': {
try {
const newSession = await createSession.mutateAsync({
agent: undefined
})
if (newSession?.id) {
const currentPath = window.location.pathname
const repoMatch = currentPath.match(/\/repos\/(\d+)\/sessions\//)
if (repoMatch) {
const repoId = repoMatch[1]
const newPath = `/repos/${repoId}/sessions/${newSession.id}`
navigate(newPath)
} else {
navigate(`/session/${newSession.id}`)
}
}
} catch (error) {
showToast.error(`Failed to create new session: ${error instanceof Error ? error.message : 'Unknown error'}`)
}
return true
}
case 'details':
if (onToggleDetails) {
const expanded = onToggleDetails()
showToast.success(expanded ? 'Tool details expanded' : 'Tool details collapsed')
}
return true
case 'export':
onExportSession?.()
return true
case 'compact': {
showToast.loading('Compacting session...', { id: `compact-${sessionID}` })
setSessionStatus(sessionID, { type: 'compact' })
await compactSession(sessionID)
return true
}
case 'undo':
await onUndo?.()
return false
case 'redo':
await onRedo?.()
return false
default: {
await syncSelection({ sessionID, model, agent: currentAgent })
await runCommand({
sessionID,
name: command.name,
text: submission.text,
...(submission.files ? { files: submission.files } : {}),
...(submission.agents ? { agents: submission.agents } : {}),
...(submission.skills ? { skills: submission.skills } : {}),
})
return true
}
}
await syncSelection({ sessionID, model, agent: currentAgent })
await runCommand({
sessionID,
name: command.name,
text: submission.text,
...(submission.files ? { files: submission.files } : {}),
...(submission.agents ? { agents: submission.agents } : {}),
...(submission.skills ? { skills: submission.skills } : {}),
})
return true
} catch (error) {
showToast.error(`Command failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
setSessionStatus(sessionID, { type: 'idle' })
return false
} finally {
setLoading(false)
}
}, [sessionID, model, onShowSessionsDialog, onShowModelsDialog, onShowHelpDialog, onToggleDetails, onExportSession, onUndo, onRedo, createSession, navigate, syncSelection, currentAgent, setSessionStatus])
}, [actions, sessionID, model, syncSelection, currentAgent, setSessionStatus])
return {
executeCommand,
loading
executeCommand
}
}
+46 -10
View File
@@ -3,6 +3,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useCommands } from './useCommands'
import { listCommands } from '../api/opencode'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
vi.mock('../api/opencode', () => ({
listCommands: vi.fn(),
@@ -24,16 +25,19 @@ describe('useCommands', () => {
vi.clearAllMocks()
})
it('returns built-in commands in alphabetical order when disabled', () => {
it('returns the built-in commands sorted by name when disabled', () => {
const { result } = renderHook(() => useCommands({ enabled: false }), { wrapper: createWrapper() })
expect(result.current.filterCommands('').map(command => command.name).slice(0, 5)).toEqual([
'clear',
'compact',
'continue',
'details',
'editor',
])
const names = result.current.filterCommands('').map(command => command.name)
expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b)))
for (const command of BUILTIN_COMMANDS) {
expect(names).toContain(command.name)
}
expect(names).not.toContain('themes')
expect(names).not.toContain('share')
expect(names).not.toContain('unshare')
expect(names).not.toContain('editor')
expect(listCommands).not.toHaveBeenCalled()
})
@@ -42,7 +46,9 @@ describe('useCommands', () => {
expect(result.current.filterCommands('co').map(command => command.name)).toEqual([
'compact',
'connect',
'continue',
'copy',
])
expect(result.current.filterCommands('do').map(command => command.name)).toEqual([
'redo',
@@ -60,12 +66,42 @@ describe('useCommands', () => {
await waitFor(() => {
expect(result.current.filterCommands('').map(command => command.name).slice(0, 3)).toEqual([
'agent',
'alpha',
'clear',
'compact',
'btw',
])
})
expect(listCommands).toHaveBeenCalledWith('/repo')
})
it('lets a loaded command override a built-in command with the same name', async () => {
vi.mocked(listCommands).mockResolvedValue([{ name: 'copy', description: 'server copy' }])
const { result } = renderHook(() => useCommands({ directory: '/repo' }), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.filterCommands('copy')).toEqual([
{ name: 'copy', description: 'server copy' },
])
})
const [copy] = result.current.filterCommands('copy')
expect('action' in copy).toBe(false)
})
it('ranks an exact built-in match ahead of a server command that contains it', async () => {
vi.mocked(listCommands).mockResolvedValue([{ name: 'xundo', description: 'X undo' }])
const { result } = renderHook(() => useCommands({ directory: '/repo' }), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.filterCommands('').some(command => command.name === 'xundo')).toBe(true)
})
expect(result.current.filterCommands('undo').map(command => command.name)).toEqual([
'undo',
'xundo',
])
})
})
+3 -22
View File
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query'
import { listCommands } from '@/api/opencode'
import type { CommandInfo } from '@opencode-manager/shared/opencode'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
function sortCommandsByName(commands: CommandInfo[]): CommandInfo[] {
return [...commands].sort((a, b) => a.name.localeCompare(b.name))
@@ -13,27 +14,7 @@ function rankCommandMatch(command: CommandInfo, searchTerm: string): number {
return 2
}
const BUILTIN_COMMANDS: CommandInfo[] = [
{ name: 'help', description: 'Show the help dialog' },
{ name: 'init', description: 'Create or update AGENTS.md file' },
{ name: 'new', description: 'Start a new session' },
{ name: 'clear', description: 'Start a new session (alias for /new)' },
{ name: 'sessions', description: 'List and switch between sessions' },
{ name: 'resume', description: 'List and switch between sessions (alias for /sessions)' },
{ name: 'continue', description: 'List and switch between sessions (alias for /sessions)' },
{ name: 'models', description: 'List available models' },
{ name: 'themes', description: 'List available themes' },
{ name: 'share', description: 'Share current session' },
{ name: 'unshare', description: 'Unshare current session' },
{ name: 'export', description: 'Export current conversation to Markdown' },
{ name: 'compact', description: 'Compact the current session' },
{ name: 'undo', description: 'Undo last message in the conversation' },
{ name: 'redo', description: 'Redo a previously undone message' },
{ name: 'details', description: 'Toggle tool execution details' },
{ name: 'editor', description: 'Open external editor for composing messages' },
]
const SORTED_BUILTIN_COMMANDS = sortCommandsByName(BUILTIN_COMMANDS)
const SORTED_BUILTIN_COMMANDS = sortCommandsByName([...BUILTIN_COMMANDS])
interface UseCommandsOptions {
directory?: string
@@ -47,7 +28,7 @@ export function useCommands(options: UseCommandsOptions = {}) {
queryKey: ['opencode', 'commands', directory ?? null],
queryFn: async () => {
const loaded = await listCommands(directory)
const allCommands = [...BUILTIN_COMMANDS, ...loaded]
const allCommands = [...loaded, ...BUILTIN_COMMANDS]
const uniqueCommands = allCommands.filter((command, index, self) =>
index === self.findIndex((c) => c.name === command.name)
)
+2
View File
@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react'
export const DESKTOP_MEDIA_QUERY = '(min-width: 640px)'
export const FINE_POINTER_MEDIA_QUERY = '(hover: hover) and (pointer: fine)'
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState<boolean>(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
+1 -6
View File
@@ -1,6 +1,7 @@
import { useMemo, useEffect } from 'react'
import { useSession, useAgents } from './useOpenCode'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { getPrimaryAgents } from '@/lib/primaryAgents'
interface AgentInfo {
id: string
@@ -9,12 +10,6 @@ interface AgentInfo {
hidden?: boolean
}
const getPrimaryAgents = (agents: AgentInfo[] | undefined): AgentInfo[] => {
return agents?.filter(
(agent) => (agent.mode === 'primary' || agent.mode === 'all') && !agent.hidden
) ?? []
}
const resolveAvailableAgentId = (
agentId: string | undefined,
agents: AgentInfo[] | undefined,
+67
View File
@@ -0,0 +1,67 @@
import type { CommandInfo } from '@opencode-manager/shared/opencode'
export const BUILTIN_COMMAND_ACTIONS = [
'showSessions',
'showModels',
'newSession',
'toggleDetails',
'exportSession',
'copyTranscript',
'compact',
'askSideQuestion',
'renameSession',
'forkSession',
'jumpToMessage',
'undo',
'redo',
'cycleAgent',
'cycleVariant',
'showMcp',
'showSkills',
'showSettings',
'connectProvider',
] as const
type BuiltinCommandAction = (typeof BUILTIN_COMMAND_ACTIONS)[number]
type CommandActionHandler = (argument: string) => void | Promise<void>
export type CommandActions = Record<BuiltinCommandAction, CommandActionHandler>
export type PageCommandActions = Omit<CommandActions, 'cycleAgent' | 'cycleVariant'>
interface BuiltinCommand extends CommandInfo {
action: BuiltinCommandAction
keepsPrompt?: boolean
}
export const BUILTIN_COMMANDS: readonly BuiltinCommand[] = [
{ name: 'help', description: 'Show the help dialog', action: 'showSettings' },
{ name: 'new', description: 'Start a new session', action: 'newSession' },
{ name: 'clear', description: 'Start a new session (alias for /new)', action: 'newSession' },
{ name: 'sessions', description: 'List and switch between sessions', action: 'showSessions' },
{ name: 'resume', description: 'List and switch between sessions (alias for /sessions)', action: 'showSessions' },
{ name: 'continue', description: 'List and switch between sessions (alias for /sessions)', action: 'showSessions' },
{ name: 'models', description: 'List available models', action: 'showModels' },
{ name: 'model', description: 'Choose a model', action: 'showModels' },
{ name: 'agent', description: 'Switch to the next primary agent', action: 'cycleAgent' },
{ name: 'variants', description: 'Cycle the model reasoning variant', action: 'cycleVariant' },
{ name: 'export', description: 'Export current conversation to Markdown', action: 'exportSession' },
{ name: 'copy', description: 'Copy the session transcript to the clipboard', action: 'copyTranscript' },
{ name: 'compact', description: 'Compact the current session', action: 'compact' },
{ name: 'btw', description: 'Ask a side question without adding it to the conversation', action: 'askSideQuestion' },
{ name: 'rename', description: 'Rename the session, or regenerate its title when no title is given', action: 'renameSession' },
{ name: 'fork', description: 'Fork the session from a chosen message', action: 'forkSession' },
{ name: 'timeline', description: 'Jump to a message in the conversation', action: 'jumpToMessage' },
{ name: 'undo', description: 'Undo last message in the conversation', action: 'undo', keepsPrompt: true },
{ name: 'redo', description: 'Redo a previously undone message', action: 'redo', keepsPrompt: true },
{ name: 'details', description: 'Toggle tool execution details', action: 'toggleDetails' },
{ name: 'mcp', description: 'Manage MCP servers', action: 'showMcp' },
{ name: 'skills', description: 'Load a skill', action: 'showSkills' },
{ name: 'settings', description: 'Open settings', action: 'showSettings' },
{ name: 'connect', description: 'Connect a provider', action: 'connectProvider' },
]
export function isBuiltinCommand(command: CommandInfo): command is BuiltinCommand {
return 'action' in command
}
+70
View File
@@ -0,0 +1,70 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { copyTextToClipboard } from './clipboard'
function stubClipboard(value: {
write?: (items: unknown[]) => Promise<void>
writeText?: (text: string) => Promise<void>
}) {
Object.defineProperty(navigator, 'clipboard', {
value,
writable: true,
configurable: true,
})
}
function stubExecCommand(result: boolean) {
const execCommand = vi.fn(() => result)
Object.defineProperty(document, 'execCommand', {
value: execCommand,
writable: true,
configurable: true,
})
return execCommand
}
describe('copyTextToClipboard', () => {
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
delete (navigator as { clipboard?: unknown }).clipboard
delete (document as { execCommand?: unknown }).execCommand
})
it('writes the awaited text through writeText when ClipboardItem is unavailable', async () => {
vi.stubGlobal('ClipboardItem', undefined)
const writeText = vi.fn().mockResolvedValue(undefined)
stubClipboard({ writeText })
await expect(copyTextToClipboard(Promise.resolve('hello'))).resolves.toBe(true)
expect(writeText).toHaveBeenCalledWith('hello')
})
it('writes a ClipboardItem through clipboard.write when available', async () => {
const write = vi.fn().mockResolvedValue(undefined)
const writeText = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('ClipboardItem', class {
constructor(public data: Record<string, unknown>) {}
})
stubClipboard({ write, writeText })
await expect(copyTextToClipboard('hello')).resolves.toBe(true)
expect(write).toHaveBeenCalledTimes(1)
expect(writeText).not.toHaveBeenCalled()
})
it('resolves false when the content promise rejects', async () => {
vi.stubGlobal('ClipboardItem', undefined)
stubClipboard({ writeText: vi.fn().mockResolvedValue(undefined) })
await expect(copyTextToClipboard(Promise.reject(new Error('nope')))).resolves.toBe(false)
})
it('falls back to execCommand when writeText rejects', async () => {
vi.stubGlobal('ClipboardItem', undefined)
stubClipboard({ writeText: vi.fn().mockRejectedValue(new Error('denied')) })
const execCommand = stubExecCommand(true)
await expect(copyTextToClipboard('hello')).resolves.toBe(true)
expect(execCommand).toHaveBeenCalledWith('copy')
})
})
+47
View File
@@ -0,0 +1,47 @@
async function copyViaExecCommand(text: string): Promise<boolean> {
try {
const textArea = document.createElement('textarea')
textArea.value = text
textArea.style.position = 'fixed'
textArea.style.left = '-9999px'
document.body.appendChild(textArea)
textArea.select()
try {
return document.execCommand('copy')
} finally {
document.body.removeChild(textArea)
}
} catch {
return false
}
}
async function attemptCopy(attempt: () => Promise<unknown>): Promise<boolean> {
try {
await attempt()
return true
} catch {
return false
}
}
export async function copyTextToClipboard(content: string | Promise<string>): Promise<boolean> {
if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
const copied = await attemptCopy(() => {
const item = new ClipboardItem({
'text/plain': Promise.resolve(content).then(
(text) => new Blob([text], { type: 'text/plain' }),
),
})
return navigator.clipboard.write([item])
})
if (copied) return true
}
const text = await Promise.resolve(content).catch(() => null)
if (text === null) return false
if (await attemptCopy(() => navigator.clipboard.writeText(text))) return true
return copyViaExecCommand(text)
}
+56
View File
@@ -0,0 +1,56 @@
import { describe, it, expect } from 'vitest'
import { getPrimaryAgents, getNextPrimaryAgentId } from './primaryAgents'
interface TestAgent {
id: string
mode?: string
hidden?: boolean
}
describe('getPrimaryAgents', () => {
it('keeps primary and all agents that are not hidden', () => {
const agents: TestAgent[] = [
{ id: 'primary', mode: 'primary' },
{ id: 'all', mode: 'all' },
{ id: 'sub', mode: 'subagent' },
{ id: 'hidden', mode: 'primary', hidden: true },
]
expect(getPrimaryAgents(agents).map((agent) => agent.id)).toEqual(['primary', 'all'])
})
it('returns an empty array for undefined or empty input', () => {
expect(getPrimaryAgents(undefined)).toEqual([])
expect(getPrimaryAgents([])).toEqual([])
})
})
describe('getNextPrimaryAgentId', () => {
const agents: TestAgent[] = [
{ id: 'build', mode: 'primary' },
{ id: 'plan', mode: 'primary' },
{ id: 'sub', mode: 'subagent' },
{ id: 'hidden', mode: 'primary', hidden: true },
]
it('returns the next primary agent', () => {
expect(getNextPrimaryAgentId(agents, 'build')).toBe('plan')
})
it('wraps around after the last primary agent', () => {
expect(getNextPrimaryAgentId(agents, 'plan')).toBe('build')
})
it('matches the current agent id case-insensitively', () => {
expect(getNextPrimaryAgentId(agents, 'BUILD')).toBe('plan')
})
it('returns the first primary agent when the current agent is unknown', () => {
expect(getNextPrimaryAgentId(agents, 'missing')).toBe('build')
})
it('returns undefined when there are no primary agents', () => {
expect(getNextPrimaryAgentId(undefined, 'build')).toBeUndefined()
expect(getNextPrimaryAgentId([{ id: 'sub', mode: 'subagent' }], 'build')).toBeUndefined()
})
})
+25
View File
@@ -0,0 +1,25 @@
export function getPrimaryAgents<T extends { mode?: string; hidden?: boolean }>(
agents: readonly T[] | undefined,
): T[] {
return agents?.filter(
(agent) => (agent.mode === 'primary' || agent.mode === 'all') && !agent.hidden,
) ?? []
}
export function getNextPrimaryAgentId<T extends { id: string; mode?: string; hidden?: boolean }>(
agents: readonly T[] | undefined,
currentAgentId: string,
): string | undefined {
const primaryAgents = getPrimaryAgents(agents)
if (primaryAgents.length === 0) return undefined
const normalizedAgentId = currentAgentId.toLowerCase()
const currentIndex = primaryAgents.findIndex(
(agent) => agent.id.toLowerCase() === normalizedAgentId,
)
if (currentIndex === -1) return primaryAgents[0].id
return primaryAgents[(currentIndex + 1) % primaryAgents.length].id
}
+205 -53
View File
@@ -32,6 +32,7 @@ import { getAssistantText, getLatestPlayableAssistantMessage, useAutoPlayLastRes
import { useEffect, useRef, useCallback, useMemo } from "react";
import { MessageSkeleton } from "@/components/message/MessageSkeleton";
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
import { copyTextToClipboard } from "@/lib/clipboard";
import { getMessagesContentVersion } from "./sessionContentVersion";
import { showToast } from "@/lib/toast";
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
@@ -40,6 +41,8 @@ import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { compactSession, forkSession, listSessionMessages } from "@/api/opencode";
import { useSessionStatus } from "@/stores/sessionStatusStore";
import type { PageCommandActions } from "@/lib/builtinCommands";
import { useRedoMessage, useUndoMessage } from "@/hooks/useUndoMessage";
import { usePermissions, useForms } from "@/contexts/EventContext";
import type { FormInfo, SessionMessageInfo } from "@opencode-manager/shared/opencode";
@@ -51,6 +54,8 @@ import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBan
import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar";
import { useDialogParam } from "@/hooks/useDialogParam";
import { SessionMoreButton } from "@/components/navigation/SessionMoreButton";
import { SideQuestionDialog } from "@/components/session/SideQuestionDialog";
import { SessionMessagePickerDialog } from "@/components/session/SessionMessagePickerDialog";
const OLDER_HISTORY_SCROLL_THRESHOLD_PX = 200
@@ -104,7 +109,7 @@ export function SessionDetail() {
const repoId = Number(id) || 0;
const isAssistantSession = new URLSearchParams(location.search).get('assistant') === '1';
const { preferences, updateSettings } = useSettings();
const { open: openSettings } = useSettingsDialog();
const { open: openSettings, setActiveTab: setSettingsTab } = useSettingsDialog();
const messageContainerRef = useRef<HTMLDivElement>(null);
const promptInputRef = useRef<PromptInputHandle>(null);
const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false);
@@ -117,6 +122,10 @@ export function SessionDetail() {
const [showScrollButton, setShowScrollButton] = useState(false);
const [hasPromptContent, setHasPromptContent] = useState(false);
const [minimizedFormId, setMinimizedFormId] = useState<string | null>(null);
const [sideQuestion, setSideQuestion] = useState<{ id: number; question: string } | null>(null);
const [messagePickerMode, setMessagePickerMode] = useState<'fork' | 'timeline' | null>(null);
const [forkPickerMessages, setForkPickerMessages] = useState<SessionMessageInfo[] | null>(null);
const [forkPickerLoading, setForkPickerLoading] = useState(false);
const isMobile = useMobile();
const { keyboardHeight } = useVisualViewport();
@@ -191,6 +200,35 @@ export function SessionDetail() {
[transcriptMessages, session?.revert?.messageID],
);
const messagesRef = useRef(messages);
messagesRef.current = messages;
const revertMessageID = session?.revert?.messageID;
useEffect(() => {
if (messagePickerMode !== 'fork' || !sessionId) return;
let cancelled = false;
setForkPickerLoading(true);
setForkPickerMessages(null);
fetchCompleteSessionHistory(sessionId)
.then((history) => {
if (cancelled) return;
setForkPickerMessages(applyRevertBoundary(history, revertMessageID));
})
.catch(() => {
if (cancelled) return;
showToast.error('Failed to load messages');
setMessagePickerMode(null);
})
.finally(() => {
if (cancelled) return;
setForkPickerLoading(false);
});
return () => {
cancelled = true;
};
}, [messagePickerMode, sessionId, revertMessageID]);
const messagesContentVersion = useMemo(() => getMessagesContentVersion(messages), [messages]);
const { scrollToBottom } = useAutoScroll({
@@ -207,9 +245,10 @@ export function SessionDetail() {
void fetchOlder().catch(() => undefined)
}, [fetchOlder, hasOlder]);
const interruptSession = useInterruptSession();
const updateSession = useUpdateSession(sessionDirectory);
const createSession = useCreateSession(sessionDirectory);
const { mutateAsync: updateSessionAsync } = useUpdateSession(sessionDirectory);
const { mutateAsync: createSessionAsync } = useCreateSession(sessionDirectory);
const { modelString } = useModelSelection(sessionDirectory);
const setSessionStatus = useSessionStatus((state) => state.setStatus);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const setActivePromptFileBasePath = useUIState((state) => state.setActivePromptFileBasePath);
const { isEnabled: ttsEnabled } = useTTS();
@@ -247,7 +286,9 @@ export function SessionDetail() {
});
const handleShowSessionsDialog = useCallback(() => setSessionsDialogOpen(true), []);
const handleShowHelpDialog = useCallback(() => openSettings(), [openSettings]);
const handleShowMcpDialog = useCallback(() => setMcpDialogOpen(true), [setMcpDialogOpen]);
const handleShowSkillsDialog = useCallback(() => setSkillsDialogOpen(true), [setSkillsDialogOpen]);
const handleConnectProvider = useCallback(() => setSettingsTab('providers'), [setSettingsTab]);
const handleMinimizeForm = useCallback((form: FormInfo) => {
setMinimizedFormId(form.id)
@@ -291,21 +332,21 @@ export function SessionDetail() {
const handleNewSession = useCallback(async () => {
try {
const newSession = await createSession.mutateAsync({ agent: undefined });
const newSession = await createSessionAsync({ agent: undefined });
if (newSession?.id) {
navigate(`/repos/${repoId}/sessions/${newSession.id}${sessionRouteSuffix}`);
}
} catch {
showToast.error('Failed to create new session');
}
}, [createSession, navigate, repoId, sessionRouteSuffix]);
}, [createSessionAsync, navigate, repoId, sessionRouteSuffix]);
const undoMessage = useUndoMessage({
const { mutateAsync: undoMessageAsync } = useUndoMessage({
sessionId: sessionId ?? '',
directory: sessionDirectory,
onSuccess: (restoredPrompt) => promptInputRef.current?.setPromptValue(restoredPrompt),
});
const redoMessage = useRedoMessage({
const { mutateAsync: redoMessageAsync } = useRedoMessage({
sessionId: sessionId ?? '',
directory: sessionDirectory,
});
@@ -313,71 +354,96 @@ export function SessionDetail() {
const handleCompact = useCallback(async () => {
if (!sessionId) return;
showToast.loading('Compacting session...', { id: `compact-${sessionId}` });
const toastId = `compact-${sessionId}`;
showToast.loading('Compacting session...', { id: toastId });
setSessionStatus(sessionId, { type: 'compact' });
try {
await compactSession(sessionId);
showToast.success('Compaction requested', { id: toastId });
} catch (error) {
showToast.error(`Compact failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
showToast.error(`Compact failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { id: toastId });
setSessionStatus(sessionId, { type: 'idle' });
}
}, [sessionId]);
}, [sessionId, setSessionStatus]);
const handleUndo = useCallback(async () => {
if (!sessionId) return;
const lastUserMessage = [...messages].reverse().find((message) => message.type === 'user');
const lastUserMessage = [...messagesRef.current].reverse().find((message) => message.type === 'user');
if (!lastUserMessage || lastUserMessage.type !== 'user') return;
try {
await undoMessage.mutateAsync({
await undoMessageAsync({
messageID: lastUserMessage.id,
messageContent: lastUserMessage.text,
});
} catch {
// The undo hook surfaces the failure.
}
}, [messages, sessionId, undoMessage]);
}, [sessionId, undoMessageAsync]);
const handleRedo = useCallback(async () => {
if (!sessionId) return;
try {
await redoMessage.mutateAsync();
await redoMessageAsync();
} catch {
// The redo hook surfaces the failure.
}
}, [sessionId, redoMessage]);
}, [sessionId, redoMessageAsync]);
const handleFork = useCallback(async () => {
const openForkPicker = useCallback(() => setMessagePickerMode('fork'), []);
const handleForkAtMessage = useCallback(async (messageID?: string) => {
if (!sessionId) return;
try {
const forkedSession = await forkSession(sessionId);
const forkedSession = await forkSession(sessionId, messageID);
if (forkedSession?.id) {
setMessagePickerMode(null);
navigate(`/repos/${repoId}/sessions/${forkedSession.id}${sessionRouteSuffix}`);
if (messageID) {
const chosenMessage = forkPickerMessages?.find((message) => message.id === messageID);
if (chosenMessage?.type === 'user') {
promptInputRef.current?.setPromptValue(chosenMessage.text);
}
}
showToast.success('Session forked');
}
} catch (error) {
showToast.error(`Fork failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [sessionId, navigate, repoId, sessionRouteSuffix]);
}, [sessionId, forkPickerMessages, navigate, repoId, sessionRouteSuffix]);
const openTimelinePicker = useCallback(() => setMessagePickerMode('timeline'), []);
const handleJumpToMessage = useCallback((messageID?: string) => {
setMessagePickerMode(null);
if (!messageID) return;
const container = messageContainerRef.current;
if (!container) return;
const target = Array.from(
container.querySelectorAll<HTMLElement>('[data-message-id]'),
).find((element) => element.dataset.messageId === messageID);
target?.scrollIntoView({ block: 'start', behavior: 'smooth' });
}, []);
const handleCloseSession = useCallback(() => {
const tab = new URLSearchParams(location.search).get('repoTab') ?? undefined;
navigate(getSessionListPath(repoId, isAssistantSession, tab))
}, [navigate, repoId, isAssistantSession, location.search])
const handleOpenModelDialog = useCallback(() => {
promptInputRef.current?.openModelPicker();
}, [])
const { leaderActive } = useKeyboardShortcuts({
openModelDialog: () => {
const modelSelectTrigger = document.querySelector(
"[data-model-select-trigger]",
) as HTMLElement;
modelSelectTrigger?.click();
},
openSessions: () => setSessionsDialogOpen(true),
openModelDialog: handleOpenModelDialog,
openSessions: handleShowSessionsDialog,
openSettings,
newSession: handleNewSession,
closeSession: handleCloseSession,
compact: handleCompact,
undo: handleUndo,
redo: handleRedo,
fork: handleFork,
fork: openForkPicker,
toggleSidebar: () => setFileBrowserOpen(!fileBrowserOpen),
toggleMode: () => {
const modeButton = document.querySelector(
@@ -409,11 +475,18 @@ export function SessionDetail() {
setFileBrowserOpen(true)
}, [repo?.fullPath, repo?.localPath, sessionDirectory, setFileBrowserOpen]);
const handleSessionTitleUpdate = useCallback((newTitle: string) => {
if (sessionId) {
updateSession.mutate({ sessionID: sessionId, title: newTitle });
const handleRenameSession = useCallback(async (title: string) => {
if (!sessionId) return;
const trimmedTitle = title.trim();
try {
await updateSessionAsync({ sessionID: sessionId, title: trimmedTitle });
if (!trimmedTitle) {
showToast.success('Session title regenerated');
}
} catch (error) {
showToast.error(`Rename failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}, [sessionId, updateSession]);
}, [sessionId, updateSessionAsync]);
const handleFileBrowserClose = useCallback(() => {
setFileBrowserOpen(false)
@@ -433,31 +506,89 @@ export function SessionDetail() {
const handleToggleDetails = useCallback(() => {
const newValue = !preferences?.expandToolCalls
updateSettings({ expandToolCalls: newValue })
return newValue
showToast.success(newValue ? 'Tool details expanded' : 'Tool details collapsed')
}, [preferences?.expandToolCalls, updateSettings]);
const handleExportSession = useCallback(async () => {
const buildSessionExport = useCallback(async () => {
if (!session || !sessionId) {
showToast.error('No session data to export')
return
throw new Error('No session data to export')
}
let history: SessionMessageInfo[]
try {
history = await fetchCompleteSessionHistory(sessionId)
} catch {
showToast.error('Failed to export session')
return
}
const { filename, content } = exportSession(
const history = await fetchCompleteSessionHistory(sessionId)
return exportSession(
applyRevertBoundary(history, session.revert?.messageID),
session,
)
}, [session, sessionId]);
const handleExportSession = useCallback(async () => {
const result = await buildSessionExport().catch((error: unknown) => {
showToast.error(
error instanceof Error && error.message === 'No session data to export'
? error.message
: 'Failed to export session',
)
return null
})
if (!result) return
const { filename, content } = result
if (await downloadMarkdown(content, filename)) {
showToast.success(`Exported to ${filename}`)
}
}, [session, sessionId]);
}, [buildSessionExport]);
const handleCopyTranscript = useCallback(async () => {
const copied = await copyTextToClipboard(
buildSessionExport().then((result) => result.content),
)
if (copied) {
showToast.success('Session transcript copied')
} else {
showToast.error('Failed to copy session transcript')
}
}, [buildSessionExport]);
const handleAskSideQuestion = useCallback((question: string) => {
setSideQuestion({ id: Date.now(), question });
}, []);
const commandActions = useMemo<PageCommandActions>(() => ({
showSessions: handleShowSessionsDialog,
showModels: handleOpenModelDialog,
newSession: handleNewSession,
toggleDetails: handleToggleDetails,
exportSession: handleExportSession,
copyTranscript: handleCopyTranscript,
compact: handleCompact,
askSideQuestion: handleAskSideQuestion,
renameSession: handleRenameSession,
forkSession: openForkPicker,
jumpToMessage: openTimelinePicker,
undo: handleUndo,
redo: handleRedo,
showMcp: handleShowMcpDialog,
showSkills: handleShowSkillsDialog,
showSettings: openSettings,
connectProvider: handleConnectProvider,
}), [
handleShowSessionsDialog,
handleOpenModelDialog,
handleNewSession,
handleToggleDetails,
handleExportSession,
handleCopyTranscript,
handleCompact,
handleAskSideQuestion,
handleRenameSession,
openForkPicker,
openTimelinePicker,
handleUndo,
handleRedo,
handleShowMcpDialog,
handleShowSkillsDialog,
openSettings,
handleConnectProvider,
]);
const handleUndoMessage = useCallback((restoredPrompt: string) => {
promptInputRef.current?.setPromptValue(restoredPrompt)
@@ -538,7 +669,7 @@ export function SessionDetail() {
)}
<Header.EditableTitle
value={session?.title || "Untitled Session"}
onChange={handleSessionTitleUpdate}
onChange={handleRenameSession}
subtitle={<span className="text-highlight">{workspaceDisplayName}</span>}
/>
</div>
@@ -643,12 +774,7 @@ export function SessionDetail() {
isSessionActive={isSessionActive}
isStreamingResponse={isStreamingResponse}
onScrollToBottom={scrollToBottom}
onShowSessionsDialog={handleShowSessionsDialog}
onShowHelpDialog={handleShowHelpDialog}
onToggleDetails={handleToggleDetails}
onExportSession={handleExportSession}
onUndo={handleUndo}
onRedo={handleRedo}
commandActions={commandActions}
onPromptChange={setHasPromptContent}
/>
</div>
@@ -675,6 +801,32 @@ export function SessionDetail() {
</DialogContent>
</Dialog>
{sideQuestion && sessionId && (
<SideQuestionDialog
key={sideQuestion.id}
open
sessionID={sessionId}
initialQuestion={sideQuestion.question}
onOpenChange={(open) => {
if (!open) setSideQuestion(null)
}}
/>
)}
{messagePickerMode && (
<SessionMessagePickerDialog
open
onOpenChange={(open) => {
if (!open) setMessagePickerMode(null);
}}
title={messagePickerMode === 'fork' ? 'Fork session' : 'Jump to message'}
leadingOptionLabel={messagePickerMode === 'fork' ? 'Entire conversation' : undefined}
messages={messagePickerMode === 'fork' ? forkPickerMessages ?? [] : messages}
loading={messagePickerMode === 'fork' && forkPickerLoading}
onSelect={messagePickerMode === 'fork' ? handleForkAtMessage : handleJumpToMessage}
/>
)}
<FileBrowserSheet
isOpen={fileBrowserOpen}
onClose={handleFileBrowserClose}
@@ -0,0 +1,804 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { SessionDetail } from '../SessionDetail'
import { LocationCatcher } from '@/test/test-utils'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
useSessionTranscript: vi.fn(),
useSSE: vi.fn(),
useRepoActivity: vi.fn(),
usePermissions: vi.fn(),
useForms: vi.fn(),
useSSEHealth: vi.fn(),
useConfig: vi.fn(),
useMobile: vi.fn(),
useAutoScroll: vi.fn(),
dialogSetters: {} as Record<string, ReturnType<typeof vi.fn>>,
openSettings: vi.fn(),
setSettingsTab: vi.fn(),
useSessionStatusForSession: vi.fn(),
compactSession: vi.fn(),
listSessionMessages: vi.fn(),
forkSession: vi.fn(),
updateSession: vi.fn(),
createSession: vi.fn(),
updateSettings: vi.fn(),
copyTextToClipboard: vi.fn(),
downloadMarkdown: vi.fn(),
setStatus: vi.fn(),
setPromptValue: vi.fn(),
openModelPicker: vi.fn(),
promptInputProps: null as Record<string, unknown> | null,
scrollIntoView: vi.fn(),
showToast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
loading: vi.fn(),
promise: vi.fn(),
dismiss: vi.fn(),
},
}))
vi.mock('@/config', () => ({
OPENCODE_API_ENDPOINT: 'http://localhost:5551/api/opencode',
API_BASE_URL: 'http://localhost:5551',
SERVER_PORT: 5003,
OPENCODE_PORT: 5551,
FILE_LIMITS: {},
DEFAULTS: {},
ALLOWED_MIME_TYPES: [],
GIT_PROVIDERS: [],
}))
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
return {
...actual,
compactSession: mocks.compactSession,
listSessionMessages: mocks.listSessionMessages,
forkSession: mocks.forkSession,
}
})
vi.mock('@/lib/exportSession', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/exportSession')>()
return {
...actual,
downloadMarkdown: mocks.downloadMarkdown,
}
})
vi.mock('@/lib/clipboard', () => ({
copyTextToClipboard: mocks.copyTextToClipboard,
}))
vi.mock('@/lib/toast', () => ({
showToast: mocks.showToast,
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession,
useInterruptSession: vi.fn(() => ({ mutate: vi.fn() })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn(), mutateAsync: mocks.updateSession })),
useCreateSession: vi.fn(() => ({ mutateAsync: mocks.createSession })),
useConfig: mocks.useConfig,
useSendPrompt: vi.fn(() => ({ mutate: vi.fn() })),
useSendShell: vi.fn(() => ({ mutate: vi.fn() })),
useAgents: vi.fn(() => ({ data: [] })),
}))
vi.mock('@/hooks/useSessionTranscript', () => ({
useSessionTranscript: mocks.useSessionTranscript,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: vi.fn(() => ({ isEnabled: false })),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: vi.fn(() => ({
preferences: { expandToolCalls: false },
updateSettings: mocks.updateSettings,
})),
}))
vi.mock('@/hooks/useSettingsDialog', () => ({
useSettingsDialog: vi.fn(() => ({ open: mocks.openSettings, setActiveTab: mocks.setSettingsTab })),
}))
vi.mock('@/hooks/useMobile', () => ({
useMobile: mocks.useMobile,
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
}))
vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
useAutoScroll: mocks.useAutoScroll,
}))
vi.mock('@/hooks/useDialogParam', () => ({
useDialogParam: vi.fn((name: string) => [false, mocks.dialogSetters[name]]),
}))
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
getAssistantText: vi.fn(() => ''),
getLatestPlayableAssistantMessage: vi.fn(() => null),
useAutoPlayLastResponse: vi.fn(() => {}),
}))
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn((selector?: (state: Record<string, unknown>) => unknown) =>
typeof selector === 'function'
? selector({ isEditingMessage: false, setActivePromptFileBasePath: vi.fn() })
: false
),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn((selector: (state: { setStatus: typeof mocks.setStatus }) => unknown) =>
selector({ setStatus: mocks.setStatus })
),
useSessionStatusForSession: mocks.useSessionStatusForSession,
}))
vi.mock('@/hooks/useSSE', () => ({
useSSE: mocks.useSSE,
}))
vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/contexts/EventContext', async (importOriginal) => {
const actual = await importOriginal()
return {
...(actual as object),
usePermissions: mocks.usePermissions,
useForms: mocks.useForms,
useSSEHealth: mocks.useSSEHealth,
}
})
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve({
id: 1,
repoUrl: 'https://github.com/test/repo',
localPath: '/test/repo',
sourcePath: null,
fullPath: '/test/repo',
branch: 'main',
currentBranch: 'main',
fullSlug: 'test/repo',
repoType: 'github' as const,
})),
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/test/repo' })),
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
vi.mock('@/components/session/SideQuestionDialog', () => ({ SideQuestionDialog: vi.fn(() => null) }))
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) }))
vi.mock('@/components/session/FormPrompt', () => ({ FormPrompt: vi.fn(() => null) }))
vi.mock('@/components/session/MinimizedFormIndicator', () => ({ MinimizedFormIndicator: vi.fn(() => null) }))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: vi.fn(() => null) }))
vi.mock('@/components/message/MessageThread', async () => {
const { createElement } = await import('react')
return {
MessageThread: ({ messages }: { messages: SessionMessageInfo[] }) =>
createElement(
'div',
null,
messages.map((message) =>
createElement('div', { key: message.id, 'data-message-id': message.id }),
),
),
}
})
vi.mock('@/components/message/PromptInput', async () => {
const { forwardRef, useImperativeHandle } = await import('react')
return {
PromptInput: forwardRef((props: Record<string, unknown>, ref) => {
mocks.promptInputProps = props
useImperativeHandle(ref, () => ({
setPromptValue: mocks.setPromptValue,
openModelPicker: mocks.openModelPicker,
}))
return null
}),
}
})
const SESSION_ID = 'session-1'
const createSession = (revert?: { messageID: string }) => ({
id: SESSION_ID,
title: 'Command Session',
time: { created: 1000, updated: 2000 },
location: { directory: '/test/repo' },
...(revert ? { revert } : {}),
})
function createUserMessage(id: string, text: string): SessionMessageInfo {
return {
id,
type: 'user',
text,
time: { created: 1000 },
} as SessionMessageInfo
}
describe('SessionDetail command actions', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.promptInputProps = null
mocks.useSession.mockReturnValue({ data: createSession(), isLoading: false })
mocks.useSessionTranscript.mockReturnValue({
messages: [],
pending: [],
status: 'idle',
isLoading: false,
fetchOlder: vi.fn(),
hasOlder: false,
})
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
mocks.useRepoActivity.mockReturnValue(undefined)
mocks.usePermissions.mockReturnValue({ pendingCount: 0, syncForSession: vi.fn() })
mocks.useForms.mockReturnValue({
current: null,
getForSession: vi.fn(() => null),
pendingCount: 0,
reply: vi.fn(),
cancel: vi.fn(),
syncForSession: vi.fn(),
})
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useMobile.mockReturnValue(false)
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.dialogSetters = {
files: vi.fn(),
mcp: vi.fn(),
skills: vi.fn(),
sourceControl: vi.fn(),
resetPermissions: vi.fn(),
}
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
mocks.compactSession.mockResolvedValue(undefined)
mocks.listSessionMessages.mockResolvedValue({ messages: [] })
mocks.downloadMarkdown.mockResolvedValue(true)
Element.prototype.scrollIntoView = mocks.scrollIntoView
})
const sessionDetailElement = (
captured?: { search: { current: string }; pathname: { current: string } },
) => (
<MemoryRouter initialEntries={[`/repos/1/sessions/${SESSION_ID}`]}>
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
{captured && (
<LocationCatcher
capturedSearch={captured.search}
capturedPathname={captured.pathname}
/>
)}
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
const renderSessionDetail = (
captured?: { search: { current: string }; pathname: { current: string } },
) => render(sessionDetailElement(captured))
const commandHandler = async (name: string) => {
await waitFor(() => expect(mocks.promptInputProps).not.toBeNull())
const commandActions = mocks.promptInputProps?.commandActions as Record<string, (argument?: string) => Promise<void>>
const handler = commandActions[name]
expect(handler).toBeTypeOf('function')
return handler
}
const mockTranscriptMessages = (messages: SessionMessageInfo[]) => {
mocks.useSessionTranscript.mockReturnValue({
messages,
pending: [],
status: 'idle',
isLoading: false,
fetchOlder: vi.fn(),
hasOlder: false,
})
}
it('compacts the session through the shared handler and resolves the toast', async () => {
renderSessionDetail()
const compact = await commandHandler('compact')
await act(async () => {
await compact()
})
expect(mocks.setStatus).toHaveBeenCalledWith(SESSION_ID, { type: 'compact' })
expect(mocks.compactSession).toHaveBeenCalledWith(SESSION_ID)
expect(mocks.showToast.loading).toHaveBeenCalledWith('Compacting session...', { id: `compact-${SESSION_ID}` })
expect(mocks.showToast.success).toHaveBeenCalledWith('Compaction requested', { id: `compact-${SESSION_ID}` })
})
it('resets the session status to idle when compaction fails', async () => {
mocks.compactSession.mockRejectedValueOnce(new Error('nope'))
renderSessionDetail()
const compact = await commandHandler('compact')
await act(async () => {
await compact()
})
expect(mocks.setStatus).toHaveBeenCalledWith(SESSION_ID, { type: 'idle' })
expect(mocks.showToast.error).toHaveBeenCalledWith('Compact failed: nope', { id: `compact-${SESSION_ID}` })
})
it('renames the session through the shared handler', async () => {
renderSessionDetail()
const renameSession = await commandHandler('renameSession')
await act(async () => {
await renameSession(' New name ')
})
expect(mocks.updateSession).toHaveBeenCalledWith({ sessionID: SESSION_ID, title: 'New name' })
expect(mocks.showToast.success).not.toHaveBeenCalled()
})
it('regenerates the title when the command has no argument', async () => {
renderSessionDetail()
const renameSession = await commandHandler('renameSession')
await act(async () => {
await renameSession('')
})
expect(mocks.updateSession).toHaveBeenCalledWith({ sessionID: SESSION_ID, title: '' })
expect(mocks.showToast.success).toHaveBeenCalledWith('Session title regenerated')
})
it('shows the error toast when renaming fails', async () => {
mocks.updateSession.mockRejectedValueOnce(new Error('nope'))
renderSessionDetail()
const renameSession = await commandHandler('renameSession')
await act(async () => {
await renameSession('New name')
})
expect(mocks.showToast.error).toHaveBeenCalledWith('Rename failed: nope')
})
it('copies the complete history across pages to the clipboard', async () => {
mocks.listSessionMessages.mockImplementation(
(_sessionID: string, input: { cursor?: string } = {}) => {
if (!input.cursor) {
return Promise.resolve({
messages: [
createUserMessage('2', 'middle-marker'),
createUserMessage('3', 'newest-marker'),
],
nextCursor: 'cursor-1',
})
}
return Promise.resolve({
messages: [
createUserMessage('1', 'oldest-marker'),
createUserMessage('2', 'middle-marker'),
],
})
},
)
mocks.copyTextToClipboard.mockResolvedValue(true)
renderSessionDetail()
const copyTranscript = await commandHandler('copyTranscript')
await act(async () => {
await copyTranscript()
})
expect(mocks.listSessionMessages).toHaveBeenCalledWith(SESSION_ID, {})
expect(mocks.listSessionMessages).toHaveBeenCalledWith(SESSION_ID, { cursor: 'cursor-1' })
expect(mocks.copyTextToClipboard).toHaveBeenCalledTimes(1)
const content = await (mocks.copyTextToClipboard.mock.calls[0][0] as Promise<string>)
expect(content.match(/oldest-marker/g)).toHaveLength(1)
expect(content.match(/middle-marker/g)).toHaveLength(1)
expect(content.match(/newest-marker/g)).toHaveLength(1)
expect(content.indexOf('oldest-marker')).toBeLessThan(content.indexOf('middle-marker'))
expect(content.indexOf('middle-marker')).toBeLessThan(content.indexOf('newest-marker'))
expect(mocks.showToast.success).toHaveBeenCalledWith('Session transcript copied')
})
it('opens the side question dialog with the command argument', async () => {
const { SideQuestionDialog } = await import('@/components/session/SideQuestionDialog')
renderSessionDetail()
const askSideQuestion = await commandHandler('askSideQuestion')
await act(async () => {
await askSideQuestion('why?')
})
expect(vi.mocked(SideQuestionDialog)).toHaveBeenCalled()
const props = vi.mocked(SideQuestionDialog).mock.calls.at(-1)?.[0] as Record<string, unknown>
expect(props).toMatchObject({
open: true,
sessionID: SESSION_ID,
initialQuestion: 'why?',
})
})
it('shows the error toast when the transcript fetch fails', async () => {
mocks.listSessionMessages.mockRejectedValueOnce(new Error('page fetch failed'))
mocks.copyTextToClipboard.mockImplementation(async (content: string | Promise<string>) => {
try {
await content
return true
} catch {
return false
}
})
renderSessionDetail()
const copyTranscript = await commandHandler('copyTranscript')
await act(async () => {
await copyTranscript()
})
expect(mocks.showToast.error).toHaveBeenCalledWith('Failed to copy session transcript')
expect(mocks.showToast.success).not.toHaveBeenCalled()
})
it('opens the fork picker from the forkSession command action', async () => {
renderSessionDetail()
const forkSessionAction = await commandHandler('forkSession')
await act(async () => {
await forkSessionAction()
})
expect(await screen.findByText('Entire conversation')).toBeInTheDocument()
})
it('lists the full session history when forking', async () => {
mockTranscriptMessages([createUserMessage('1', 'first prompt')])
mocks.listSessionMessages.mockResolvedValue({
messages: [
createUserMessage('1', 'first prompt'),
createUserMessage('2', 'history-only prompt'),
],
})
renderSessionDetail()
const forkSessionAction = await commandHandler('forkSession')
await act(async () => {
await forkSessionAction()
})
expect(await screen.findByText('history-only prompt')).toBeInTheDocument()
expect(mocks.listSessionMessages).toHaveBeenCalledWith(SESSION_ID, {})
})
it('forks before the chosen message and pre-fills the composer', async () => {
mockTranscriptMessages([
createUserMessage('1', 'first prompt'),
createUserMessage('2', 'second prompt'),
])
mocks.listSessionMessages.mockResolvedValue({
messages: [
createUserMessage('1', 'first prompt'),
createUserMessage('2', 'second prompt'),
],
})
mocks.forkSession.mockResolvedValue({ id: 'session-2' })
const captured = { search: { current: '' }, pathname: { current: '' } }
renderSessionDetail(captured)
const forkSessionAction = await commandHandler('forkSession')
await act(async () => {
await forkSessionAction()
})
fireEvent.click(await screen.findByText('second prompt'))
await waitFor(() => expect(mocks.forkSession).toHaveBeenCalledWith(SESSION_ID, '2'))
expect(mocks.setPromptValue).toHaveBeenCalledWith('second prompt')
await waitFor(() => expect(captured.pathname.current).toBe('/repos/1/sessions/session-2'))
expect(mocks.showToast.success).toHaveBeenCalledWith('Session forked')
})
it('pre-fills the composer from a full-history message that is not in the loaded transcript', async () => {
mockTranscriptMessages([createUserMessage('1', 'first prompt')])
mocks.listSessionMessages.mockResolvedValue({
messages: [
createUserMessage('1', 'first prompt'),
createUserMessage('2', 'history-only prompt'),
],
})
mocks.forkSession.mockResolvedValue({ id: 'session-2' })
renderSessionDetail()
const forkSessionAction = await commandHandler('forkSession')
await act(async () => {
await forkSessionAction()
})
fireEvent.click(await screen.findByText('history-only prompt'))
await waitFor(() => expect(mocks.forkSession).toHaveBeenCalledWith(SESSION_ID, '2'))
expect(mocks.setPromptValue).toHaveBeenCalledWith('history-only prompt')
})
it('forks the entire conversation from the leading option without pre-filling', async () => {
mockTranscriptMessages([createUserMessage('1', 'first prompt')])
mocks.forkSession.mockResolvedValue({ id: 'session-2' })
renderSessionDetail()
const forkSessionAction = await commandHandler('forkSession')
await act(async () => {
await forkSessionAction()
})
fireEvent.click(await screen.findByText('Entire conversation'))
await waitFor(() => expect(mocks.forkSession).toHaveBeenCalledWith(SESSION_ID, undefined))
expect(mocks.setPromptValue).not.toHaveBeenCalled()
})
it('closes the fork picker and shows an error when the history fetch fails', async () => {
mocks.listSessionMessages.mockRejectedValueOnce(new Error('history failed'))
renderSessionDetail()
const forkSessionAction = await commandHandler('forkSession')
await act(async () => {
await forkSessionAction()
})
await waitFor(() => expect(mocks.showToast.error).toHaveBeenCalledWith('Failed to load messages'))
await waitFor(() => expect(screen.queryByText('Entire conversation')).not.toBeInTheDocument())
})
it('jumps to the chosen message from the timeline picker', async () => {
mockTranscriptMessages([
createUserMessage('1', 'first prompt'),
createUserMessage('2', 'second prompt'),
])
renderSessionDetail()
const jumpToMessage = await commandHandler('jumpToMessage')
await act(async () => {
await jumpToMessage()
})
expect(await screen.findByText('Jump to message')).toBeInTheDocument()
fireEvent.click(await screen.findByText('second prompt'))
await waitFor(() => expect(mocks.scrollIntoView).toHaveBeenCalled())
const target = document.querySelector('[data-message-id="2"]')
expect(target).not.toBeNull()
expect(mocks.scrollIntoView.mock.instances.at(-1)).toBe(target)
expect(mocks.scrollIntoView).toHaveBeenCalledWith({ block: 'start', behavior: 'smooth' })
})
it('lists only the loaded transcript in the timeline picker', async () => {
mockTranscriptMessages([createUserMessage('1', 'visible-transcript')])
mocks.listSessionMessages.mockResolvedValue({
messages: [createUserMessage('2', 'history-only prompt')],
})
renderSessionDetail()
const jumpToMessage = await commandHandler('jumpToMessage')
await act(async () => {
await jumpToMessage()
})
expect(await screen.findByText('visible-transcript')).toBeInTheDocument()
expect(screen.queryByText('history-only prompt')).not.toBeInTheDocument()
expect(mocks.listSessionMessages).not.toHaveBeenCalled()
})
it('mounts no picker while no picker mode is active', async () => {
renderSessionDetail()
await waitFor(() => expect(mocks.promptInputProps).not.toBeNull())
expect(screen.queryByText('Fork session')).not.toBeInTheDocument()
expect(screen.queryByText('Jump to message')).not.toBeInTheDocument()
expect(screen.queryByPlaceholderText('Search messages')).not.toBeInTheDocument()
})
it('opens the model picker from the showModels command action', async () => {
renderSessionDetail()
const showModels = await commandHandler('showModels')
await act(async () => {
await showModels()
})
expect(mocks.openModelPicker).toHaveBeenCalledTimes(1)
})
it('keeps commandActions referentially stable across re-renders', async () => {
const view = renderSessionDetail()
await waitFor(() => expect(mocks.promptInputProps).not.toBeNull())
const firstActions = mocks.promptInputProps?.commandActions
mockTranscriptMessages([createUserMessage('9', 'changed transcript')])
view.rerender(sessionDetailElement())
await waitFor(() => expect(mocks.promptInputProps?.commandActions).toBe(firstActions))
})
it('opens the MCP dialog from the showMcp command action', async () => {
renderSessionDetail()
const showMcp = await commandHandler('showMcp')
await act(async () => {
await showMcp()
})
expect(mocks.dialogSetters.mcp).toHaveBeenCalledWith(true)
})
it('opens the skills dialog from the showSkills command action', async () => {
renderSessionDetail()
const showSkills = await commandHandler('showSkills')
await act(async () => {
await showSkills()
})
expect(mocks.dialogSetters.skills).toHaveBeenCalledWith(true)
})
it('opens settings from the showSettings command action', async () => {
renderSessionDetail()
const showSettings = await commandHandler('showSettings')
await act(async () => {
await showSettings()
})
expect(mocks.openSettings).toHaveBeenCalledTimes(1)
})
it('maps the help command to the showSettings action', () => {
expect(BUILTIN_COMMANDS.find((command) => command.name === 'help')?.action).toBe('showSettings')
})
it('opens the providers tab from the connectProvider command action', async () => {
renderSessionDetail()
const connectProvider = await commandHandler('connectProvider')
await act(async () => {
await connectProvider()
})
expect(mocks.setSettingsTab).toHaveBeenCalledWith('providers')
})
it('exports complete history across pages in oldest-first order without duplicates', async () => {
mocks.listSessionMessages.mockImplementation(
(_sessionID: string, input: { cursor?: string } = {}) => {
if (!input.cursor) {
return Promise.resolve({
messages: [
createUserMessage('2', 'middle-marker'),
createUserMessage('3', 'newest-marker'),
],
nextCursor: 'cursor-1',
})
}
return Promise.resolve({
messages: [
createUserMessage('1', 'oldest-marker'),
createUserMessage('2', 'middle-marker'),
],
})
},
)
renderSessionDetail()
const handler = await commandHandler('exportSession')
await act(async () => {
await handler()
})
expect(mocks.listSessionMessages).toHaveBeenCalledWith(SESSION_ID, {})
expect(mocks.listSessionMessages).toHaveBeenCalledWith(SESSION_ID, { cursor: 'cursor-1' })
expect(mocks.downloadMarkdown).toHaveBeenCalledTimes(1)
const content = mocks.downloadMarkdown.mock.calls[0][0] as string
expect(content.match(/oldest-marker/g)).toHaveLength(1)
expect(content.match(/middle-marker/g)).toHaveLength(1)
expect(content.match(/newest-marker/g)).toHaveLength(1)
expect(content.indexOf('oldest-marker')).toBeLessThan(content.indexOf('middle-marker'))
expect(content.indexOf('middle-marker')).toBeLessThan(content.indexOf('newest-marker'))
expect(mocks.showToast.error).not.toHaveBeenCalled()
})
it('does not download a partial export when a later page fails', async () => {
mocks.listSessionMessages
.mockResolvedValueOnce({
messages: [createUserMessage('3', 'newest-marker')],
nextCursor: 'cursor-1',
})
.mockRejectedValueOnce(new Error('page fetch failed'))
renderSessionDetail()
const handler = await commandHandler('exportSession')
await act(async () => {
await handler()
})
expect(mocks.downloadMarkdown).not.toHaveBeenCalled()
expect(mocks.showToast.error).toHaveBeenCalledWith('Failed to export session')
expect(mocks.showToast.success).not.toHaveBeenCalled()
})
it('applies the staged-revert boundary to the complete history', async () => {
mocks.useSession.mockReturnValue({
data: createSession({ messageID: '2' }),
isLoading: false,
})
mocks.listSessionMessages.mockImplementation(
(_sessionID: string, input: { cursor?: string } = {}) => {
if (!input.cursor) {
return Promise.resolve({
messages: [
createUserMessage('2', 'middle-marker'),
createUserMessage('3', 'newest-marker'),
],
nextCursor: 'cursor-1',
})
}
return Promise.resolve({
messages: [createUserMessage('1', 'oldest-marker')],
})
},
)
renderSessionDetail()
const handler = await commandHandler('exportSession')
await act(async () => {
await handler()
})
const content = mocks.downloadMarkdown.mock.calls[0][0] as string
expect(content).toContain('oldest-marker')
expect(content).not.toContain('middle-marker')
expect(content).not.toContain('newest-marker')
})
})
@@ -1,351 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { SessionDetail } from '../SessionDetail'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
useSessionTranscript: vi.fn(),
useSSE: vi.fn(),
useRepoActivity: vi.fn(),
usePermissions: vi.fn(),
useForms: vi.fn(),
useSSEHealth: vi.fn(),
useConfig: vi.fn(),
useMobile: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(),
listSessionMessages: vi.fn(),
downloadMarkdown: vi.fn(),
showToast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
loading: vi.fn(),
promise: vi.fn(),
dismiss: vi.fn(),
},
PromptInput: vi.fn(),
}))
vi.mock('@/config', () => ({
OPENCODE_API_ENDPOINT: 'http://localhost:5551/api/opencode',
API_BASE_URL: 'http://localhost:5551',
SERVER_PORT: 5003,
OPENCODE_PORT: 5551,
FILE_LIMITS: {},
DEFAULTS: {},
ALLOWED_MIME_TYPES: [],
GIT_PROVIDERS: [],
}))
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
return {
...actual,
listSessionMessages: mocks.listSessionMessages,
}
})
vi.mock('@/lib/exportSession', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/exportSession')>()
return {
...actual,
downloadMarkdown: mocks.downloadMarkdown,
}
})
vi.mock('@/lib/toast', () => ({
showToast: mocks.showToast,
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession,
useInterruptSession: vi.fn(() => ({ mutate: vi.fn() })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
useConfig: mocks.useConfig,
useSendPrompt: vi.fn(() => ({ mutate: vi.fn() })),
useSendShell: vi.fn(() => ({ mutate: vi.fn() })),
useAgents: vi.fn(() => ({ data: [] })),
}))
vi.mock('@/hooks/useSessionTranscript', () => ({
useSessionTranscript: mocks.useSessionTranscript,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: vi.fn(() => ({ isEnabled: false })),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: vi.fn(() => ({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})),
}))
vi.mock('@/hooks/useSettingsDialog', () => ({
useSettingsDialog: vi.fn(() => ({ open: vi.fn() })),
}))
vi.mock('@/hooks/useMobile', () => ({
useMobile: mocks.useMobile,
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
}))
vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
useAutoScroll: mocks.useAutoScroll,
}))
vi.mock('@/hooks/useDialogParam', () => ({
useDialogParam: vi.fn(() => [false, vi.fn()]),
}))
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
getAssistantText: vi.fn(() => ''),
getLatestPlayableAssistantMessage: vi.fn(() => null),
useAutoPlayLastResponse: vi.fn(() => {}),
}))
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn((selector?: (state: Record<string, unknown>) => unknown) =>
typeof selector === 'function'
? selector({ isEditingMessage: false, setActivePromptFileBasePath: vi.fn() })
: false
),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
useSessionStatusForSession: mocks.useSessionStatusForSession,
}))
vi.mock('@/hooks/useSSE', () => ({
useSSE: mocks.useSSE,
}))
vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/contexts/EventContext', async (importOriginal) => {
const actual = await importOriginal()
return {
...(actual as object),
usePermissions: mocks.usePermissions,
useForms: mocks.useForms,
useSSEHealth: mocks.useSSEHealth,
}
})
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve({
id: 1,
repoUrl: 'https://github.com/test/repo',
localPath: '/test/repo',
sourcePath: null,
fullPath: '/test/repo',
branch: 'main',
currentBranch: 'main',
fullSlug: 'test/repo',
repoType: 'github' as const,
})),
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/test/repo' })),
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) }))
vi.mock('@/components/session/FormPrompt', () => ({ FormPrompt: vi.fn(() => null) }))
vi.mock('@/components/session/MinimizedFormIndicator', () => ({ MinimizedFormIndicator: vi.fn(() => null) }))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: vi.fn(() => null) }))
vi.mock('@/components/message/MessageThread', () => ({ MessageThread: vi.fn(() => null) }))
vi.mock('@/components/message/PromptInput', () => ({ PromptInput: mocks.PromptInput }))
const SESSION_ID = 'session-1'
function createUserMessage(id: string, text: string): SessionMessageInfo {
return {
id,
type: 'user',
text,
time: { created: 1000 },
} as SessionMessageInfo
}
const createSession = (revert?: { messageID: string }) => ({
id: SESSION_ID,
title: 'Export Session',
time: { created: 1000, updated: 2000 },
location: { directory: '/test/repo' },
...(revert ? { revert } : {}),
})
describe('SessionDetail export history', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSession.mockReturnValue({ data: createSession(), isLoading: false })
mocks.useSessionTranscript.mockReturnValue({
messages: [createUserMessage('4', 'visible-transcript-only')],
pending: [],
status: 'idle',
isLoading: false,
fetchOlder: vi.fn(),
hasOlder: false,
})
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
mocks.useRepoActivity.mockReturnValue(undefined)
mocks.usePermissions.mockReturnValue({ pendingCount: 0, syncForSession: vi.fn() })
mocks.useForms.mockReturnValue({
current: null,
getForSession: vi.fn(() => null),
pendingCount: 0,
reply: vi.fn(),
cancel: vi.fn(),
syncForSession: vi.fn(),
})
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useMobile.mockReturnValue(false)
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
mocks.downloadMarkdown.mockResolvedValue(true)
})
const renderSessionDetail = () =>
render(
<MemoryRouter initialEntries={[`/repos/1/sessions/${SESSION_ID}`]}>
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
const exportHandler = async () => {
await waitFor(() => expect(mocks.PromptInput).toHaveBeenCalled())
const props = mocks.PromptInput.mock.calls.at(-1)?.[0] as { onExportSession?: () => Promise<void> }
expect(props.onExportSession).toBeTypeOf('function')
return props.onExportSession!
}
it('exports complete history across pages in oldest-first order without duplicates', async () => {
mocks.listSessionMessages.mockImplementation(
(_sessionID: string, input: { cursor?: string } = {}) => {
if (!input.cursor) {
return Promise.resolve({
messages: [
createUserMessage('2', 'middle-marker'),
createUserMessage('3', 'newest-marker'),
],
nextCursor: 'cursor-1',
})
}
return Promise.resolve({
messages: [
createUserMessage('1', 'oldest-marker'),
createUserMessage('2', 'middle-marker'),
],
})
},
)
renderSessionDetail()
const handler = await exportHandler()
await act(async () => {
await handler()
})
expect(mocks.listSessionMessages).toHaveBeenCalledWith(SESSION_ID, {})
expect(mocks.listSessionMessages).toHaveBeenCalledWith(SESSION_ID, { cursor: 'cursor-1' })
expect(mocks.downloadMarkdown).toHaveBeenCalledTimes(1)
const content = mocks.downloadMarkdown.mock.calls[0][0] as string
expect(content.match(/oldest-marker/g)).toHaveLength(1)
expect(content.match(/middle-marker/g)).toHaveLength(1)
expect(content.match(/newest-marker/g)).toHaveLength(1)
expect(content.indexOf('oldest-marker')).toBeLessThan(content.indexOf('middle-marker'))
expect(content.indexOf('middle-marker')).toBeLessThan(content.indexOf('newest-marker'))
expect(mocks.showToast.error).not.toHaveBeenCalled()
})
it('does not download a partial export when a later page fails', async () => {
mocks.listSessionMessages
.mockResolvedValueOnce({
messages: [createUserMessage('3', 'newest-marker')],
nextCursor: 'cursor-1',
})
.mockRejectedValueOnce(new Error('page fetch failed'))
renderSessionDetail()
const handler = await exportHandler()
await act(async () => {
await handler()
})
expect(mocks.downloadMarkdown).not.toHaveBeenCalled()
expect(mocks.showToast.error).toHaveBeenCalledWith('Failed to export session')
expect(mocks.showToast.success).not.toHaveBeenCalled()
})
it('applies the staged-revert boundary to the complete history', async () => {
mocks.useSession.mockReturnValue({
data: createSession({ messageID: '2' }),
isLoading: false,
})
mocks.listSessionMessages.mockImplementation(
(_sessionID: string, input: { cursor?: string } = {}) => {
if (!input.cursor) {
return Promise.resolve({
messages: [
createUserMessage('2', 'middle-marker'),
createUserMessage('3', 'newest-marker'),
],
nextCursor: 'cursor-1',
})
}
return Promise.resolve({
messages: [createUserMessage('1', 'oldest-marker')],
})
},
)
renderSessionDetail()
const handler = await exportHandler()
await act(async () => {
await handler()
})
const content = mocks.downloadMarkdown.mock.calls[0][0] as string
expect(content).toContain('oldest-marker')
expect(content).not.toContain('middle-marker')
expect(content).not.toContain('newest-marker')
})
})
+15 -1
View File
@@ -5,6 +5,13 @@ import { renderHook } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { vi } from 'vitest'
import type { useSettings } from '@/hooks/useSettings'
import { BUILTIN_COMMAND_ACTIONS, type CommandActions } from '@/lib/builtinCommands'
export function createCommandActionsMock(): CommandActions {
return Object.fromEntries(
BUILTIN_COMMAND_ACTIONS.map((action) => [action, vi.fn()]),
) as unknown as CommandActions
}
export function createUseSettingsMock(
overrides: Partial<ReturnType<typeof useSettings>> = {},
@@ -52,10 +59,17 @@ export function renderHookWithRouter<T>(renderFn: () => T, initialEntries?: stri
return renderHook(renderFn, { wrapper: createRouterWrapper(initialEntries) })
}
export function LocationCatcher({ capturedSearch }: { capturedSearch: { current: string } }) {
export function LocationCatcher({
capturedSearch,
capturedPathname,
}: {
capturedSearch: { current: string }
capturedPathname?: { current: string }
}) {
const location = useLocation()
useEffect(() => {
capturedSearch.current = location.search
if (capturedPathname) capturedPathname.current = location.pathname
})
return null
}