diff --git a/backend/src/services/change-walkthroughs.ts b/backend/src/services/change-walkthroughs.ts index 57a5d16c..9e372eea 100644 --- a/backend/src/services/change-walkthroughs.ts +++ b/backend/src/services/change-walkthroughs.ts @@ -28,6 +28,8 @@ import { getErrorMessage } from '../utils/error-utils' import { ServiceError } from '../utils/service-error' import { truncateText } from '../utils/text-truncate' import { extractFirstJsonObject } from '../utils/json-extract' +import { mapWithConcurrency } from '../utils/concurrency' +import { logger } from '../utils/logger' import { GenerateTextTimeoutError, generateTextWithTimeout } from './opencode/generate-text' import type { OpenCodeClient } from './opencode/client' import { readSessionChanges } from './session-changes' @@ -35,6 +37,7 @@ import type { SSEEvent } from './sse-aggregator' const DEFAULT_TIMEOUT_MS = 120_000 const WALKTHROUGH_CALL_ATTEMPTS = 2 +const WALKTHROUGH_EXPLAIN_CONCURRENCY = 4 const HUNK_TRUNCATION_MARKER = '\n[hunk truncated]' const TEXT_TRUNCATION_MARKER = '' const REMAINING_STOP_TITLE = 'Remaining changes' @@ -476,6 +479,79 @@ export function parseWalkthroughPlan(text: string, hunks: WalkthroughHunk[]): Pa } } +const explanationSchema = z.object({ + explanation: z.string().catch(''), +}) + +export function parseWalkthroughExplanation(text: string): string | null { + const extracted = extractFirstJsonObject(text) + if (!extracted) { + return null + } + + let raw: unknown + try { + raw = JSON.parse(extracted) + } catch { + return null + } + + const parsed = explanationSchema.safeParse(raw) + if (!parsed.success) { + return null + } + + const explanation = parsed.data.explanation.trim() + if (explanation.length === 0) { + return null + } + + return truncateText(explanation, WALKTHROUGH_TEXT_MAX_CHARS, TEXT_TRUNCATION_MARKER).text +} + +export function buildWalkthroughExplainPrompt({ + title, + summary, + stop, + hunks, +}: { + title: string + summary: string + stop: WalkthroughStop + hunks: WalkthroughHunk[] +}): string { + const rule = 'Respond with only the JSON {"explanation": string}.' + const stopHunks = hunks.filter((hunk) => stop.hunkIds.includes(hunk.id)) + const context = [ + buildWalkthroughPreamble(title), + `## Walkthrough summary\n${summary}`, + `## Stop: ${stop.title}`, + ].join('\n\n') + + const sections = [context] + let shown = 0 + + for (const hunk of stopHunks) { + const block = formatHunkBlock(hunk) + const omittedCount = stopHunks.length - shown - 1 + const candidate = [...sections, block, rule] + if (omittedCount > 0) { + candidate.push(`${omittedCount} more hunks in this stop are not shown.`) + } + if (candidate.join('\n\n').length > WALKTHROUGH_DIFF_MAX_CHARS) { + break + } + sections.push(block) + shown += 1 + } + + if (shown < stopHunks.length) { + sections.push(`${stopHunks.length - shown} more hunks in this stop are not shown.`) + } + sections.push(rule) + return sections.join('\n\n') +} + interface InFlightGeneration { modelStarted: Promise result: Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> @@ -498,6 +574,7 @@ export class ChangeWalkthroughService { private readonly failures = new Map() private readonly deletedDuringGeneration = new Set() private readonly currentHashes = new Map() + private readonly hashEpochs = new Map() private readonly timeoutMs: number constructor( @@ -531,16 +608,24 @@ export class ChangeWalkthroughService { return cached } + const epoch = this.hashEpochs.get(sessionId) ?? 0 try { const changes = await readSessionChanges(this.openCodeClient, sessionId) const hash = computeChangesHash(changes) - this.currentHashes.set(sessionId, hash) + if ((this.hashEpochs.get(sessionId) ?? 0) === epoch) { + this.currentHashes.set(sessionId, hash) + } return hash } catch { return null } } + private invalidateCurrentHash(sessionId: string): void { + this.currentHashes.delete(sessionId) + this.hashEpochs.set(sessionId, (this.hashEpochs.get(sessionId) ?? 0) + 1) + } + generate(sessionId: string, request: GenerateChangeWalkthroughRequest): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> { return this.begin(sessionId, request).result } @@ -560,7 +645,7 @@ export class ChangeWalkthroughService { this.deletedDuringGeneration.add(sessionID) } this.failures.delete(sessionID) - this.currentHashes.delete(sessionID) + this.invalidateCurrentHash(sessionID) deleteChangeWalkthrough(this.db, sessionID) return } @@ -568,7 +653,7 @@ export class ChangeWalkthroughService { case 'session.execution.succeeded': case 'session.execution.failed': case 'session.execution.interrupted': - this.currentHashes.delete(event.data.sessionID) + this.invalidateCurrentHash(event.data.sessionID) return default: return @@ -603,7 +688,7 @@ export class ChangeWalkthroughService { .finally(() => { this.inFlight.delete(sessionId) this.deletedDuringGeneration.delete(sessionId) - this.currentHashes.delete(sessionId) + this.invalidateCurrentHash(sessionId) }) result.catch(() => {}) @@ -664,48 +749,107 @@ export class ChangeWalkthroughService { createdAt: Date.now(), } - if (this.deletedDuringGeneration.has(sessionId)) { + if (!this.saveIfSessionLive(walkthrough)) { throw new ChangeWalkthroughError('Session not found', 404) } - - saveChangeWalkthrough(this.db, walkthrough) return { walkthrough, created: true } } - if (!fitsSingleCall(input, title)) { - const budgetFiles = [...new Set(hunks.map((hunk) => hunk.file))].map((file) => ({ - file, - reason: 'budget' as const, - })) - throw new ChangeWalkthroughError('These changes are too large to walk through', 413, { - code: 'WALKTHROUGH_CONTEXT_LIMIT', - details: { omittedFiles: [...omittedFiles, ...budgetFiles] }, - }) + if (fitsSingleCall(input, title)) { + const prompt = buildWalkthroughPrompt({ title, hunks }) + onModelStart() + + const parsed = await this.callModelParsed(prompt, session.model, (text) => + parseWalkthroughResponse(text, hunks), + ) + + const walkthrough: ChangeWalkthrough = { + sessionId, + diffHash, + summary: parsed.summary, + stops: mechanicalStop ? [...parsed.stops, mechanicalStop] : parsed.stops, + hunks: [...hunks, ...mechanicalHunks], + omittedFiles, + createdAt: Date.now(), + } + + if (!this.saveIfSessionLive(walkthrough)) { + throw new ChangeWalkthroughError('Session not found', 404) + } + return { walkthrough, created: true } } - const prompt = buildWalkthroughPrompt({ title, hunks }) + const outline = buildWalkthroughOutline(input, title) + if (outline.hunks.length === 0) { + if (!mechanicalStop) { + throw new ChangeWalkthroughError('These changes are too large to walk through', 413, { + code: 'WALKTHROUGH_CONTEXT_LIMIT', + details: { omittedFiles: outline.omittedFiles }, + }) + } + const walkthrough: ChangeWalkthrough = { + sessionId, + diffHash, + summary: MECHANICAL_ONLY_SUMMARY, + stops: [mechanicalStop], + hunks: mechanicalHunks, + omittedFiles: outline.omittedFiles, + createdAt: Date.now(), + } + + if (!this.saveIfSessionLive(walkthrough)) { + throw new ChangeWalkthroughError('Session not found', 404) + } + return { walkthrough, created: true } + } + + const planPrompt = buildWalkthroughPlanPrompt({ title, outline: outline.outline, previousStops: [] }) onModelStart() - const parsed = await this.callModelParsed(prompt, session.model, (text) => - parseWalkthroughResponse(text, hunks), + const planned = await this.callModelParsed(planPrompt, session.model, (text) => + parseWalkthroughPlan(text, outline.hunks), ) - const walkthrough: ChangeWalkthrough = { + let walkthrough: ChangeWalkthrough = { sessionId, diffHash, - summary: parsed.summary, - stops: mechanicalStop ? [...parsed.stops, mechanicalStop] : parsed.stops, - hunks: [...hunks, ...mechanicalHunks], - omittedFiles, + summary: planned.summary, + stops: mechanicalStop ? [...planned.stops, mechanicalStop] : planned.stops, + hunks: [...outline.hunks, ...mechanicalHunks], + omittedFiles: outline.omittedFiles, createdAt: Date.now(), } + if (!this.saveIfSessionLive(walkthrough)) { + throw new ChangeWalkthroughError('Session not found', 404) + } + + await mapWithConcurrency(planned.stops, WALKTHROUGH_EXPLAIN_CONCURRENCY, async (stop) => { + const explainPrompt = buildWalkthroughExplainPrompt({ + 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) + }) + if (this.deletedDuringGeneration.has(sessionId)) { throw new ChangeWalkthroughError('Session not found', 404) } - saveChangeWalkthrough(this.db, walkthrough) return { walkthrough, created: true } } @@ -746,6 +890,21 @@ export class ChangeWalkthroughService { throw lastError } + private replaceStop(walkthrough: ChangeWalkthrough, stop: WalkthroughStop): ChangeWalkthrough { + return { + ...walkthrough, + stops: walkthrough.stops.map((existing) => (existing.id === stop.id ? stop : existing)), + } + } + + private saveIfSessionLive(walkthrough: ChangeWalkthrough): boolean { + if (this.deletedDuringGeneration.has(walkthrough.sessionId)) { + return false + } + saveChangeWalkthrough(this.db, walkthrough) + return true + } + private async readSession(sessionId: string): Promise { try { return await this.openCodeClient.api.session.get({ sessionID: sessionId }) diff --git a/backend/src/utils/concurrency.ts b/backend/src/utils/concurrency.ts new file mode 100644 index 00000000..c338a800 --- /dev/null +++ b/backend/src/utils/concurrency.ts @@ -0,0 +1,23 @@ +export async function mapWithConcurrency( + items: T[], + limit: number, + fn: (item: T, index: number) => Promise, +): Promise { + const results = new Array(items.length) + const workerCount = Math.max(1, Math.min(limit, items.length)) + let nextIndex = 0 + + const worker = async (): Promise => { + while (true) { + const index = nextIndex + nextIndex += 1 + if (index >= items.length) { + return + } + results[index] = await fn(items[index]!, index) + } + } + + await Promise.all(Array.from({ length: workerCount }, () => worker())) + return results +} diff --git a/backend/test/services/change-walkthroughs.test.ts b/backend/test/services/change-walkthroughs.test.ts index 70c89c98..7142e495 100644 --- a/backend/test/services/change-walkthroughs.test.ts +++ b/backend/test/services/change-walkthroughs.test.ts @@ -48,7 +48,7 @@ function hunkPatch(line: number): string { } function bigHunk(index: number, size = WALKTHROUGH_HUNK_MAX_CHARS): string { - return `@@ -${index},1 +${index},1 @@\n+${'x'.repeat(size)}` + return `@@ -${index},1 +${index},1 @@\n+${'x'.repeat(size)}_${index}` } function longHunk(index: number): string { @@ -99,6 +99,21 @@ const THREE_HUNK_IDS = [ computeHunkId('src/b.ts', 'modified', hunkPatch(1)), ] +const PLAN_MARKER = 'Assign every hunk id' +const EXPLANATION_REPLY = JSON.stringify({ explanation: 'Why' }) + +const LARGE_CHANGES: FileDiffInfo[] = [ + change('src/a.ts', [0, 1, 2, 3].map((index) => bigHunk(index)).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 LARGE_PLAN_REPLY = planReply([ + { title: 'A', hunkIds: [0, 1, 2, 3].map((index) => computeHunkId('src/a.ts', 'modified', bigHunk(index))) }, + { 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))) }, +]) + interface FakeSession { info?: SessionInfo | Error changes?: FileDiffInfo[] | Error @@ -107,7 +122,7 @@ interface FakeSession { function createFakeClient(sessions: Record) { const generateCalls: string[] = [] const generateModels: Array = [] - let generateImpl: () => Promise = async () => modelReply([]) + let generateImpl: (prompt: string) => Promise = async () => modelReply([]) const client = { api: { @@ -143,7 +158,7 @@ function createFakeClient(sessions: Record) { text: vi.fn(async (input: { prompt: string; model?: ModelRef }) => { generateCalls.push(input.prompt) generateModels.push(input.model) - return { text: await generateImpl() } + return { text: await generateImpl(input.prompt) } }), }, }, @@ -154,7 +169,7 @@ function createFakeClient(sessions: Record) { client, generateCalls, generateModels, - setGenerateImpl: (impl: () => Promise) => { + setGenerateImpl: (impl: (prompt: string) => Promise) => { generateImpl = impl }, } @@ -954,9 +969,12 @@ describe('ChangeWalkthroughService', () => { }) }) - it('rejects with 413 and the omitted files when a text file exceeds the context budget', async () => { + it('rejects with 413 and the omitted files when the outline admits no hunk', async () => { const file = 'src/huge.ts' - const patch = Array.from({ length: 10 }, (_, index) => bigHunk(index)).join('\n') + const patch = Array.from( + { length: 2000 }, + (_, index) => `@@ -${index + 1},1 +${index + 1},1 @@\n+line${index}`, + ).join('\n') sessions[SESSION_ID]!.changes = [change(file, patch)] await expect(service.generate(SESSION_ID, {})).rejects.toMatchObject({ @@ -1042,6 +1060,105 @@ describe('ChangeWalkthroughService', () => { await expect(service.generate('ses_missing', {})).rejects.toMatchObject({ status: 404 }) }) + it('plans then explains each stop', async () => { + sessions[SESSION_ID]!.changes = LARGE_CHANGES + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : EXPLANATION_REPLY), + ) + + const { walkthrough, created } = await service.generate(SESSION_ID, {}) + + expect(created).toBe(true) + expect(walkthrough.stops.map((stop) => stop.title)).toEqual(['A', 'B', 'C']) + expect(walkthrough.stops.every((stop) => stop.status === 'ready')).toBe(true) + expect(walkthrough.stops.every((stop) => stop.explanation === 'Why')).toBe(true) + expect(fake.generateCalls).toHaveLength(4) + expect(fake.generateCalls.filter((prompt) => prompt.includes(PLAN_MARKER))).toHaveLength(1) + }) + + it('exposes pending stops while explaining', async () => { + sessions[SESSION_ID]!.changes = LARGE_CHANGES + const explainResolvers: Array<(text: string) => void> = [] + fake.setGenerateImpl((prompt) => { + if (prompt.includes(PLAN_MARKER)) { + return Promise.resolve(LARGE_PLAN_REPLY) + } + return new Promise((resolve) => { + explainResolvers.push(resolve) + }) + }) + + const pending = service.generate(SESSION_ID, {}) + + await vi.waitFor(async () => { + const state = await service.getState(SESSION_ID) + expect(state.generating).toBe(true) + expect(state.walkthrough?.stops).toHaveLength(3) + expect(state.walkthrough?.stops.every((stop) => stop.status === 'pending')).toBe(true) + }) + + await vi.waitFor(() => expect(explainResolvers).toHaveLength(3)) + for (const resolve of explainResolvers) { + resolve(EXPLANATION_REPLY) + } + + const { walkthrough } = await pending + expect(walkthrough.stops.every((stop) => stop.status === 'ready')).toBe(true) + }) + + it('marks a stop failed when its explanation fails twice', 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(EXPLANATION_REPLY) + }) + + const { walkthrough, created } = await service.generate(SESSION_ID, {}) + + expect(created).toBe(true) + const byTitle = new Map(walkthrough.stops.map((stop) => [stop.title, stop])) + expect(byTitle.get('B')?.status).toBe('failed') + expect(byTitle.get('A')?.status).toBe('ready') + expect(byTitle.get('C')?.status).toBe('ready') + expect(fake.generateCalls.filter((prompt) => prompt.includes('## Stop: B'))).toHaveLength(2) + }) + + it('keeps a single call for small diffs', async () => { + fake.setGenerateImpl(async () => + modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }]), + ) + + const { walkthrough } = await service.generate(SESSION_ID, {}) + + expect(fake.generateCalls).toHaveLength(1) + expect(walkthrough.stops).toHaveLength(1) + expect(walkthrough.stops[0]!.status).toBe('ready') + }) + + it('does not cache a diff read that an execution event invalidated', async () => { + const diffMock = vi.mocked(fake.client.api.session.diff) + let resolveDiff: (changes: FileDiffInfo[]) => void = () => {} + diffMock.mockImplementationOnce( + () => new Promise((resolve) => { + resolveDiff = resolve + }), + ) + + const pending = service.getState(SESSION_ID) + await vi.waitFor(() => expect(diffMock).toHaveBeenCalledTimes(1)) + service.handleEvent(sessionEvent('session.execution.succeeded', SESSION_ID)) + resolveDiff(threeHunks) + await pending + + await service.getState(SESSION_ID) + expect(diffMock).toHaveBeenCalledTimes(2) + }) + describe('startGeneration', () => { const coveringReply = modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }]) diff --git a/backend/test/utils/concurrency.test.ts b/backend/test/utils/concurrency.test.ts new file mode 100644 index 00000000..4ed19bb7 --- /dev/null +++ b/backend/test/utils/concurrency.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { mapWithConcurrency } from '../../src/utils/concurrency' + +describe('mapWithConcurrency', () => { + it('keeps result order', async () => { + const result = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (item) => item * 2) + expect(result).toEqual([2, 4, 6, 8, 10]) + }) + + it('runs at most limit calls at once', async () => { + let inFlight = 0 + let maxInFlight = 0 + + await mapWithConcurrency([1, 2, 3, 4, 5, 6], 2, async (item) => { + inFlight += 1 + maxInFlight = Math.max(maxInFlight, inFlight) + await new Promise((resolve) => setTimeout(resolve, 1)) + inFlight -= 1 + return item + }) + + expect(maxInFlight).toBe(2) + }) + + it('propagates a rejection', async () => { + await expect( + mapWithConcurrency([1, 2, 3], 2, async (item) => { + if (item === 2) { + throw new Error('boom') + } + return item + }), + ).rejects.toThrow('boom') + }) + + it('passes the index to the callback', async () => { + const result = await mapWithConcurrency(['a', 'b'], 2, async (item, index) => `${item}${index}`) + expect(result).toEqual(['a0', 'b1']) + }) +})