From ca348f20a3f42b117106865c59669a175954c2ba Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:52:46 -0400 Subject: [PATCH] feat(schedules): open repo session with run context for finished worktree runs --- docs/features/schedules.md | 12 +- frontend/src/api/opencode.test.ts | 41 +++++++ frontend/src/api/opencode.ts | 15 +++ .../schedules/RunDetailPanel.test.tsx | 106 +++++++++++++++++- .../components/schedules/RunDetailPanel.tsx | 70 +++++++++--- 5 files changed, 221 insertions(+), 23 deletions(-) diff --git a/docs/features/schedules.md b/docs/features/schedules.md index a572d4f7..fa9f4796 100644 --- a/docs/features/schedules.md +++ b/docs/features/schedules.md @@ -157,12 +157,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. @@ -180,7 +180,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/frontend/src/api/opencode.test.ts b/frontend/src/api/opencode.test.ts index f6ff004d..20c1fc7b 100644 --- a/frontend/src/api/opencode.test.ts +++ b/frontend/src/api/opencode.test.ts @@ -1,12 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { activateSkill, + addSessionContext, askSideQuestion, cancelForm, clearRevert, commitRevert, compactSession, createSession, + createSessionWithContext, deleteSession, findFiles, forkSession, @@ -174,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({ diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 01f3639c..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 })) } diff --git a/frontend/src/components/schedules/RunDetailPanel.test.tsx b/frontend/src/components/schedules/RunDetailPanel.test.tsx index aeeabd47..4248723f 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' @@ -10,10 +10,35 @@ const mocks = vi.hoisted(() => ({ getRepo: 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('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: ({ isOpen, initialSelectedFile }: { isOpen: boolean; initialSelectedFile?: string }) => isOpen ?
: null, @@ -48,7 +73,7 @@ const run: ScheduleRun = { worktreePath: null, } -function renderPanel() { +function renderPanel(activeRun: ScheduleRun = run) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, @@ -60,11 +85,12 @@ function renderPanel() { + , ) @@ -128,3 +154,77 @@ describe('RunDetailPanel local link handling', () => { expect(docs.getAttribute('rel')).toBe('noopener noreferrer') }) }) + +describe('RunDetailPanel open session', () => { + beforeEach(() => { + vi.clearAllMocks() + 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 dd2ad238..542934c8 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 { Loader2 } from 'lucide-react' import type { ScheduleRun } from '@opencode-manager/shared/types' @@ -23,6 +25,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), @@ -51,6 +54,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 ( <> @@ -61,23 +86,22 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel {activeRun.status === 'cancelled' ? 'Details' : 'Error'}
- {(activeRun.status === 'running' || activeRun.sessionId) && ( -
-
- {sessionId && ( - - )} -
- {activeRun.status === 'running' && ( - )}
- )} + {activeRun.status === 'running' && ( + + )} + {selectedRunLoading && !activeRun ? (
@@ -126,3 +150,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.' +}