feat(walkthrough): stop an in-flight change walkthrough generation

Add DELETE /api/change-walkthroughs/:sessionId to cancel the generation for a session and source. The service removes the in-flight entry, persists the partial walkthrough, and aborts a per-generation signal threaded through model resolution and every model call. Cancellation is not recorded as a failure and leaves the remaining stops pending. A Stop button in the walkthrough chrome calls the new endpoint.
This commit is contained in:
Chris Scott committed 2026-10-10 17:48:14 +00:00
1 parent 2d134d9de7
commit 0752ebf360
12 files changed
+334 -21

No files matched your search

+76 -14
View File
@@ -673,6 +673,7 @@ interface InFlightGeneration {
modelStarted: Promise<void>
result: Promise<{ walkthrough: ChangeWalkthrough; created: boolean }>
walkthrough: ChangeWalkthrough | null
controller: AbortController
}
class WalkthroughCallSkippedError extends Error {
@@ -682,6 +683,13 @@ class WalkthroughCallSkippedError extends Error {
}
}
export class WalkthroughCancelledError extends Error {
constructor() {
super('Walkthrough generation stopped')
this.name = 'WalkthroughCancelledError'
}
}
function toGenerationError(error: unknown): WalkthroughGenerationError {
if (error instanceof ServiceError) {
return {
@@ -816,6 +824,25 @@ export class ChangeWalkthroughService {
return this.getState(sessionId, request.source ?? DEFAULT_WALKTHROUGH_SOURCE)
}
/**
* Stops an in-flight generation for a session and source. The in-flight entry is removed
* synchronously so the next read reports `generating: false`, the partial walkthrough is
* persisted, and the abort signal stops the model calls that are still running.
*/
cancelGeneration(sessionId: string, source: WalkthroughSource = DEFAULT_WALKTHROUGH_SOURCE): boolean {
const key = entryKey(sessionId, source)
const entry = this.inFlight.get(key)
if (!entry) {
return false
}
this.inFlight.delete(key)
if (entry.walkthrough) {
this.saveIfSessionLive(entry.walkthrough)
}
entry.controller.abort()
return true
}
/** Removes the stored walkthroughs of a deleted session, including one still being generated. */
handleEvent(event: SSEEvent): void {
switch (event.type) {
@@ -910,18 +937,20 @@ export class ChangeWalkthroughService {
resolveModelStarted()
}
const entry = { modelStarted, walkthrough: null } as InFlightGeneration
const entry = { modelStarted, walkthrough: null, controller: new AbortController() } as InFlightGeneration
this.inFlight.set(key, entry)
entry.result = this.runGenerate(sessionId, source, request, markModelStarted, entry)
entry.result = this.runGenerate(sessionId, source, request, markModelStarted, entry, entry.controller.signal)
.catch((error) => {
if (modelCalled) {
if (modelCalled && !(error instanceof WalkthroughCancelledError)) {
this.failures.set(key, toGenerationError(error))
}
throw error
})
.finally(() => {
this.inFlight.delete(key)
if (this.inFlight.get(key) === entry) {
this.inFlight.delete(key)
}
this.deletedDuringGeneration.delete(key)
this.invalidateCurrentHash(key)
})
@@ -959,6 +988,7 @@ export class ChangeWalkthroughService {
request: GenerateChangeWalkthroughRequest,
onModelStart: () => void,
entry: InFlightGeneration,
signal: AbortSignal,
): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> {
const session = await this.readSession(sessionId)
const key = entryKey(sessionId, source)
@@ -1001,7 +1031,7 @@ export class ChangeWalkthroughService {
return { walkthrough: previous, created: false }
}
const model = await this.resolveWalkthroughModel(session)
const model = await this.resolveWalkthroughModel(session, signal)
const storedModel = formatOpenCodeModelRef(model)
const resumingStops = previous.stops.map((stop) =>
stop.status === 'ready' ? stop : { ...stop, status: 'pending' as const },
@@ -1021,6 +1051,7 @@ export class ChangeWalkthroughService {
resuming,
onModelStart,
entry,
signal,
)
if (this.deletedDuringGeneration.has(key)) {
throw new ChangeWalkthroughError('Session not found', 404)
@@ -1028,7 +1059,7 @@ export class ChangeWalkthroughService {
return { walkthrough: resumed, created: true }
}
const model = await this.resolveWalkthroughModel(session)
const model = await this.resolveWalkthroughModel(session, signal)
const modelKey = computeModelKey(model)
const storedModel = formatOpenCodeModelRef(model)
@@ -1110,8 +1141,11 @@ export class ChangeWalkthroughService {
const prompt = buildWalkthroughPrompt({ title, hunks })
onModelStart()
const parsed = await this.callModelParsed(prompt, model, (text) =>
parseWalkthroughResponse(text, hunks),
const parsed = await this.callModelParsed(
prompt,
model,
(text) => parseWalkthroughResponse(text, hunks),
signal,
)
const stops = parsed.stops.map((stop) => applySingleCallKeys(stop, modelKey))
@@ -1138,8 +1172,11 @@ export class ChangeWalkthroughService {
})
onModelStart()
const planned = await this.callModelParsed(planPrompt, model, (text) =>
parseWalkthroughPlan(text, outline.hunks),
const planned = await this.callModelParsed(
planPrompt,
model,
(text) => parseWalkthroughPlan(text, outline.hunks),
signal,
)
const stops = planned.stops.map((stop) => applyReuse(stop, reusable, modelKey))
@@ -1162,6 +1199,7 @@ export class ChangeWalkthroughService {
walkthrough,
onModelStart,
entry,
signal,
)
}
@@ -1181,6 +1219,7 @@ export class ChangeWalkthroughService {
walkthrough: ChangeWalkthrough,
onModelStart: () => void,
entry: InFlightGeneration,
signal: AbortSignal,
): Promise<ChangeWalkthrough> {
const modelKey = computeModelKey(model)
const key = entryKey(walkthrough.sessionId, walkthrough.source)
@@ -1189,6 +1228,9 @@ export class ChangeWalkthroughService {
let current = walkthrough
await mapWithConcurrency(stops, WALKTHROUGH_EXPLAIN_CONCURRENCY, async (stop) => {
if (signal.aborted) {
return
}
const explainPrompt = buildWalkthroughExplainPrompt({ title, summary, stop, hunks })
onModelStart()
@@ -1198,6 +1240,7 @@ export class ChangeWalkthroughService {
explainPrompt,
model,
parseWalkthroughExplanation,
signal,
() => this.deletedDuringGeneration.has(key),
)
explained = {
@@ -1207,7 +1250,7 @@ export class ChangeWalkthroughService {
explanationKey: computeExplanationKey(modelKey, stop.hunkIds),
}
} catch (error) {
if (error instanceof WalkthroughCallSkippedError) {
if (error instanceof WalkthroughCallSkippedError || error instanceof WalkthroughCancelledError) {
return
}
logger.warn('Failed to explain a change walkthrough stop', getErrorMessage(error))
@@ -1222,6 +1265,10 @@ export class ChangeWalkthroughService {
}
})
if (signal.aborted) {
this.saveIfSessionLive(current)
}
return current
}
@@ -1229,23 +1276,33 @@ export class ChangeWalkthroughService {
prompt: string,
model: ModelRef,
parse: (text: string) => T | null,
signal: AbortSignal,
shouldSkip?: () => boolean,
): Promise<T> {
let lastError = new ChangeWalkthroughError('Failed to generate the change walkthrough', 502)
for (let attempt = 0; attempt < WALKTHROUGH_CALL_ATTEMPTS; attempt += 1) {
if (signal.aborted) {
throw new WalkthroughCancelledError()
}
let text: string
try {
text = await WALKTHROUGH_MODEL_LIMITER.run(() => {
if (shouldSkip?.()) {
throw new WalkthroughCallSkippedError()
}
return generateTextWithTimeout(this.openCodeClient, { prompt, model }, this.timeoutMs)
if (signal.aborted) {
throw new WalkthroughCancelledError()
}
return generateTextWithTimeout(this.openCodeClient, { prompt, model }, this.timeoutMs, signal)
})
} catch (error) {
if (error instanceof WalkthroughCallSkippedError) {
throw error
}
if (error instanceof WalkthroughCancelledError || signal.aborted) {
throw new WalkthroughCancelledError()
}
lastError =
error instanceof GenerateTextTimeoutError
? new ChangeWalkthroughError('Generating the change walkthrough timed out', 504, {
@@ -1302,7 +1359,7 @@ export class ChangeWalkthroughService {
* walkthrough model is registered before the first call. A failed wait is swallowed because generation proceeds and
* lets OpenCode surface its own error; the wait is per generation, never per stop.
*/
private async resolveWalkthroughModel(session: SessionInfo): Promise<ModelRef> {
private async resolveWalkthroughModel(session: SessionInfo, signal?: AbortSignal): Promise<ModelRef> {
const configured = this.settingsService.getSettings().preferences.walkthroughModel?.trim()
const parsed = configured ? parseOpenCodeModelRef(configured) : undefined
const preferred = parsed ?? session.model
@@ -1310,6 +1367,7 @@ export class ChangeWalkthroughService {
try {
await resolveOpenCodeModel(this.openCodeClient, getOpenCodeGlobalConfigPath(), {
preferredModel: formatOpenCodeModelRef(preferred),
...(signal ? { signal } : {}),
})
} catch {
return preferred
@@ -1318,7 +1376,11 @@ export class ChangeWalkthroughService {
}
let resolved
try {
resolved = await resolveOpenCodeModel(this.openCodeClient, getOpenCodeGlobalConfigPath())
resolved = await resolveOpenCodeModel(
this.openCodeClient,
getOpenCodeGlobalConfigPath(),
signal ? { signal } : undefined,
)
} catch (error) {
throw new ChangeWalkthroughError(
getErrorMessage(error) || 'Failed to resolve the walkthrough model',
@@ -14,9 +14,18 @@ export async function generateTextWithTimeout(
client: OpenCodeClient,
input: { prompt: string; model?: ModelRef },
timeoutMs: number,
signal?: AbortSignal,
): Promise<string> {
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
const abortFromSignal = () => controller.abort(signal?.reason)
if (signal) {
if (signal.aborted) {
controller.abort(signal.reason)
} else {
signal.addEventListener('abort', abortFromSignal, { once: true })
}
}
const timeout = new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => {
controller.abort()
@@ -29,6 +38,7 @@ export async function generateTextWithTimeout(
return text
} finally {
if (timer) clearTimeout(timer)
signal?.removeEventListener('abort', abortFromSignal)
}
}