mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(schedules): open repo session with run context for finished worktree runs
This commit is contained in:
1 parent
7102715068
commit
ca348f20a3
5 files changed
+221
-23
No files matched your search
@@ -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
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -136,6 +136,21 @@ export async function forkSession(sessionID: string, before?: string): Promise<S
|
||||
)
|
||||
}
|
||||
|
||||
export async function addSessionContext(sessionID: string, text: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.synthetic({ sessionID, text, resume: false }))
|
||||
}
|
||||
|
||||
export async function createSessionWithContext(input: CreateSessionInput, context: string): Promise<SessionInfo> {
|
||||
const session = await createSession(input)
|
||||
try {
|
||||
await addSessionContext(session.id, context)
|
||||
} catch (error) {
|
||||
await deleteSession(session.id).catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
export async function switchSessionModel(sessionID: string, model: ModelRef): Promise<void> {
|
||||
await callOpenCode((api) => api.session.switchModel({ sessionID, model }))
|
||||
}
|
||||
|
||||
@@ -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 <div data-testid="location">{location.pathname}</div>
|
||||
}
|
||||
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
|
||||
FileBrowserSheet: ({ isOpen, initialSelectedFile }: { isOpen: boolean; initialSelectedFile?: string }) =>
|
||||
isOpen ? <div data-testid="file-browser-sheet" data-selected-file={initialSelectedFile} /> : 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() {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RunDetailPanel
|
||||
repoId={5}
|
||||
activeRun={run}
|
||||
activeRun={activeRun}
|
||||
selectedRunLoading={false}
|
||||
onCancelRun={vi.fn()}
|
||||
cancelRunPending={false}
|
||||
/>
|
||||
<LocationProbe />
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<string | null>(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 (
|
||||
<>
|
||||
<Tabs key={`${activeRun.id}-${String(activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log')}`} defaultValue={activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log'} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
@@ -61,23 +86,22 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
|
||||
<TabsTrigger value="error" disabled={!activeRun.errorText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">{activeRun.status === 'cancelled' ? 'Details' : 'Error'}</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
{(activeRun.status === 'running' || activeRun.sessionId) && (
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{sessionId && (
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(getSessionPath(repoId, sessionId))}>
|
||||
Open session
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{activeRun.status === 'running' && (
|
||||
<Button variant="outline" size="sm" onClick={onCancelRun} disabled={cancelRunPending}>
|
||||
{cancelRunPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
Cancel run
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{(sessionId || opensNewRepoSession) && (
|
||||
<Button variant="outline" size="sm" onClick={() => { void handleOpenSession() }} disabled={openingSession || (opensNewRepoSession && !repo)}>
|
||||
{openingSession ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
Open session
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{activeRun.status === 'running' && (
|
||||
<Button variant="outline" size="sm" onClick={onCancelRun} disabled={cancelRunPending}>
|
||||
{cancelRunPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
Cancel run
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<TabsContent value="log" className="mt-0 min-h-0 flex-1 overflow-y-auto px-3 py-3 xl:[mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
@@ -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.'
|
||||
}
|
||||
Reference in new issue
Block a user