mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
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:
1 parent
2d134d9de7
commit
0752ebf360
12 files changed
+334
-21
No files matched your search
@@ -41,5 +41,16 @@ export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:sessionId', (c) => {
|
||||
const sourceParam = c.req.query('source')
|
||||
const source = sourceParam === undefined ? DEFAULT_WALKTHROUGH_SOURCE : parseWalkthroughSourceKey(sourceParam)
|
||||
if (!source) {
|
||||
return c.json({ error: 'Invalid walkthrough source' }, 400)
|
||||
}
|
||||
|
||||
service.cancelGeneration(c.req.param('sessionId'), source)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -387,4 +387,31 @@ describe('change walkthrough routes', () => {
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('DELETE stops an in-flight generation', async () => {
|
||||
fake.setGenerateImpl(() => new Promise<string>(() => {}))
|
||||
|
||||
const postRes = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
|
||||
expect(postRes.status).toBe(202)
|
||||
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' })
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
|
||||
const state = (await getRes.json()) as { generating: boolean; error: unknown }
|
||||
expect(state.generating).toBe(false)
|
||||
expect(state.error).toBeNull()
|
||||
})
|
||||
|
||||
it('DELETE is a no-op when nothing is generating', async () => {
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
})
|
||||
|
||||
it('DELETE rejects an invalid source with 400', async () => {
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}?source=branch:-x`, { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -25,6 +25,7 @@ import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
|
||||
import { createCommittedRepo, createGitAuthService, createOrigin, cloneOrigin, git, uniqueName } from '../helpers/git-fixtures'
|
||||
import {
|
||||
ChangeWalkthroughService,
|
||||
WalkthroughCancelledError,
|
||||
buildWalkthroughInput,
|
||||
buildWalkthroughOutline,
|
||||
buildWalkthroughPlanPrompt,
|
||||
@@ -42,6 +43,25 @@ import { ChangeWalkthroughError } from '../../src/services/change-walkthrough-er
|
||||
|
||||
const SESSION_ID = 'ses_walkthrough'
|
||||
|
||||
function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||
if (!signal) return promise
|
||||
if (signal.aborted) return Promise.reject(new DOMException('Aborted', 'AbortError'))
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const onAbort = () => reject(new DOMException('Aborted', 'AbortError'))
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
promise.then(
|
||||
(value) => {
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
resolve(value)
|
||||
},
|
||||
(error) => {
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
reject(error)
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function userMessage(id: string): SessionMessageInfo {
|
||||
return { id, type: 'user', time: { created: 0 }, text: id } as SessionMessageInfo
|
||||
}
|
||||
@@ -185,10 +205,10 @@ function createFakeClient(sessions: Record<string, FakeSession>) {
|
||||
}),
|
||||
},
|
||||
generate: {
|
||||
text: vi.fn(async (input: { prompt: string; model?: ModelRef }) => {
|
||||
text: vi.fn(async (input: { prompt: string; model?: ModelRef }, options?: { signal?: AbortSignal }) => {
|
||||
generateCalls.push(input.prompt)
|
||||
generateModels.push(input.model)
|
||||
return { text: await generateImpl(input.prompt) }
|
||||
return { text: await abortable(generateImpl(input.prompt), options?.signal) }
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -2280,4 +2300,70 @@ describe('ChangeWalkthroughService', () => {
|
||||
expect(victimExplainStarted).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cancelGeneration', () => {
|
||||
it('stops a pending generation without recording an error', async () => {
|
||||
fake.setGenerateImpl(() => new Promise<string>(() => {}))
|
||||
|
||||
const pending = service.generate(SESSION_ID, {})
|
||||
await vi.waitFor(() => expect(fake.generateCalls).toHaveLength(1))
|
||||
|
||||
expect(service.cancelGeneration(SESSION_ID)).toBe(true)
|
||||
await expect(pending).rejects.toBeInstanceOf(WalkthroughCancelledError)
|
||||
|
||||
const state = await service.getState(SESSION_ID)
|
||||
expect(state.generating).toBe(false)
|
||||
expect(state.error).toBeNull()
|
||||
})
|
||||
|
||||
it('returns false when nothing is generating', () => {
|
||||
expect(service.cancelGeneration(SESSION_ID)).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps explained stops and persists the partial walkthrough', async () => {
|
||||
sessions[SESSION_ID]!.changes = LARGE_CHANGES
|
||||
fake.setGenerateImpl((prompt) => {
|
||||
if (prompt.includes(PLAN_MARKER)) {
|
||||
return Promise.resolve(LARGE_PLAN_REPLY)
|
||||
}
|
||||
return new Promise<string>(() => {})
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
expect(service.cancelGeneration(SESSION_ID)).toBe(true)
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
expect((await service.getState(SESSION_ID)).generating).toBe(false)
|
||||
})
|
||||
|
||||
const state = await service.getState(SESSION_ID)
|
||||
expect(state.error).toBeNull()
|
||||
const stored = getChangeWalkthrough(db, SESSION_ID, 'session')
|
||||
expect(stored).not.toBeNull()
|
||||
expect(stored!.stops.every((stop) => stop.status === 'pending')).toBe(true)
|
||||
|
||||
await pending
|
||||
})
|
||||
|
||||
it('aborts only the requested source', async () => {
|
||||
fake.setGenerateImpl(() => new Promise<string>(() => {}))
|
||||
|
||||
const pending = service.generate(SESSION_ID, {})
|
||||
await vi.waitFor(() => expect(fake.generateCalls).toHaveLength(1))
|
||||
|
||||
expect(service.cancelGeneration(SESSION_ID, { kind: 'staged' })).toBe(false)
|
||||
expect((await service.getState(SESSION_ID)).generating).toBe(true)
|
||||
|
||||
expect(service.cancelGeneration(SESSION_ID)).toBe(true)
|
||||
await expect(pending).rejects.toBeInstanceOf(WalkthroughCancelledError)
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user