feat: add multi-run fusion and session change walkthroughs

Fuse two to five completed multi-run entries into one synthesized session,
and explain a session's diff as ordered walkthrough stops cached by diff hash.

- Multi-run fusion service, persistence, routes and FuseRunDialog
- Change walkthrough service, persistence, routes and ChangesWalkthroughDialog
- Shared unified-diff parser plus bounded text generation, json-extract,
  text-truncate and service-error helpers
This commit is contained in:
Chris Scott committed 2026-10-06 15:27:14 -04:00
1 parent 90c6ccf236
commit b36d412ca2
66 files changed
+6228 -468

No files matched your search

@@ -0,0 +1,247 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { ChangesWalkthroughDialog } from './ChangesWalkthroughDialog'
import { FetchError } from '@/api/fetchWrapper'
import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
}))
vi.mock('@/api/changeWalkthroughs', () => ({
getChangeWalkthrough: mocks.getChangeWalkthrough,
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
}))
const walkthrough: ChangeWalkthrough = {
sessionId: 'ses_1',
diffHash: 'hash-1',
summary: 'This change adds a greeting.',
stops: [
{ title: 'Add the greeting', explanation: 'Introduces the greeting helper.', hunkIds: ['f0h0'] },
{ title: 'Wire it up', explanation: 'Calls the helper from the entry point.', hunkIds: ['f1h0'] },
],
hunks: [
{
id: 'f0h0',
file: 'src/greet.ts',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-const a = 1\n+const a = 2',
truncated: false,
},
{
id: 'f1h0',
file: 'src/main.ts',
status: 'added',
header: '@@ -0,0 +1 @@',
text: '@@ -0,0 +1 @@\n+const b = 3',
truncated: true,
},
],
omittedFiles: [{ file: 'assets/logo.png', reason: 'binary' }],
createdAt: 1,
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough, currentDiffHash: 'hash-1', stale: false, ...overrides }
}
function createWrapper() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
function renderDialog(overrides: Partial<React.ComponentProps<typeof ChangesWalkthroughDialog>> = {}) {
const onOpenChange = vi.fn()
const view = render(
<ChangesWalkthroughDialog sessionId="ses_1" open onOpenChange={onOpenChange} {...overrides} />,
{ wrapper: createWrapper() },
)
return { ...view, onOpenChange }
}
describe('ChangesWalkthroughDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('generates a walkthrough and renders the summary and first stop', async () => {
const user = userEvent.setup()
let generated = false
mocks.getChangeWalkthrough.mockImplementation(async () =>
generated ? state() : { walkthrough: null, currentDiffHash: 'hash-1', stale: false },
)
mocks.generateChangeWalkthrough.mockImplementation(async () => {
generated = true
return walkthrough
})
renderDialog()
const generate = await screen.findByRole('button', { name: 'Generate walkthrough' })
await user.click(generate)
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {})
})
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
expect(screen.getByText('Stop 1 of 2')).toBeInTheDocument()
expect(screen.getByText('src/greet.ts')).toBeInTheDocument()
expect(screen.getByText('const a = 2')).toBeInTheDocument()
expect(screen.queryByText('src/main.ts')).not.toBeInTheDocument()
expect(screen.getByText('assets/logo.png — binary file')).toBeInTheDocument()
})
it('moves through the stops with the navigator in order', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderDialog()
expect(await screen.findByText('Stop 1 of 2')).toBeInTheDocument()
expect(screen.getByText('src/greet.ts')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /previous/i })).toBeDisabled()
await user.click(screen.getByRole('button', { name: /next/i }))
expect(await screen.findByText('Stop 2 of 2')).toBeInTheDocument()
expect(screen.getByText('src/main.ts')).toBeInTheDocument()
expect(screen.queryByText('src/greet.ts')).not.toBeInTheDocument()
expect(screen.getByText('truncated')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /next/i })).toBeDisabled()
await user.click(screen.getByRole('button', { name: /previous/i }))
expect(await screen.findByText('Stop 1 of 2')).toBeInTheDocument()
})
it('shows the stale warning and regenerates', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ stale: true, currentDiffHash: 'hash-2' }))
mocks.generateChangeWalkthrough.mockResolvedValue(walkthrough)
renderDialog()
expect(
await screen.findByText('Changes have been updated since this walkthrough was generated'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /regenerate/i }))
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { regenerate: true })
})
})
it('renders the no-changes message inline', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
mocks.generateChangeWalkthrough.mockRejectedValue(
new FetchError('This session has no changes to walk through', 409, 'WALKTHROUGH_NO_CHANGES'),
)
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('This session has no text changes to walk through')).toBeInTheDocument()
})
it('renders other generation errors inline', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
mocks.generateChangeWalkthrough.mockRejectedValue(new Error('model exploded'))
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('model exploded')).toBeInTheDocument()
})
it('lists the omitted files when the diff is too large to walk through', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
mocks.generateChangeWalkthrough.mockRejectedValue(
new FetchError('These changes are too large to walk through', 413, 'WALKTHROUGH_CONTEXT_LIMIT', undefined, {
details: {
omittedFiles: [
{ file: 'src/big.ts', reason: 'budget' },
{ file: 'assets/logo.png', reason: 'binary' },
],
},
}),
)
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('These changes are too large to walk through')).toBeInTheDocument()
expect(screen.getByText('src/big.ts — over the diff budget')).toBeInTheDocument()
expect(screen.getByText('assets/logo.png — binary file')).toBeInTheDocument()
})
it('renders raw HTML in the summary and stop explanation as inert text', async () => {
const payload =
'<iframe srcdoc="&lt;script&gt;parent.document.documentElement.dataset.walkthroughProbe = 1&lt;/script&gt;"></iframe>'
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
summary: `Summary ${payload}`,
stops: [{ title: 'Stop', explanation: `Explanation ${payload}`, hunkIds: ['f0h0'] }],
},
}),
)
const { container } = renderDialog()
expect(await screen.findByText(/Summary/)).toBeInTheDocument()
expect(await screen.findByText(/Explanation/)).toBeInTheDocument()
expect(container.querySelector('iframe')).toBeNull()
expect(container.querySelector('script')).toBeNull()
expect(document.documentElement.dataset.walkthroughProbe).toBeUndefined()
})
it.each([
['WALKTHROUGH_NO_CHANGES', 'This session has no changes to walk through'],
['WALKTHROUGH_NO_TEXT_CHANGES', 'This session has no text changes to walk through'],
])('recovers from a prior %s error once changes appear and the dialog is reopened', async (code, serverMessage) => {
const user = userEvent.setup()
let generated = false
mocks.getChangeWalkthrough.mockImplementation(async () =>
generated ? state() : { walkthrough: null, currentDiffHash: null, stale: false },
)
mocks.generateChangeWalkthrough
.mockRejectedValueOnce(new FetchError(serverMessage, 409, code))
.mockImplementationOnce(async () => {
generated = true
return walkthrough
})
const { rerender, onOpenChange } = renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('This session has no text changes to walk through')).toBeInTheDocument()
rerender(<ChangesWalkthroughDialog sessionId="ses_1" open={false} onOpenChange={onOpenChange} />)
rerender(<ChangesWalkthroughDialog sessionId="ses_1" open onOpenChange={onOpenChange} />)
const generate = await screen.findByRole('button', { name: 'Generate walkthrough' })
expect(generate).toBeEnabled()
expect(screen.queryByText('This session has no text changes to walk through')).not.toBeInTheDocument()
await user.click(generate)
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
expect(screen.queryByText('This session has no text changes to walk through')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,243 @@
import { memo, useEffect, useMemo, useState } from 'react'
import { ChevronLeft, ChevronRight, Loader2, RefreshCw } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { DiffLines } from '@/components/file-browser/DiffLines'
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
import { useChangeWalkthrough, useGenerateChangeWalkthrough } from '@/hooks/useChangeWalkthrough'
import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from '@/lib/git-status-styles'
import { WalkthroughOmittedFileSchema } from '@opencode-manager/shared/schemas'
import type { WalkthroughHunk, WalkthroughOmittedFile } from '@opencode-manager/shared/schemas'
interface ChangesWalkthroughDialogProps {
sessionId: string
open: boolean
onOpenChange: (open: boolean) => void
}
function isNoChangesError(error: unknown): boolean {
const code = (error as { code?: string } | null)?.code
return code === 'WALKTHROUGH_NO_CHANGES' || code === 'WALKTHROUGH_NO_TEXT_CHANGES'
}
function isContextLimitError(error: unknown): boolean {
return (error as { code?: string } | null)?.code === 'WALKTHROUGH_CONTEXT_LIMIT'
}
function omittedFilesFromError(error: unknown): WalkthroughOmittedFile[] {
const details = (error as { details?: { omittedFiles?: unknown } } | null)?.details
const parsed = WalkthroughOmittedFileSchema.array().safeParse(details?.omittedFiles)
return parsed.success ? parsed.data : []
}
function walkthroughErrorMessage(error: unknown): string {
if (isNoChangesError(error)) {
return 'This session has no text changes to walk through'
}
if (isContextLimitError(error)) {
return 'These changes are too large to walk through'
}
return error instanceof Error ? error.message : 'Failed to load the walkthrough'
}
const OMITTED_REASON_LABELS: Record<WalkthroughOmittedFile['reason'], string> = {
binary: 'binary file',
budget: 'over the diff budget',
}
export const ChangesWalkthroughDialog = memo(function ChangesWalkthroughDialog({ sessionId, open, onOpenChange }: ChangesWalkthroughDialogProps) {
const stateQuery = useChangeWalkthrough(sessionId, open)
const generate = useGenerateChangeWalkthrough(sessionId)
const [stopIndex, setStopIndex] = useState(0)
const walkthrough = stateQuery.data?.walkthrough ?? null
const stale = stateQuery.data?.stale ?? false
const error = generate.error ?? stateQuery.error
const contextLimitFiles = isContextLimitError(error) ? omittedFilesFromError(error) : []
useEffect(() => {
generate.reset()
}, [open, sessionId, generate.reset])
useEffect(() => {
setStopIndex(0)
}, [open, sessionId, walkthrough?.createdAt])
const hunksById = useMemo(
() => new Map(walkthrough?.hunks.map((hunk) => [hunk.id, hunk]) ?? []),
[walkthrough],
)
const stops = walkthrough?.stops ?? []
const clampedIndex = stops.length > 0 ? Math.min(stopIndex, stops.length - 1) : 0
const selectedStop = stops[clampedIndex] ?? null
const selectedHunks = (selectedStop?.hunkIds ?? [])
.map((id) => hunksById.get(id))
.filter((hunk): hunk is WalkthroughHunk => hunk !== undefined)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
mobileFullscreen
keyboardAware
className="sm:max-w-3xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe"
>
<DialogHeader className="p-4 sm:p-6 border-b shrink-0">
<DialogTitle>Change walkthrough</DialogTitle>
<DialogDescription>Walk through this session's changes, explained step by step.</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-4">
{error ? (
<div className="space-y-2">
<p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p>
{contextLimitFiles.length > 0 ? (
<div className="space-y-1 rounded-md border border-border bg-muted/20 p-3">
<p className="text-xs font-medium text-muted-foreground">Omitted files</p>
{contextLimitFiles.map((omitted) => (
<p key={omitted.file} className="text-xs text-muted-foreground">
{omitted.file} — {OMITTED_REASON_LABELS[omitted.reason]}
</p>
))}
</div>
) : null}
</div>
) : null}
{stateQuery.isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : !walkthrough ? (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Generate a step-by-step walkthrough of the changes in this session.
</p>
<Button
onClick={() => generate.mutate({})}
disabled={generate.isPending}
>
{generate.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Generating walkthrough…
</>
) : (
'Generate walkthrough'
)}
</Button>
</div>
) : (
<div className="space-y-4">
{stale ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2">
<p className="text-sm text-warning">
Changes have been updated since this walkthrough was generated
</p>
<Button
variant="outline"
size="sm"
onClick={() => generate.mutate({ regenerate: true })}
disabled={generate.isPending}
>
{generate.isPending ? (
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="mr-2 h-3.5 w-3.5" />
)}
Regenerate
</Button>
</div>
) : null}
<ScheduleRunMarkdown content={walkthrough.summary} />
{stops.length > 0 ? (
<div className="space-y-3">
<ol className="space-y-1">
{stops.map((stop, index) => (
<li key={index}>
<button
type="button"
onClick={() => setStopIndex(index)}
aria-current={index === clampedIndex}
className={
index === clampedIndex
? 'w-full rounded-md bg-accent/40 px-2 py-1 text-left text-sm font-medium text-foreground'
: 'w-full rounded-md px-2 py-1 text-left text-sm text-muted-foreground hover:bg-accent/20'
}
>
{index + 1}. {stop.title}
</button>
</li>
))}
</ol>
<div className="flex items-center justify-between gap-2 border-t border-border pt-3">
<Button
variant="outline"
size="sm"
onClick={() => setStopIndex(clampedIndex - 1)}
disabled={clampedIndex === 0}
>
<ChevronLeft className="mr-1 h-3.5 w-3.5" />
Previous
</Button>
<span className="text-xs text-muted-foreground">
Stop {clampedIndex + 1} of {stops.length}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setStopIndex(clampedIndex + 1)}
disabled={clampedIndex >= stops.length - 1}
>
Next
<ChevronRight className="ml-1 h-3.5 w-3.5" />
</Button>
</div>
{selectedStop ? (
<div className="space-y-3">
<ScheduleRunMarkdown content={selectedStop.explanation} />
{selectedHunks.map((hunk) => (
<div key={hunk.id} className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5">
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">
{hunk.file}
</span>
{hunk.truncated ? (
<Badge variant="outline">truncated</Badge>
) : null}
<span className={`text-xs ${GIT_STATUS_COLORS[hunk.status]}`}>
{GIT_STATUS_LABELS[hunk.status]}
</span>
</div>
<div className="overflow-x-auto">
<DiffLines diff={hunk.text} />
</div>
</div>
))}
</div>
) : null}
</div>
) : null}
{walkthrough.omittedFiles.length > 0 ? (
<div className="space-y-1 rounded-md border border-border bg-muted/20 p-3">
<p className="text-xs font-medium text-muted-foreground">Omitted files</p>
{walkthrough.omittedFiles.map((omitted) => (
<p key={omitted.file} className="text-xs text-muted-foreground">
{omitted.file} — {OMITTED_REASON_LABELS[omitted.reason]}
</p>
))}
</div>
) : null}
</div>
)}
</div>
</DialogContent>
</Dialog>
)
})