diff --git a/backend/src/services/change-walkthroughs.ts b/backend/src/services/change-walkthroughs.ts index 9e372eea..471ce7da 100644 --- a/backend/src/services/change-walkthroughs.ts +++ b/backend/src/services/change-walkthroughs.ts @@ -2,6 +2,7 @@ import type { Database } from 'bun:sqlite' import { createHash } from 'node:crypto' import { z } from 'zod' import { + formatOpenCodeModelRef, isSessionNotFoundError, type FileDiffInfo, type ModelRef, @@ -38,6 +39,7 @@ import type { SSEEvent } from './sse-aggregator' const DEFAULT_TIMEOUT_MS = 120_000 const WALKTHROUGH_CALL_ATTEMPTS = 2 const WALKTHROUGH_EXPLAIN_CONCURRENCY = 4 +const WALKTHROUGH_PROMPT_VERSION = '2' const HUNK_TRUNCATION_MARKER = '\n[hunk truncated]' const TEXT_TRUNCATION_MARKER = '' const REMAINING_STOP_TITLE = 'Remaining changes' @@ -130,6 +132,26 @@ export function computeStopId(hunkIds: string[]): string { return `s_${digest.slice(0, 12)}` } +export function computeExplanationKey(modelKey: string, hunkIds: string[]): string { + const digest = createHash('sha256') + .update(`${WALKTHROUGH_PROMPT_VERSION}\0${modelKey}\0${[...hunkIds].sort().join('\n')}`) + .digest('hex') + return digest +} + +function computeModelKey(model: ModelRef | undefined): string { + return model ? formatOpenCodeModelRef(model) : 'default' +} + +function applyReuse(stop: WalkthroughStop, reusable: Map, modelKey: string): WalkthroughStop { + const key = computeExplanationKey(modelKey, stop.hunkIds) + const explanation = reusable.get(key) + if (explanation !== undefined) { + return { ...stop, explanation, status: 'ready', explanationKey: key } + } + return stop.status === 'ready' ? { ...stop, explanationKey: key } : stop +} + export function buildWalkthroughPreamble(title: string): string { return [ `You are writing a change walkthrough for a reviewer who reads it top to bottom to understand the change to "${title}".`, @@ -293,6 +315,18 @@ export function buildWalkthroughPlanPrompt({ outline: string previousStops: Array<{ title: string; hunkIds: string[] }> }): string { + const prompt = buildWalkthroughPlanSections(title, outline, previousStops).join('\n\n') + if (previousStops.length > 0 && prompt.length > WALKTHROUGH_DIFF_MAX_CHARS) { + return buildWalkthroughPlanSections(title, outline, []).join('\n\n') + } + return prompt +} + +function buildWalkthroughPlanSections( + title: string, + outline: string, + previousStops: Array<{ title: string; hunkIds: string[] }>, +): string[] { const sections = [buildWalkthroughPlanRules(title)] if (previousStops.length > 0) { sections.push( @@ -303,7 +337,7 @@ export function buildWalkthroughPlanPrompt({ ) } sections.push(`## Outline\n${outline}`) - return sections.join('\n\n') + return sections } export function buildWalkthroughOutline(input: WalkthroughInput, title: string): WalkthroughOutline { @@ -722,12 +756,33 @@ export class ChangeWalkthroughService { const diffHash = computeChangesHash(changes) this.currentHashes.set(sessionId, diffHash) - const stored = getChangeWalkthrough(this.db, sessionId) - if (stored && stored.diffHash === diffHash && !request.regenerate) { - return { walkthrough: stored, created: false } + + const previous = getChangeWalkthrough(this.db, sessionId) + const title = session.title ?? sessionId + const modelKey = computeModelKey(session.model) + const storedModel = session.model ? formatOpenCodeModelRef(session.model) : null + + if (previous && previous.diffHash === diffHash && !request.regenerate) { + if (previous.stops.every((stop) => stop.status === 'ready')) { + return { walkthrough: previous, created: false } + } + + const unfinished = previous.stops.filter((stop) => stop.status !== 'ready') + const resumed = await this.explainStops( + session, + title, + previous.summary, + unfinished, + previous.hunks, + { ...previous, model: storedModel }, + onModelStart, + ) + if (this.deletedDuringGeneration.has(sessionId)) { + throw new ChangeWalkthroughError('Session not found', 404) + } + return { walkthrough: resumed, created: true } } - const title = session.title ?? sessionId const input = buildWalkthroughInput(changes) const { hunks, mechanicalHunks, omittedFiles } = input if (hunks.length === 0 && mechanicalHunks.length === 0) { @@ -742,6 +797,7 @@ export class ChangeWalkthroughService { const walkthrough: ChangeWalkthrough = { sessionId, diffHash, + model: storedModel, summary: MECHANICAL_ONLY_SUMMARY, stops: [mechanicalStop!], hunks: mechanicalHunks, @@ -755,6 +811,15 @@ export class ChangeWalkthroughService { return { walkthrough, created: true } } + const reusable = new Map() + if (!request.regenerate && previous) { + for (const stop of previous.stops) { + if (stop.status === 'ready' && stop.explanationKey) { + reusable.set(stop.explanationKey, stop.explanation) + } + } + } + if (fitsSingleCall(input, title)) { const prompt = buildWalkthroughPrompt({ title, hunks }) onModelStart() @@ -763,11 +828,13 @@ export class ChangeWalkthroughService { parseWalkthroughResponse(text, hunks), ) + const stops = parsed.stops.map((stop) => applyReuse(stop, reusable, modelKey)) const walkthrough: ChangeWalkthrough = { sessionId, diffHash, + model: storedModel, summary: parsed.summary, - stops: mechanicalStop ? [...parsed.stops, mechanicalStop] : parsed.stops, + stops: mechanicalStop ? [...stops, mechanicalStop] : stops, hunks: [...hunks, ...mechanicalHunks], omittedFiles, createdAt: Date.now(), @@ -791,6 +858,7 @@ export class ChangeWalkthroughService { const walkthrough: ChangeWalkthrough = { sessionId, diffHash, + model: storedModel, summary: MECHANICAL_ONLY_SUMMARY, stops: [mechanicalStop], hunks: mechanicalHunks, @@ -804,18 +872,28 @@ export class ChangeWalkthroughService { return { walkthrough, created: true } } - const planPrompt = buildWalkthroughPlanPrompt({ title, outline: outline.outline, previousStops: [] }) + const outlineIds = new Set(outline.hunks.map((hunk) => hunk.id)) + const previousStops = + !request.regenerate && previous + ? previous.stops + .filter((stop) => stop.hunkIds.length > 0 && stop.hunkIds.every((id) => outlineIds.has(id))) + .map((stop) => ({ title: stop.title, hunkIds: stop.hunkIds })) + : [] + + const planPrompt = buildWalkthroughPlanPrompt({ title, outline: outline.outline, previousStops }) onModelStart() const planned = await this.callModelParsed(planPrompt, session.model, (text) => parseWalkthroughPlan(text, outline.hunks), ) + const stops = planned.stops.map((stop) => applyReuse(stop, reusable, modelKey)) let walkthrough: ChangeWalkthrough = { sessionId, diffHash, + model: storedModel, summary: planned.summary, - stops: mechanicalStop ? [...planned.stops, mechanicalStop] : planned.stops, + stops: mechanicalStop ? [...stops, mechanicalStop] : stops, hunks: [...outline.hunks, ...mechanicalHunks], omittedFiles: outline.omittedFiles, createdAt: Date.now(), @@ -825,26 +903,18 @@ export class ChangeWalkthroughService { throw new ChangeWalkthroughError('Session not found', 404) } - await mapWithConcurrency(planned.stops, WALKTHROUGH_EXPLAIN_CONCURRENCY, async (stop) => { - const explainPrompt = buildWalkthroughExplainPrompt({ + const pending = stops.filter((stop) => stop.status !== 'ready') + if (pending.length > 0) { + walkthrough = await this.explainStops( + session, title, - summary: planned.summary, - stop, - hunks: outline.hunks, - }) - - let explained: WalkthroughStop - try { - const explanation = await this.callModelParsed(explainPrompt, session.model, parseWalkthroughExplanation) - explained = { ...stop, explanation, status: 'ready' } - } catch (error) { - logger.warn('Failed to explain a change walkthrough stop', getErrorMessage(error)) - explained = { ...stop, status: 'failed' } - } - - walkthrough = this.replaceStop(walkthrough, explained) - this.saveIfSessionLive(walkthrough) - }) + planned.summary, + pending, + outline.hunks, + walkthrough, + onModelStart, + ) + } if (this.deletedDuringGeneration.has(sessionId)) { throw new ChangeWalkthroughError('Session not found', 404) @@ -853,6 +923,43 @@ export class ChangeWalkthroughService { return { walkthrough, created: true } } + private async explainStops( + session: SessionInfo, + title: string, + summary: string, + stops: WalkthroughStop[], + hunks: WalkthroughHunk[], + walkthrough: ChangeWalkthrough, + onModelStart: () => void, + ): Promise { + const modelKey = computeModelKey(session.model) + let current = walkthrough + + await mapWithConcurrency(stops, WALKTHROUGH_EXPLAIN_CONCURRENCY, async (stop) => { + const explainPrompt = buildWalkthroughExplainPrompt({ title, summary, stop, hunks }) + onModelStart() + + let explained: WalkthroughStop + try { + const explanation = await this.callModelParsed(explainPrompt, session.model, parseWalkthroughExplanation) + explained = { + ...stop, + explanation, + status: 'ready', + explanationKey: computeExplanationKey(modelKey, stop.hunkIds), + } + } catch (error) { + logger.warn('Failed to explain a change walkthrough stop', getErrorMessage(error)) + explained = { ...stop, status: 'failed' } + } + + current = this.replaceStop(current, explained) + this.saveIfSessionLive(current) + }) + + return current + } + private async callModelParsed( prompt: string, model: ModelRef | undefined, diff --git a/backend/test/db/change-walkthroughs.test.ts b/backend/test/db/change-walkthroughs.test.ts index 5fd86925..bde49bcc 100644 --- a/backend/test/db/change-walkthroughs.test.ts +++ b/backend/test/db/change-walkthroughs.test.ts @@ -16,6 +16,7 @@ function walkthrough(overrides: Partial = {}): ChangeWalkthro return { sessionId: SESSION_ID, diffHash: 'hash-1', + model: null, summary: 'A short summary', stops: [ { id: 's_1', title: 'First stop', explanation: 'Why it matters', hunkIds: ['h_1'], status: 'ready', explanationKey: null }, diff --git a/backend/test/services/change-walkthroughs.test.ts b/backend/test/services/change-walkthroughs.test.ts index 7142e495..6d17a21c 100644 --- a/backend/test/services/change-walkthroughs.test.ts +++ b/backend/test/services/change-walkthroughs.test.ts @@ -114,6 +114,25 @@ const LARGE_PLAN_REPLY = planReply([ { title: 'C', hunkIds: [20, 21, 22, 23].map((index) => computeHunkId('src/c.ts', 'modified', bigHunk(index))) }, ]) +const EDITED_A_HUNKS = [0, 1, 2, 3].map((index) => bigHunk(index, WALKTHROUGH_HUNK_MAX_CHARS - 10)) + +const EDITED_LARGE_CHANGES: FileDiffInfo[] = [ + change('src/a.ts', EDITED_A_HUNKS.join('\n')), + change('src/b.ts', [10, 11, 12, 13].map((index) => bigHunk(index)).join('\n')), + change('src/c.ts', [20, 21, 22, 23].map((index) => bigHunk(index)).join('\n')), +] + +const EDITED_LARGE_PLAN_REPLY = planReply([ + { title: 'A', hunkIds: EDITED_A_HUNKS.map((hunk) => computeHunkId('src/a.ts', 'modified', hunk)) }, + { title: 'B', hunkIds: [10, 11, 12, 13].map((index) => computeHunkId('src/b.ts', 'modified', bigHunk(index))) }, + { title: 'C', hunkIds: [20, 21, 22, 23].map((index) => computeHunkId('src/c.ts', 'modified', bigHunk(index))) }, +]) + +function explanationFor(prompt: string): string { + const title = prompt.match(/## Stop: (.+)/)?.[1] ?? '' + return JSON.stringify({ explanation: `explained-${title}` }) +} + interface FakeSession { info?: SessionInfo | Error changes?: FileDiffInfo[] | Error @@ -529,6 +548,18 @@ describe('buildWalkthroughPlanPrompt', () => { expect(prompt).toContain('Previous stops') expect(prompt).toContain('A: h_1') }) + + it('drops previous stops when they would push the prompt over the diff budget', () => { + const prompt = buildWalkthroughPlanPrompt({ + title: 'My session', + outline, + previousStops: [{ title: 'T'.repeat(WALKTHROUGH_DIFF_MAX_CHARS), hunkIds: ['h_1'] }], + }) + + expect(prompt).not.toContain('Previous stops') + expect(prompt).toContain(outline) + expect(prompt.length).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS) + }) }) describe('parseWalkthroughPlan', () => { @@ -1128,6 +1159,141 @@ describe('ChangeWalkthroughService', () => { expect(fake.generateCalls.filter((prompt) => prompt.includes('## Stop: B'))).toHaveLength(2) }) + it('reuses explanations for unchanged stops after an edit', async () => { + sessions[SESSION_ID]!.changes = LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + const first = await service.generate(SESSION_ID, {}) + expect(first.walkthrough.stops.every((stop) => stop.status === 'ready')).toBe(true) + const callsAfterFirst = fake.generateCalls.length + expect(callsAfterFirst).toBe(4) + + sessions[SESSION_ID]!.changes = EDITED_LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? EDITED_LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + const second = await service.generate(SESSION_ID, {}) + + expect(second.created).toBe(true) + const secondCalls = fake.generateCalls.slice(callsAfterFirst) + expect(secondCalls).toHaveLength(2) + expect(secondCalls.filter((prompt) => prompt.includes(PLAN_MARKER))).toHaveLength(1) + expect(secondCalls.filter((prompt) => prompt.includes('## Stop: A'))).toHaveLength(1) + expect(secondCalls.filter((prompt) => prompt.includes('## Stop: B'))).toHaveLength(0) + expect(secondCalls.filter((prompt) => prompt.includes('## Stop: C'))).toHaveLength(0) + + const byTitle = new Map(second.walkthrough.stops.map((stop) => [stop.title, stop])) + expect(byTitle.get('A')!.explanation).toBe('explained-A') + expect(byTitle.get('B')!.explanation).toBe('explained-B') + expect(byTitle.get('C')!.explanation).toBe('explained-C') + expect(second.walkthrough.stops.every((stop) => stop.status === 'ready')).toBe(true) + }) + + it('retries only failed stops on an unchanged diff', async () => { + sessions[SESSION_ID]!.changes = LARGE_CHANGES + fake.setGenerateImpl((prompt) => { + if (prompt.includes(PLAN_MARKER)) { + return Promise.resolve(LARGE_PLAN_REPLY) + } + if (prompt.includes('## Stop: B')) { + return Promise.resolve('not json') + } + return Promise.resolve(explanationFor(prompt)) + }) + + const first = await service.generate(SESSION_ID, {}) + const firstByTitle = new Map(first.walkthrough.stops.map((stop) => [stop.title, stop])) + expect(firstByTitle.get('B')!.status).toBe('failed') + const callsAfterFirst = fake.generateCalls.length + + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + const second = await service.generate(SESSION_ID, {}) + + expect(second.created).toBe(true) + const secondCalls = fake.generateCalls.slice(callsAfterFirst) + expect(secondCalls).toHaveLength(1) + expect(secondCalls[0]).toContain('## Stop: B') + expect(secondCalls.filter((prompt) => prompt.includes(PLAN_MARKER))).toHaveLength(0) + + const secondByTitle = new Map(second.walkthrough.stops.map((stop) => [stop.title, stop])) + expect(secondByTitle.get('B')!.status).toBe('ready') + expect(secondByTitle.get('A')!.explanation).toBe('explained-A') + expect(secondByTitle.get('C')!.explanation).toBe('explained-C') + }) + + it('regenerate ignores previous explanations', async () => { + sessions[SESSION_ID]!.changes = LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + await service.generate(SESSION_ID, {}) + const callsAfterFirst = fake.generateCalls.length + + await service.generate(SESSION_ID, { regenerate: true }) + + expect(fake.generateCalls.length - callsAfterFirst).toBe(4) + }) + + it('does not reuse explanations across models', async () => { + sessions[SESSION_ID]!.info = { + id: SESSION_ID, + title: 'Title', + model: { providerID: 'anthropic', id: 'claude-sonnet-4' }, + } as SessionInfo + sessions[SESSION_ID]!.changes = LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + await service.generate(SESSION_ID, {}) + const callsAfterFirst = fake.generateCalls.length + + sessions[SESSION_ID]!.info = { + id: SESSION_ID, + title: 'Title', + model: { providerID: 'openai', id: 'gpt-5' }, + } as SessionInfo + sessions[SESSION_ID]!.changes = EDITED_LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? EDITED_LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + await service.generate(SESSION_ID, {}) + + expect(fake.generateCalls.length - callsAfterFirst).toBe(4) + }) + + it('lists surviving previous stops in the plan prompt', async () => { + sessions[SESSION_ID]!.changes = LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + await service.generate(SESSION_ID, {}) + const callsAfterFirst = fake.generateCalls.length + + sessions[SESSION_ID]!.changes = EDITED_LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? EDITED_LARGE_PLAN_REPLY : explanationFor(prompt)), + ) + + await service.generate(SESSION_ID, {}) + + const planPrompt = fake.generateCalls.slice(callsAfterFirst).find((prompt) => prompt.includes(PLAN_MARKER)) + expect(planPrompt).toBeDefined() + expect(planPrompt).toContain('Previous stops') + expect(planPrompt).toContain('- B:') + expect(planPrompt).toContain('- C:') + expect(planPrompt).not.toContain('- A:') + }) + it('keeps a single call for small diffs', async () => { fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }]), diff --git a/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx b/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx index 99c86419..5afbab7d 100644 --- a/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx +++ b/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx @@ -20,6 +20,7 @@ vi.mock('@/api/changeWalkthroughs', () => ({ const walkthrough: ChangeWalkthrough = { sessionId: 'ses_1', diffHash: 'hash-1', + model: null, summary: 'This change adds a greeting.', stops: [ { diff --git a/frontend/src/hooks/useChangeWalkthrough.test.tsx b/frontend/src/hooks/useChangeWalkthrough.test.tsx index 2439cbaa..2889f533 100644 --- a/frontend/src/hooks/useChangeWalkthrough.test.tsx +++ b/frontend/src/hooks/useChangeWalkthrough.test.tsx @@ -18,6 +18,7 @@ vi.mock('@/api/changeWalkthroughs', () => ({ const walkthroughForA: ChangeWalkthrough = { sessionId: 'ses_A', diffHash: 'hash-a', + model: null, summary: 'A summary', stops: [], hunks: [], diff --git a/shared/src/schemas/change-walkthroughs.ts b/shared/src/schemas/change-walkthroughs.ts index c1d90ca5..37935de0 100644 --- a/shared/src/schemas/change-walkthroughs.ts +++ b/shared/src/schemas/change-walkthroughs.ts @@ -41,6 +41,7 @@ export type WalkthroughOmittedFile = z.infer