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