From d4a5f46ac6b202eb659b843c1f3631e781adc11c Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:29:20 -0400 Subject: [PATCH] fix(walkthrough): cancel generation cleanly before the first model call Guard every newly generated persistence point and each await before it so a cancelled generation cannot write a walkthrough after DELETE is accepted, including the mechanical-only path. Treat an aborted model-catalog resolution as cancellation rather than a model-resolution failure, and let startGeneration return the stopped state for cancellation while preserving genuine errors. --- backend/src/services/change-walkthroughs.ts | 30 +++++++- .../test/routes/change-walkthroughs.test.ts | 34 ++++++++ .../test/services/change-walkthroughs.test.ts | 77 +++++++++++++++++++ 3 files changed, 140 insertions(+), 1 deletion(-) diff --git a/backend/src/services/change-walkthroughs.ts b/backend/src/services/change-walkthroughs.ts index 021cbc88..06618a50 100644 --- a/backend/src/services/change-walkthroughs.ts +++ b/backend/src/services/change-walkthroughs.ts @@ -820,7 +820,13 @@ export class ChangeWalkthroughService { async startGeneration(sessionId: string, request: GenerateChangeWalkthroughRequest): Promise { const entry = this.begin(sessionId, request) - await Promise.race([entry.modelStarted, entry.result]) + try { + await Promise.race([entry.modelStarted, entry.result]) + } catch (error) { + if (!(error instanceof WalkthroughCancelledError)) { + throw error + } + } return this.getState(sessionId, request.source ?? DEFAULT_WALKTHROUGH_SOURCE) } @@ -982,6 +988,12 @@ export class ChangeWalkthroughService { } } + private throwIfCancelled(signal: AbortSignal): void { + if (signal.aborted) { + throw new WalkthroughCancelledError() + } + } + private async runGenerate( sessionId: string, source: WalkthroughSource, @@ -991,10 +1003,12 @@ export class ChangeWalkthroughService { signal: AbortSignal, ): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> { const session = await this.readSession(sessionId) + this.throwIfCancelled(signal) const key = entryKey(sessionId, source) if (source.kind === 'pullRequest') { await this.fetchPullRequestChanges(session, source) + this.throwIfCancelled(signal) } let changes: FileDiffInfo[] @@ -1013,6 +1027,7 @@ export class ChangeWalkthroughService { code: 'WALKTHROUGH_CHANGES_UNAVAILABLE', }) } + this.throwIfCancelled(signal) if (changes.length === 0) { throw new ChangeWalkthroughError(noChangesMessage(source), 409, { @@ -1079,6 +1094,7 @@ export class ChangeWalkthroughService { hunks: WalkthroughHunk[] omittedFiles: WalkthroughOmittedFile[] }): ChangeWalkthrough => { + this.throwIfCancelled(signal) const walkthrough: ChangeWalkthrough = { sessionId, source, @@ -1370,8 +1386,14 @@ export class ChangeWalkthroughService { ...(signal ? { signal } : {}), }) } catch { + if (signal?.aborted) { + throw new WalkthroughCancelledError() + } return preferred } + if (signal?.aborted) { + throw new WalkthroughCancelledError() + } return preferred } let resolved @@ -1382,12 +1404,18 @@ export class ChangeWalkthroughService { signal ? { signal } : undefined, ) } catch (error) { + if (signal?.aborted) { + throw new WalkthroughCancelledError() + } throw new ChangeWalkthroughError( getErrorMessage(error) || 'Failed to resolve the walkthrough model', 502, { code: 'WALKTHROUGH_MODEL_UNAVAILABLE' }, ) } + if (signal?.aborted) { + throw new WalkthroughCancelledError() + } return resolved.variant ? { providerID: resolved.providerID, id: resolved.id, variant: resolved.variant } diff --git a/backend/test/routes/change-walkthroughs.test.ts b/backend/test/routes/change-walkthroughs.test.ts index 5ff68d22..d1c427d5 100644 --- a/backend/test/routes/change-walkthroughs.test.ts +++ b/backend/test/routes/change-walkthroughs.test.ts @@ -113,6 +113,14 @@ function replyForPrompt(prompt: string, summary = 'A summary'): string { return JSON.stringify({ summary, stops: [{ title: 'A', explanation: 'Why', hunkIds: ids }] }) } +function createDeferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + describe('change walkthrough routes', () => { let db: Database let sessions: Record @@ -403,6 +411,32 @@ describe('change walkthrough routes', () => { expect(state.error).toBeNull() }) + it('resolves a pending POST with the stopped state after DELETE cancels it', async () => { + const diff = createDeferred() + const diffMock = vi.mocked(fake.client.api.session.diff) + diffMock.mockImplementationOnce(() => diff.promise) + + const postPromise = app.request(`/change-walkthroughs/${SESSION_ID}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }) + + await vi.waitFor(() => expect(diffMock).toHaveBeenCalledTimes(1)) + + const deleteRes = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' }) + expect(deleteRes.status).toBe(204) + + diff.resolve(CHANGES) + + const postRes = await postPromise + expect(postRes.status).toBe(200) + const body = (await postRes.json()) as { generating: boolean; walkthrough: unknown; error: unknown } + expect(body.generating).toBe(false) + expect(body.walkthrough).toBeNull() + expect(body.error).toBeNull() + }) + it('DELETE is a no-op when nothing is generating', async () => { const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' }) diff --git a/backend/test/services/change-walkthroughs.test.ts b/backend/test/services/change-walkthroughs.test.ts index 3bfc0474..56c4f66c 100644 --- a/backend/test/services/change-walkthroughs.test.ts +++ b/backend/test/services/change-walkthroughs.test.ts @@ -62,6 +62,14 @@ function abortable(promise: Promise, signal?: AbortSignal): Promise { }) } +function createDeferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + function userMessage(id: string): SessionMessageInfo { return { id, type: 'user', time: { created: 0 }, text: id } as SessionMessageInfo } @@ -2366,4 +2374,73 @@ describe('ChangeWalkthroughService', () => { await expect(pending).rejects.toBeInstanceOf(WalkthroughCancelledError) }) }) + + describe('cancellation before the model call', () => { + it('does not persist a mechanical-only walkthrough cancelled during the changes read', async () => { + sessions[SESSION_ID]!.info = { + id: SESSION_ID, + title: 'Title', + model: { providerID: 'anthropic', id: 'claude-sonnet-4' }, + } as SessionInfo + fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }])) + const previous = await service.generate(SESSION_ID, {}) + expect(previous.created).toBe(true) + + const mechanical = [change('pnpm-lock.yaml', hunkPatch(1))] + sessions[SESSION_ID]!.changes = mechanical + const diff = createDeferred() + const diffMock = vi.mocked(fake.client.api.session.diff) + diffMock.mockImplementationOnce(() => diff.promise) + + const pending = service.generate(SESSION_ID, {}) + await vi.waitFor(() => expect(diffMock).toHaveBeenCalledTimes(2)) + + expect(service.cancelGeneration(SESSION_ID)).toBe(true) + diff.resolve(mechanical) + + await expect(pending).rejects.toBeInstanceOf(WalkthroughCancelledError) + expect(fake.generateCalls).toHaveLength(1) + expect(getChangeWalkthrough(db, SESSION_ID, 'session')).toEqual(previous.walkthrough) + }) + + it('cancels while resolving the preferred model without persisting the mechanical-only changes', async () => { + sessions[SESSION_ID]!.info = { + id: SESSION_ID, + title: 'Title', + model: { providerID: 'anthropic', id: 'claude-sonnet-4' }, + } as SessionInfo + sessions[SESSION_ID]!.changes = [change('pnpm-lock.yaml', hunkPatch(1))] + + const config = createDeferred>>() + const configMock = vi.mocked(fake.client.api.config.get) + configMock.mockImplementationOnce(() => config.promise) + + const pending = service.generate(SESSION_ID, {}) + await vi.waitFor(() => expect(configMock).toHaveBeenCalledTimes(1)) + + expect(service.cancelGeneration(SESSION_ID)).toBe(true) + config.resolve([]) + + await expect(pending).rejects.toBeInstanceOf(WalkthroughCancelledError) + expect(fake.generateCalls).toHaveLength(0) + expect(getChangeWalkthrough(db, SESSION_ID, 'session')).toBeNull() + expect((await service.getState(SESSION_ID)).error).toBeNull() + }) + + it('cancels while resolving the default model without a 502 failure', async () => { + const config = createDeferred>>() + const configMock = vi.mocked(fake.client.api.config.get) + configMock.mockImplementationOnce(() => config.promise) + + const pending = service.generate(SESSION_ID, {}) + await vi.waitFor(() => expect(configMock).toHaveBeenCalledTimes(1)) + + expect(service.cancelGeneration(SESSION_ID)).toBe(true) + config.resolve([]) + + await expect(pending).rejects.toBeInstanceOf(WalkthroughCancelledError) + expect(fake.generateCalls).toHaveLength(0) + expect((await service.getState(SESSION_ID)).error).toBeNull() + }) + }) })