diff --git a/docs/features/chat.md b/docs/features/chat.md index 120b6ac4..919adc6b 100644 --- a/docs/features/chat.md +++ b/docs/features/chat.md @@ -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 diff --git a/docs/features/schedules.md b/docs/features/schedules.md index adf8aa87..b689068e 100644 --- a/docs/features/schedules.md +++ b/docs/features/schedules.md @@ -163,12 +163,12 @@ This makes recurring jobs easy to review without digging through raw session dat Every run creates or attaches to a normal OpenCode session. -Use **Open session** when you want to: +Use **Open session** to continue from the generated report, answer follow-up questions, or debug provider, permission, or tool issues. -- inspect the original conversation -- continue from the generated report -- answer follow-up questions from the agent -- debug provider, permission, or tool issues +What it opens depends on where the run worked: + +- **In the repository, or still running**: the run's own session. +- **In a temporary worktree that has finished**: the worktree is removed when the run ends, so the original session can no longer do any work. Instead, a new session opens in the repository with the run's full output, any error, and the branch and commit holding the run's changes added as context. It uses your normal permissions rather than the run's unattended ones, and nothing is sent to the model until you write a message. This keeps automation connected to the rest of the OpenCode Manager workflow instead of creating a separate silo. @@ -186,7 +186,7 @@ This keeps automation connected to the rest of the OpenCode Manager workflow ins 1. Open the run from **Run History** 2. Check the **Error** tab for the failure message -3. Use **Open session** to inspect the underlying session +3. Use **Open session** to follow up on the failure with the agent 4. Verify provider credentials, model availability, and any pending agent questions or permissions ### No Assistant Output diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md index 059ddfc6..78b494de 100644 --- a/docs/getting-started/quickstart.md +++ b/docs/getting-started/quickstart.md @@ -80,15 +80,32 @@ If you already used standalone OpenCode in those repositories, existing chats ap 1. Select your repository from the sidebar 2. Click **New Session** or type `/new` 3. Type your message -4. Press **Enter** to send +4. Press **Cmd+Enter** (`Ctrl+Enter` on other platforms) to send, or **Enter** on mobile ### Useful Commands | Command | Description | |---------|-------------| -| `/help` | Show available commands | -| `/new` | Start a new session | +| `/help`, `/settings` | Open settings | +| `/new`, `/clear` | Start a new session | +| `/sessions`, `/resume`, `/continue` | List and switch between sessions | +| `/model`, `/models` | Open the model picker, also while a response is running | +| `/agent` | Switch to the next primary agent | +| `/variants` | Cycle the model's reasoning variant | | `/compact` | Reduce session context | +| `/rename [title]` | Rename the session; with no title, regenerate it | +| `/fork` | Fork the session from a chosen message, or the entire conversation | +| `/timeline` | Jump to a loaded message in the conversation | +| `/btw ` | Ask a side question without adding it to the conversation | +| `/copy` | Copy the full transcript as Markdown | +| `/export` | Download the full transcript as Markdown | +| `/undo`, `/redo` | Undo or redo the last message | +| `/details` | Toggle tool execution details | +| `/mcp` | Manage MCP servers | +| `/skills` | Load a skill | +| `/connect` | Connect a provider | + +Press **Enter** to run a command once its name is complete; use **Shift+Enter** to continue its text on a new line. Built-in commands use only the command text. Attached files and images are kept in the composer for your next message. ### File Mentions @@ -112,7 +129,8 @@ Now that you're set up, explore more features: | Shortcut | Action | |----------|--------| -| `Enter` | Send message | +| `Cmd+Enter` / `Ctrl+Enter` | Send message | +| `Enter` | Run a slash command, such as `/btw `; otherwise a new line on desktop, send on mobile | | `Shift+Enter` | New line | The app uses a configurable leader key system (`Cmd+O` on Mac, `Ctrl+O` on other platforms) for additional shortcuts. Customize in Settings > Keyboard Shortcuts. diff --git a/frontend/src/api/opencode.test.ts b/frontend/src/api/opencode.test.ts index 3bac0f44..20c1fc7b 100644 --- a/frontend/src/api/opencode.test.ts +++ b/frontend/src/api/opencode.test.ts @@ -1,11 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { activateSkill, + addSessionContext, + askSideQuestion, cancelForm, clearRevert, commitRevert, compactSession, createSession, + createSessionWithContext, deleteSession, findFiles, forkSession, @@ -26,6 +29,7 @@ import { stageRevert, switchSessionAgent, switchSessionModel, + SIDE_QUESTION_INSTRUCTIONS, } from './opencode' import { FetchError } from './fetchWrapper' @@ -172,6 +176,45 @@ describe('OpenCode facade', () => { expect(lastRequest().init.body).toBe(JSON.stringify({})) }) + it('adds context to a session without resuming the model', async () => { + fetchMock.mockResolvedValue(jsonResponse({ data: { id: 'inb_1' } })) + + await expect(addSessionContext('ses_1', 'Run output')).resolves.toBeUndefined() + + expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/synthetic') + expect(lastRequest().init.method).toBe('POST') + expect(lastRequest().init.body).toBe(JSON.stringify({ text: 'Run output', resume: false })) + }) + + it('creates a session in a directory and seeds it with context', async () => { + fetchMock + .mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') })) + .mockResolvedValueOnce(jsonResponse({ data: { id: 'inb_1' } })) + + const session = await createSessionWithContext({ directory: '/abs/repos/my-repo', title: 'Run (continued)' }, 'Run output') + + expect(session.id).toBe('ses_new') + const [createUrl, createInit] = fetchMock.mock.calls[0] ?? [] + expect(String(createUrl)).toBe('http://localhost/api/opencode/api/session') + expect((createInit as RequestInit).body).toBe(JSON.stringify({ title: 'Run (continued)', location: { directory: '/abs/repos/my-repo' } })) + const [contextUrl, contextInit] = fetchMock.mock.calls[1] ?? [] + expect(String(contextUrl)).toBe('http://localhost/api/opencode/api/session/ses_new/synthetic') + expect((contextInit as RequestInit).body).toBe(JSON.stringify({ text: 'Run output', resume: false })) + }) + + it('deletes the new session when seeding its context fails', async () => { + fetchMock + .mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') })) + .mockResolvedValueOnce(new Response('nope', { status: 400 })) + .mockResolvedValueOnce(new Response(null, { status: 204 })) + + await expect(createSessionWithContext({ directory: '/abs/repos/my-repo' }, 'Run output')).rejects.toBeInstanceOf(FetchError) + + const [deleteUrl, deleteInit] = fetchMock.mock.calls[2] ?? [] + expect(String(deleteUrl)).toBe('http://localhost/api/opencode/api/session/ses_new') + expect((deleteInit as RequestInit).method).toBe('DELETE') + }) + it('finds files through the V2 filesystem route and returns paths', async () => { fetchMock.mockResolvedValue( jsonResponse({ @@ -413,6 +456,20 @@ describe('OpenCode facade', () => { expect(lastRequest().init.method).toBe('POST') }) + it('asks a side question through the session generate route with the shared instructions', async () => { + fetchMock.mockResolvedValue(jsonResponse({ data: { text: ' answer \n' } })) + + const answer = await askSideQuestion('ses_1', 'why?') + + expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/generate') + expect(lastRequest().init.method).toBe('POST') + const body = JSON.parse(String(lastRequest().init.body)) + expect(body.prompt).toBe(`${SIDE_QUESTION_INSTRUCTIONS}\n\nwhy?`) + expect(body.prompt.startsWith(SIDE_QUESTION_INSTRUCTIONS)).toBe(true) + expect(body.prompt.endsWith('\n\nwhy?')).toBe(true) + expect(answer).toBe('answer') + }) + it('stages, commits, and clears a session revert', async () => { fetchMock.mockResolvedValue(jsonResponse({ data: { messageID: 'msg_1' } })) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 780737b7..c7456484 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -136,6 +136,21 @@ export async function forkSession(sessionID: string, before?: string): Promise { + await callOpenCode((api) => api.session.synthetic({ sessionID, text, resume: false })) +} + +export async function createSessionWithContext(input: CreateSessionInput, context: string): Promise { + const session = await createSession(input) + try { + await addSessionContext(session.id, context) + } catch (error) { + await deleteSession(session.id).catch(() => undefined) + throw error + } + return session +} + export async function switchSessionModel(sessionID: string, model: ModelRef): Promise { await callOpenCode((api) => api.session.switchModel({ sessionID, model })) } @@ -167,6 +182,23 @@ export async function runShell(sessionID: string, command: string): Promise 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 { + 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 { await callOpenCode((api) => api.session.interrupt({ sessionID })) } diff --git a/frontend/src/components/agent/AgentQuickSelect.tsx b/frontend/src/components/agent/AgentQuickSelect.tsx index e9f34890..ab659426 100644 --- a/frontend/src/components/agent/AgentQuickSelect.tsx +++ b/frontend/src/components/agent/AgentQuickSelect.tsx @@ -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) diff --git a/frontend/src/components/message/MessagePart.test.tsx b/frontend/src/components/message/MessagePart.test.tsx index ddc651e0..bbef9209 100644 --- a/frontend/src/components/message/MessagePart.test.tsx +++ b/frontend/src/components/message/MessagePart.test.tsx @@ -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) }) }) diff --git a/frontend/src/components/message/MessageThread.test.tsx b/frontend/src/components/message/MessageThread.test.tsx index d0865b26..ee75c908 100644 --- a/frontend/src/components/message/MessageThread.test.tsx +++ b/frontend/src/components/message/MessageThread.test.tsx @@ -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( + , + ) + + expect(container.querySelector('[data-message-id="user-42"]')).not.toBeNull() + }) + it('renders a projected shell message from the fixtures', () => { setupSettings({ simpleChatMode: false, showReasoning: false }) diff --git a/frontend/src/components/message/MessageThread.tsx b/frontend/src/components/message/MessageThread.tsx index f5332115..4906d311 100644 --- a/frontend/src/components/message/MessageThread.tsx +++ b/frontend/src/components/message/MessageThread.tsx @@ -398,7 +398,7 @@ const MessageRow = memo(function MessageRow({ if (!hasRenderableContent(message, simpleChatMode, showReasoning)) return null return ( -
+
({ 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 }) =>
{children}
, + ModelQuickSelect: ({ children, open }: { children?: React.ReactNode; open?: boolean }) => ( +
{children}
+ ), })) vi.mock('@/components/ui/session-status-indicator', () => ({ @@ -105,10 +119,7 @@ describe('PromptInput command submission', () => { isSessionActive: false, isStreamingResponse: false, onScrollToBottom: vi.fn(), - onShowSessionsDialog: vi.fn(), - onShowHelpDialog: vi.fn(), - onToggleDetails: vi.fn(), - onExportSession: vi.fn(), + commandActions: createCommandActionsMock(), onPromptChange: vi.fn(), } @@ -134,7 +145,7 @@ describe('PromptInput command submission', () => { mocks.runCommand.mockResolvedValue(undefined) mocks.switchSessionModel.mockResolvedValue(undefined) mocks.switchSessionAgent.mockResolvedValue(undefined) - mocks.agents = [{ name: 'reviewer', description: 'Reviewer' }] + mocks.agents = [{ id: 'reviewer', name: 'reviewer', description: 'Reviewer', mode: 'primary' }] mocks.useMobile.mockReturnValue(false) mocks.useSTT.mockReturnValue({ isRecording: false, @@ -150,7 +161,11 @@ describe('PromptInput command submission', () => { clear: vi.fn(), }) mocks.useCommands.mockReturnValue({ - filterCommands: (query: string) => query === 'review' ? [{ name: 'review', description: 'Review' }] : [], + filterCommands: (query: string) => { + if (query === 'review') return [{ name: 'review', description: 'Review' }] + const builtin = BUILTIN_COMMANDS.find((command) => command.name === query) + return builtin ? [builtin] : [] + }, }) mocks.useFileSearch.mockReturnValue({ files: [] }) mocks.useModelSelection.mockReturnValue({ @@ -163,15 +178,48 @@ describe('PromptInput command submission', () => { toggleFavorite: vi.fn(), isModelStateLoading: false, }) - mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: vi.fn() }) + mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant }) mocks.useSessionAgent.mockReturnValue({ agent: 'build' }) mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() })) - mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() })) + mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: mocks.setAgent })) mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} })) useUIState.getState().clearPendingPromptCommand() useUIState.getState().clearPendingPromptFile() }) + afterEach(() => { + Reflect.deleteProperty(window, 'matchMedia') + }) + + it('focuses the prompt on open with a fine pointer', async () => { + stubMatchMedia(true) + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + expect(input).toHaveFocus() + }) + + it('does not focus the prompt on open on touch devices', async () => { + stubMatchMedia(false) + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + expect(input).not.toHaveFocus() + }) + + it('does not take focus from an element that already has it', async () => { + stubMatchMedia(true) + const other = document.createElement('button') + document.body.appendChild(other) + other.focus() + + renderComponent() + + await screen.findByPlaceholderText('Send a message...') + expect(other).toHaveFocus() + other.remove() + }) + it('sends parsed command attachments and offsets to runCommand without injecting the selected agent', async () => { const { container } = renderComponent() @@ -211,6 +259,53 @@ describe('PromptInput command submission', () => { expect(call.skills).toEqual([]) }) + it('runs a command whose arguments span multiple lines', async () => { + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: '/review first line\nsecond line' } }) + fireEvent.click(screen.getByTitle('Send')) + + await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled()) + expect(mocks.runCommand.mock.calls[0][0]).toMatchObject({ + name: 'review', + text: 'first line\nsecond line', + }) + }) + + it('submits on plain Enter when the prompt is a known command', async () => { + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: '/btw first line\nsecond line' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + + await waitFor(() => expect(defaultProps.commandActions.askSideQuestion).toHaveBeenCalledWith('first line\nsecond line')) + }) + + it('does not submit a known command on Shift+Enter', async () => { + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: '/btw hi' } }) + fireEvent.keyDown(input, { key: 'Enter', shiftKey: true }) + + expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled() + expect(input).toHaveValue('/btw hi') + }) + + it.each(['hello there', '/bt hi', '/unknown hi'])('does not submit %j on plain Enter', async (value) => { + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value } }) + fireEvent.keyDown(input, { key: 'Enter' }) + + expect(input).toHaveValue(value) + expect(mocks.runCommand).not.toHaveBeenCalled() + expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled() + }) + it('preserves the submitted command text when the command submission fails', async () => { mocks.runCommand.mockRejectedValueOnce(new Error('command failed')) renderComponent() @@ -222,4 +317,88 @@ describe('PromptInput command submission', () => { await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled()) expect(input).toHaveValue('/review') }) + + it('switches to the next primary agent for /agent without invoking runCommand', async () => { + mocks.agents = [ + { id: 'build', name: 'build', mode: 'primary' }, + { id: 'plan', name: 'plan', mode: 'primary' }, + ] + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: '/agent' } }) + fireEvent.click(screen.getByTitle('Send')) + + await waitFor(() => expect(mocks.setAgent).toHaveBeenCalledWith('test-session', 'plan')) + expect(mocks.runCommand).not.toHaveBeenCalled() + }) + + it('reports when /variants is used with a model that has no variants', async () => { + mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant }) + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: '/variants' } }) + fireEvent.click(screen.getByTitle('Send')) + + await waitFor(() => expect(mocks.showToast.info).toHaveBeenCalledWith('The selected model has no variants')) + expect(mocks.cycleVariant).not.toHaveBeenCalled() + }) + + it('cycles variants for /variants when the model has them', async () => { + mocks.useVariants.mockReturnValue({ hasVariants: true, currentVariant: 'high', cycleVariant: mocks.cycleVariant }) + renderComponent() + + const input = await screen.findByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: '/variants' } }) + fireEvent.click(screen.getByTitle('Send')) + + await waitFor(() => expect(mocks.cycleVariant).toHaveBeenCalled()) + expect(mocks.showToast.info).not.toHaveBeenCalled() + }) + + it('opens the model picker through the imperative handle while the session is active', () => { + const queryClient = createTestQueryClient() + queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo()) + const ref = createRef() + + render( + + + + ) + + 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() + }) }) diff --git a/frontend/src/components/message/PromptInput.mention.test.tsx b/frontend/src/components/message/PromptInput.mention.test.tsx index 9b9f3ab0..b4394cf1 100644 --- a/frontend/src/components/message/PromptInput.mention.test.tsx +++ b/frontend/src/components/message/PromptInput.mention.test.tsx @@ -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({ diff --git a/frontend/src/components/message/PromptInput.stt.test.tsx b/frontend/src/components/message/PromptInput.stt.test.tsx index 833555c6..52772e9e 100644 --- a/frontend/src/components/message/PromptInput.stt.test.tsx +++ b/frontend/src/components/message/PromptInput.stt.test.tsx @@ -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(), } diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 8c649bcf..c43720b3 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -14,6 +14,7 @@ import { useSessionAgentStore } from '@/stores/sessionAgentStore' import { useUIState } from '@/stores/uiStateStore' import { useSendErrorStore } from '@/stores/sendErrorStore' import { useMobile } from '@/hooks/useMobile' +import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery' import { usePermissions } from '@/contexts/EventContext' import { ArrowDown, Upload, X, Mic, MicOff } from 'lucide-react' @@ -27,6 +28,7 @@ import { ModelQuickSelect } from '@/components/model/ModelQuickSelect' import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect' import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay' import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser' +import { getNextPrimaryAgentId } from '@/lib/primaryAgents' import { randomId } from '@/lib/utils' import { showToast } from '@/lib/toast' import { formatModelName } from '@/api/providers' @@ -35,9 +37,15 @@ import { useProviders } from '@/hooks/useProviders' import type { CommandInfo, ModelRef } from '@opencode-manager/shared/opencode' import type { FileAttachmentInfo, ImageAttachment } from '@/api/types' +import { isBuiltinCommand, type CommandActions, type PageCommandActions } from '@/lib/builtinCommands' const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"] +function parseCommandPrompt(value: string): { name: string; args?: string } | null { + const match = value.match(/^\/([a-zA-Z0-9_-]+)(?:\s+([\s\S]*))?$/) + return match ? { name: match[1], args: match[2] } : null +} + const revokeBlobUrls = (attachments: ImageAttachment[]) => { attachments.forEach((attachment) => { @@ -58,6 +66,7 @@ export interface PromptInputHandle { setPromptValue: (value: string) => void clearPrompt: () => void triggerFileUpload: () => void + openModelPicker: () => void } interface PromptInputProps { @@ -67,12 +76,7 @@ interface PromptInputProps { isSessionActive?: boolean isStreamingResponse?: boolean onScrollToBottom: () => void - onShowSessionsDialog?: () => void - onShowHelpDialog?: () => void - onToggleDetails?: () => boolean - onExportSession?: () => void - onUndo?: () => void | Promise - onRedo?: () => void | Promise + commandActions: PageCommandActions onPromptChange?: (hasContent: boolean) => void } @@ -83,12 +87,7 @@ export const PromptInput = memo(forwardRef( isSessionActive = false, isStreamingResponse = false, onScrollToBottom, - onShowSessionsDialog, - onShowHelpDialog, - onToggleDetails, - onExportSession, - onUndo, - onRedo, + commandActions, onPromptChange }, ref) { const [prompt, setPrompt] = useState('') @@ -98,6 +97,7 @@ export const PromptInput = memo(forwardRef( const [attachedFiles, setAttachedFiles] = useState(new Map()) const [imageAttachments, setImageAttachments] = useState([]) const [isDragging, setIsDragging] = useState(false) + const [isModelPickerOpen, setIsModelPickerOpen] = useState(false) const [showMentionSuggestions, setShowMentionSuggestions] = useState(false) const [mentionQuery, setMentionQuery] = useState('') const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null) @@ -139,6 +139,14 @@ export const PromptInput = memo(forwardRef( const textareaRef = useRef(null) const fileInputRef = useRef(null) const voiceButtonContainerRef = useRef(null) + const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY) + + useEffect(() => { + if (!hasFinePointer) return + const activeElement = document.activeElement + if (activeElement && activeElement !== document.body) return + textareaRef.current?.focus() + }, [hasFinePointer, sessionID]) const resetVoiceGestureState = useCallback(() => { voiceGestureStartYRef.current = null @@ -156,7 +164,7 @@ export const PromptInput = memo(forwardRef( imageAttachmentsRef.current = imageAttachments }, [attachedFiles, imageAttachments, prompt]) - const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map, submittedImageAttachments: ImageAttachment[]) => { + const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map, submittedImageAttachments: ImageAttachment[], options?: { keepAttachments?: boolean }) => { if ( promptRef.current !== submittedPrompt || attachedFilesRef.current !== submittedAttachedFiles || @@ -166,9 +174,11 @@ export const PromptInput = memo(forwardRef( } setPrompt('') - setAttachedFiles(new Map()) - revokeBlobUrls(submittedImageAttachments) - setImageAttachments([]) + if (!options?.keepAttachments) { + setAttachedFiles(new Map()) + revokeBlobUrls(submittedImageAttachments) + setImageAttachments([]) + } clearSTT() }, [clearSTT]) @@ -206,6 +216,9 @@ export const PromptInput = memo(forwardRef( }, triggerFileUpload: () => { fileInputRef.current?.click() + }, + openModelPicker: () => { + setIsModelPickerOpen(true) } }), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState]) const sessionAgent = useSessionAgent(sessionID, directory) @@ -216,6 +229,12 @@ export const PromptInput = memo(forwardRef( const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending const interruptSession = useInterruptSession() const { filterCommands } = useCommands({ directory }) + const isExactCommandPrompt = (value: string) => { + const commandPrompt = parseCommandPrompt(value) + if (!commandPrompt) return false + const [command] = filterCommands(commandPrompt.name) + return command?.name.toLowerCase() === commandPrompt.name.toLowerCase() + } const { files: searchResults } = useFileSearch( mentionQuery, @@ -331,13 +350,12 @@ export const PromptInput = memo(forwardRef( - const commandMatch = prompt.match(/^\/([a-zA-Z0-9_-]+)(?:\s+(.*))?$/) - if (commandMatch) { - const [, commandName, commandArgs] = commandMatch - const command = filterCommands(commandName)[0] + const commandPrompt = parseCommandPrompt(prompt) + if (commandPrompt) { + const command = filterCommands(commandPrompt.name)[0] if (command) { - const parsed = parsePromptToInput(commandArgs?.trim() || '', attachedFiles, agentNames, imageAttachments) + const parsed = parsePromptToInput(commandPrompt.args?.trim() || '', attachedFiles, agentNames, imageAttachments) const submittedPrompt = prompt const submittedAttachedFiles = attachedFiles const submittedImageAttachments = imageAttachments @@ -348,9 +366,14 @@ export const PromptInput = memo(forwardRef( agents: parsed.agents, skills: parsed.skills, }).then((shouldClear) => { - if (shouldClear) { - clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments) + if (!shouldClear) return + const keepAttachments = isBuiltinCommand(command) && (submittedAttachedFiles.size > 0 || submittedImageAttachments.length > 0) + if (keepAttachments) { + clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments, { keepAttachments: true }) + showToast.info('Built-in commands do not use attachments; they were kept') + return } + clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments) }) return } @@ -499,15 +522,6 @@ export const PromptInput = memo(forwardRef( setMentionRange(null) } - const handleAgentChange = (agentId: string) => { - setLocalMode(agentId) - setStoredAgent(sessionID, agentId) - const agent = agents.find(a => a.id === agentId) - if (agent?.model) { - setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.id }) - } - } - const startVoiceRecording = async () => { if (isRecording || isProcessing || isTogglingRecording) { return @@ -966,7 +980,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) } } - if (e.key === 'Enter' && (e.metaKey || e.ctrlKey || (isMobile && !e.shiftKey))) { + if (e.key === 'Enter' && !e.nativeEvent.isComposing && (e.metaKey || e.ctrlKey || (!e.shiftKey && (isMobile || isExactCommandPrompt(prompt))))) { e.preventDefault() if (isMobile) { textareaRef.current?.blur() @@ -985,9 +999,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) clearSTT() } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') { e.preventDefault() - if (hasVariants) { - cycleVariant() - } + handleCycleVariant() } } @@ -1089,18 +1101,48 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) : undefined, [model, currentVariant], ) + + const handleAgentChange = useCallback((agentId: string) => { + setLocalMode(agentId) + setStoredAgent(sessionID, agentId) + const agent = agents.find(a => a.id === agentId) + if (agent?.model) { + setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.id }) + } + }, [agents, sessionID, setStoredAgent, setStoredModel]) + + const handleCycleVariant = useCallback(() => { + if (!hasVariants) { + showToast.info('The selected model has no variants') + return + } + cycleVariant() + }, [hasVariants, cycleVariant]) + + const handleCycleAgent = useCallback(() => { + const next = getNextPrimaryAgentId(agents, currentMode) + if (!next) { + showToast.info('No primary agents available') + return + } + handleAgentChange(next) + }, [agents, currentMode, handleAgentChange]) + + const commandActionsWithPrompt = useMemo( + () => ({ + ...commandActions, + cycleAgent: handleCycleAgent, + cycleVariant: handleCycleVariant, + }), + [commandActions, handleCycleAgent, handleCycleVariant], + ) + const { executeCommand } = useCommandHandler({ sessionID, directory, model: modelRef, currentAgent: currentMode, - onShowSessionsDialog, - onShowModelsDialog: undefined, - onShowHelpDialog, - onToggleDetails, - onExportSession, - onUndo, - onRedo + actions: commandActionsWithPrompt, }) const showStopButton = isSessionActive const hideSecondaryButtons = isMobile && isSessionActive @@ -1298,6 +1340,11 @@ return (
)} + ) : ( <> @@ -1307,26 +1354,27 @@ return ( onAgentChange={handleAgentChange} isBashMode={isBashMode} /> - {isSessionActive ? ( -
- -
- ) : ( - !hideSecondaryButtons && ( - - - - ) + {isSessionActive && ( +
+ +
)} + + {!isSessionActive && !hideSecondaryButtons && ( + + )} + )}
diff --git a/frontend/src/components/model/ModelQuickSelect.test.tsx b/frontend/src/components/model/ModelQuickSelect.test.tsx index e5c333ae..af13ae3d 100644 --- a/frontend/src/components/model/ModelQuickSelect.test.tsx +++ b/frontend/src/components/model/ModelQuickSelect.test.tsx @@ -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() + + expect(screen.queryByRole('dialog', { name: 'Select model' })).not.toBeInTheDocument() + + rerender() + + expect(screen.getByRole('dialog', { name: 'Select model' })).toBeInTheDocument() + }) + + it('renders only the sheet without a trigger when no children are provided', () => { + render() + + 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() + + 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() + }) +}) diff --git a/frontend/src/components/model/ModelQuickSelect.tsx b/frontend/src/components/model/ModelQuickSelect.tsx index 423874e7..22abb04c 100644 --- a/frontend/src/components/model/ModelQuickSelect.tsx +++ b/frontend/src/components/model/ModelQuickSelect.tsx @@ -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 ( <> - !disabled && handleOpenChange(true)} data-model-select-trigger> - {children} - + {children && ( + !disabled && handleOpenChange(true)}> + {children} + + )} handleOpenChange(false)} diff --git a/frontend/src/components/schedules/RunDetailPanel.test.tsx b/frontend/src/components/schedules/RunDetailPanel.test.tsx index 3ecf3a72..58eca62c 100644 --- a/frontend/src/components/schedules/RunDetailPanel.test.tsx +++ b/frontend/src/components/schedules/RunDetailPanel.test.tsx @@ -1,7 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { render, screen, waitFor, fireEvent } from '@testing-library/react' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { MemoryRouter } from 'react-router-dom' +import { MemoryRouter, useLocation } from 'react-router-dom' import { RunDetailPanel } from './RunDetailPanel' import type { Repo } from '@/api/types' import type { ScheduleRun } from '@opencode-manager/shared/types' @@ -11,10 +11,35 @@ const mocks = vi.hoisted(() => ({ useMarkScheduleRunViewed: vi.fn(), })) +const apiMocks = vi.hoisted(() => ({ + createSessionWithContext: vi.fn(), +})) + vi.mock('@/api/repos', () => ({ getRepo: mocks.getRepo, })) +vi.mock('@/api/opencode', () => ({ + createSessionWithContext: apiMocks.createSessionWithContext, +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { + success: vi.fn(), + error: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + loading: vi.fn(), + promise: vi.fn(), + dismiss: vi.fn(), + }, +})) + +function LocationProbe() { + const location = useLocation() + return
{location.pathname}
+} + vi.mock('@/hooks/useSchedules', () => ({ useMarkScheduleRunViewed: mocks.useMarkScheduleRunViewed, })) @@ -71,6 +96,7 @@ function renderPanel(activeRun: ScheduleRun | null = run) { onCancelRun={vi.fn()} cancelRunPending={false} /> + , ) @@ -155,3 +181,78 @@ describe('RunDetailPanel local link handling', () => { expect(viewedMutate).not.toHaveBeenCalled() }) }) + +describe('RunDetailPanel open session', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: vi.fn(), isPending: false }) + mocks.getRepo.mockResolvedValue(repo) + }) + + async function clickOpenSession() { + await waitFor(() => expect(screen.getByRole('button', { name: 'Open session' })).toBeEnabled()) + fireEvent.click(screen.getByRole('button', { name: 'Open session' })) + } + + it('opens the original session for a run that worked in the repository', async () => { + renderPanel({ ...run, sessionId: 'ses_run', worktreePath: null }) + + await clickOpenSession() + + await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_run')) + expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled() + }) + + it('opens the original session while a worktree run is still running', async () => { + renderPanel({ ...run, status: 'running', sessionId: 'ses_run', worktreePath: '/abs/worktrees/run-1' }) + + await clickOpenSession() + + await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_run')) + expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled() + }) + + it('opens a new repo session seeded with the full output and branch for a finished worktree run', async () => { + apiMocks.createSessionWithContext.mockResolvedValue({ id: 'ses_new' }) + renderPanel({ + ...run, + sessionId: 'ses_run', + sessionTitle: 'Daily recap', + finishedAt: Date.UTC(2026, 9, 2), + worktreePath: '/abs/worktrees/run-1', + runBranch: 'schedule/run-1', + commitHash: 'abc123', + }) + + await clickOpenSession() + + await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_new')) + const [input, context] = apiMocks.createSessionWithContext.mock.calls[0] ?? [] + expect(input).toEqual({ directory: '/abs/repos/my-repo', title: 'Daily recap (continued)' }) + expect(context).toContain('scheduled run #1 "Daily recap", which completed and finished at 2026-10-02T00:00:00.000Z') + expect(context).toContain('branch `schedule/run-1` at commit `abc123`') + expect(context).toContain(`Run output:\n\n${run.responseText}`) + }) + + it('includes the error and notes no committed changes for a failed worktree run', async () => { + apiMocks.createSessionWithContext.mockResolvedValue({ id: 'ses_new' }) + renderPanel({ ...run, status: 'failed', responseText: null, errorText: 'Model timed out', worktreePath: '/abs/worktrees/run-1' }) + + await clickOpenSession() + + await waitFor(() => expect(apiMocks.createSessionWithContext).toHaveBeenCalled()) + const [input, context] = apiMocks.createSessionWithContext.mock.calls[0] ?? [] + expect(input).toEqual({ directory: '/abs/repos/my-repo', title: 'Scheduled run (continued)' }) + expect(context).toContain('ended as failed') + expect(context).toContain('committed no changes') + expect(context).toContain('The run produced no output.') + expect(context).toContain('Run error:\n\nModel timed out') + }) + + it('shows a single open session button', async () => { + renderPanel({ ...run, sessionId: 'ses_run', worktreePath: '/abs/worktrees/run-1' }) + + await waitFor(() => expect(screen.getByRole('button', { name: 'Open session' })).toBeEnabled()) + expect(screen.getAllByRole('button', { name: /session|repo/i })).toHaveLength(1) + }) +}) diff --git a/frontend/src/components/schedules/RunDetailPanel.tsx b/frontend/src/components/schedules/RunDetailPanel.tsx index 230a37d1..a5cdf23f 100644 --- a/frontend/src/components/schedules/RunDetailPanel.tsx +++ b/frontend/src/components/schedules/RunDetailPanel.tsx @@ -6,9 +6,11 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown' import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet' import { getRepo } from '@/api/repos' +import { createSessionWithContext } from '@/api/opencode' import { getWorkspaceFilePath } from '@/lib/markdownLinks' import { getSessionPath } from '@/lib/navigation' import { getRepoDisplayName } from '@/lib/utils' +import { showToast } from '@/lib/toast' import { useMarkScheduleRunViewed } from '@/hooks/useSchedules' import { Loader2 } from 'lucide-react' import type { ScheduleRun } from '@opencode-manager/shared/types' @@ -24,6 +26,7 @@ interface RunDetailPanelProps { export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) { const navigate = useNavigate() const [selectedFilePath, setSelectedFilePath] = useState(null) + const [openingSession, setOpeningSession] = useState(false) const { data: repo, isPending: repoPending, isError: repoError, refetch: refetchRepo } = useQuery({ queryKey: ['repo', repoId], queryFn: () => getRepo(repoId), @@ -67,6 +70,28 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel const { sessionId } = activeRun + const opensNewRepoSession = Boolean(activeRun.worktreePath) && activeRun.status !== 'running' + + const handleOpenSession = async () => { + if (!opensNewRepoSession) { + if (sessionId) navigate(getSessionPath(repoId, sessionId)) + return + } + if (!repo) return + setOpeningSession(true) + try { + const session = await createSessionWithContext( + { directory: repo.fullPath, title: `${activeRun.sessionTitle ?? 'Scheduled run'} (continued)` }, + buildRunContext(activeRun), + ) + navigate(getSessionPath(repoId, session.id)) + } catch (error) { + showToast.error(`Could not open a repository session for this run: ${error instanceof Error ? error.message : 'Unknown error'}`) + } finally { + setOpeningSession(false) + } + } + return ( <> @@ -77,8 +102,9 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel {activeRun.status === 'cancelled' ? 'Details' : 'Error'}
- {sessionId && ( - )} @@ -138,3 +164,21 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel ) } + +function buildRunContext(run: ScheduleRun): string { + const finished = run.finishedAt ? ` and finished at ${new Date(run.finishedAt).toISOString()}` : '' + const sections = [ + `Context from scheduled run #${run.id} "${run.sessionTitle ?? 'Scheduled run'}", which ${run.status === 'completed' ? 'completed' : `ended as ${run.status}`}${finished}.`, + describeRunChanges(run), + run.responseText ? `Run output:\n\n${run.responseText}` : 'The run produced no output.', + run.errorText ? `Run error:\n\n${run.errorText}` : null, + ] + return sections.filter((section): section is string => section !== null).join('\n\n') +} + +function describeRunChanges(run: ScheduleRun): string { + if (run.runBranch && run.commitHash) { + return `The run worked in a temporary worktree that has since been removed. Its changes were committed to branch \`${run.runBranch}\` at commit \`${run.commitHash}\`; they are not in this checkout unless that branch is checked out or merged.` + } + return 'The run worked in a temporary worktree that has since been removed and committed no changes.' +} diff --git a/frontend/src/components/schedules/ScheduleJobDialog.tsx b/frontend/src/components/schedules/ScheduleJobDialog.tsx index 0e3d5293..553e0c1d 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.tsx @@ -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(() => { - 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 diff --git a/frontend/src/components/session/SessionMessagePickerDialog.test.tsx b/frontend/src/components/session/SessionMessagePickerDialog.test.tsx new file mode 100644 index 00000000..aaba2f8e --- /dev/null +++ b/frontend/src/components/session/SessionMessagePickerDialog.test.tsx @@ -0,0 +1,141 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { stubMatchMedia } from '@/test/test-utils' +import { useState } from 'react' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import type { SessionMessageInfo } from '@opencode-manager/shared/opencode' +import { SessionMessagePickerDialog } from './SessionMessagePickerDialog' + +function userMessage(id: string, text: string, created = 1000): SessionMessageInfo { + return { id, type: 'user', text, time: { created } } as SessionMessageInfo +} + +function assistantMessage(id: string, text: string): SessionMessageInfo { + return { id, type: 'assistant', text, time: { created: 1000 } } as unknown as SessionMessageInfo +} + +const renderPicker = ( + props: Partial> = {}, +) => + render( + , + ) + +function FocusHost() { + const [open, setOpen] = useState(false) + return ( + <> +