mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
@@ -35,3 +35,13 @@ export async function generateChangeWalkthrough(
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
}
|
||||
|
||||
export async function cancelChangeWalkthrough(
|
||||
sessionId: string,
|
||||
source: WalkthroughSource,
|
||||
): Promise<void> {
|
||||
await fetchWrapperVoid(walkthroughUrl(sessionId), {
|
||||
method: 'DELETE',
|
||||
params: { source: walkthroughSourceKey(source) },
|
||||
})
|
||||
}
|
||||
@@ -28,6 +28,7 @@ vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({
|
||||
ChangesWalkthroughNav: () => null,
|
||||
ChangesWalkthroughRegenerate: () => null,
|
||||
ChangesWalkthroughSourcePicker: () => null,
|
||||
ChangesWalkthroughStop: () => null,
|
||||
ChangesWalkthroughView: () => <div>walkthrough-tool</div>,
|
||||
}))
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ChangesWalkthroughProvider,
|
||||
ChangesWalkthroughRegenerate,
|
||||
ChangesWalkthroughSourcePicker,
|
||||
ChangesWalkthroughStop,
|
||||
ChangesWalkthroughView,
|
||||
type WalkthroughSourceRequest,
|
||||
} from '@/components/session/ChangesWalkthroughSheet'
|
||||
@@ -172,6 +173,7 @@ export function ToolSidePanel({
|
||||
{activeTool === 'walkthrough' ? (
|
||||
<>
|
||||
<ChangesWalkthroughSourcePicker />
|
||||
<ChangesWalkthroughStop />
|
||||
<ChangesWalkthroughRegenerate />
|
||||
<ChangesWalkthroughNav />
|
||||
</>
|
||||
|
||||
@@ -10,11 +10,13 @@ import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manage
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getChangeWalkthrough: vi.fn(),
|
||||
generateChangeWalkthrough: vi.fn(),
|
||||
cancelChangeWalkthrough: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/changeWalkthroughs', () => ({
|
||||
getChangeWalkthrough: mocks.getChangeWalkthrough,
|
||||
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
|
||||
cancelChangeWalkthrough: mocks.cancelChangeWalkthrough,
|
||||
}))
|
||||
|
||||
const walkthrough: ChangeWalkthrough = {
|
||||
@@ -265,6 +267,28 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('stops an in-flight generation from the header', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ generating: true }))
|
||||
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
|
||||
renderSheet()
|
||||
|
||||
const stop = await screen.findByRole('button', { name: 'Stop generating walkthrough' })
|
||||
await user.click(stop)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.cancelChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' })
|
||||
})
|
||||
})
|
||||
|
||||
it('does not show a stop button when idle', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
|
||||
await screen.findByText('Overview')
|
||||
expect(screen.queryByRole('button', { name: 'Stop generating walkthrough' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('switches to staged changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createContext, memo, useCallback, useContext, useEffect, useRef, useState } from 'react'
|
||||
import type { ReactNode, RefObject } from 'react'
|
||||
import { ChevronDown, ChevronLeft, ChevronRight, Loader2, RefreshCw } from 'lucide-react'
|
||||
import { ChevronDown, ChevronLeft, ChevronRight, Loader2, RefreshCw, Square } from 'lucide-react'
|
||||
import { SideDrawer, SideDrawerHeader } from '@/components/ui/side-drawer'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
@@ -16,7 +16,11 @@ import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { DiffLines } from '@/components/file-browser/DiffLines'
|
||||
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
|
||||
import { useChangeWalkthrough, useGenerateChangeWalkthrough } from '@/hooks/useChangeWalkthrough'
|
||||
import {
|
||||
useCancelChangeWalkthrough,
|
||||
useChangeWalkthrough,
|
||||
useGenerateChangeWalkthrough,
|
||||
} from '@/hooks/useChangeWalkthrough'
|
||||
import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from '@/lib/git-status-styles'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
@@ -129,6 +133,8 @@ interface ChangesWalkthroughContextValue {
|
||||
contextLimitFiles: WalkthroughOmittedFile[]
|
||||
generate: () => void
|
||||
regenerate: () => void
|
||||
stop: () => void
|
||||
stopping: boolean
|
||||
stops: WalkthroughStop[]
|
||||
stopIndex: number | null
|
||||
selectedStop: WalkthroughStop | null
|
||||
@@ -268,6 +274,8 @@ export function ChangesWalkthroughProvider({
|
||||
const sourceKey = walkthroughSourceKey(source)
|
||||
const stateQuery = useChangeWalkthrough(sessionId, active, source)
|
||||
const generate = useGenerateChangeWalkthrough(sessionId, source)
|
||||
const cancel = useCancelChangeWalkthrough(sessionId, source)
|
||||
const stop = useCallback(() => cancel.mutate(), [cancel])
|
||||
const resetGenerate = generate.reset
|
||||
const [stopIndex, setStopIndex] = useState<number | null>(null)
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
@@ -333,6 +341,8 @@ export function ChangesWalkthroughProvider({
|
||||
contextLimitFiles,
|
||||
generate: () => generate.mutate({}),
|
||||
regenerate: () => generate.mutate({ regenerate: true }),
|
||||
stop,
|
||||
stopping: cancel.isPending,
|
||||
stops,
|
||||
stopIndex: clampedIndex,
|
||||
selectedStop,
|
||||
@@ -406,6 +416,26 @@ export const ChangesWalkthroughNav = memo(function ChangesWalkthroughNav() {
|
||||
)
|
||||
})
|
||||
|
||||
export const ChangesWalkthroughStop = memo(function ChangesWalkthroughStop() {
|
||||
const { generating, stopping, stop } = useChangesWalkthrough()
|
||||
|
||||
if (!generating) return null
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Stop generating walkthrough"
|
||||
onClick={stop}
|
||||
disabled={stopping}
|
||||
className="h-7 gap-1 px-2 text-xs"
|
||||
>
|
||||
<Square className="h-3.5 w-3.5" />
|
||||
{stopping ? 'Stopping…' : 'Stop'}
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
|
||||
/** Regenerates the current walkthrough from the chrome; renders nothing until one exists. */
|
||||
export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRegenerate() {
|
||||
const { walkthrough, generating, regenerate, sourcePending } = useChangesWalkthrough()
|
||||
@@ -677,6 +707,7 @@ export function ChangesWalkthroughSheet({
|
||||
actions={
|
||||
<>
|
||||
<ChangesWalkthroughSourcePicker />
|
||||
<ChangesWalkthroughStop />
|
||||
<ChangesWalkthroughRegenerate />
|
||||
<ChangesWalkthroughNav />
|
||||
</>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { changeWalkthroughQueryKey, useChangeWalkthrough, useGenerateChangeWalkthrough } from './useChangeWalkthrough'
|
||||
import { changeWalkthroughQueryKey, useCancelChangeWalkthrough, useChangeWalkthrough, useGenerateChangeWalkthrough } from './useChangeWalkthrough'
|
||||
import { DEFAULT_WALKTHROUGH_SOURCE, walkthroughHunksIdentity } from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
ChangeWalkthrough,
|
||||
@@ -13,11 +13,13 @@ import type {
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getChangeWalkthrough: vi.fn(),
|
||||
generateChangeWalkthrough: vi.fn(),
|
||||
cancelChangeWalkthrough: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/changeWalkthroughs', () => ({
|
||||
getChangeWalkthrough: mocks.getChangeWalkthrough,
|
||||
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
|
||||
cancelChangeWalkthrough: mocks.cancelChangeWalkthrough,
|
||||
}))
|
||||
|
||||
const walkthroughForA: ChangeWalkthrough = {
|
||||
@@ -187,3 +189,30 @@ describe('useChangeWalkthrough', () => {
|
||||
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(4))
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCancelChangeWalkthrough', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('cancels the walkthrough and optimistically clears the generating state', async () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const queryKey = changeWalkthroughQueryKey('ses_A', 'session')
|
||||
queryClient.setQueryData(queryKey, state({ generating: true }))
|
||||
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ generating: false }))
|
||||
|
||||
const { result } = renderHook(() => useCancelChangeWalkthrough('ses_A', DEFAULT_WALKTHROUGH_SOURCE), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
result.current.mutate()
|
||||
})
|
||||
|
||||
expect(mocks.cancelChangeWalkthrough).toHaveBeenCalledWith('ses_A', { kind: 'session' })
|
||||
await waitFor(() => {
|
||||
expect(queryClient.getQueryData<ChangeWalkthroughState>(queryKey)?.generating).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { generateChangeWalkthrough, getChangeWalkthrough } from '@/api/changeWalkthroughs'
|
||||
import { cancelChangeWalkthrough, generateChangeWalkthrough, getChangeWalkthrough } from '@/api/changeWalkthroughs'
|
||||
import { walkthroughHunksIdentity, walkthroughSourceKey } from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
ChangeWalkthrough,
|
||||
@@ -81,3 +81,23 @@ export function useGenerateChangeWalkthrough(sessionId: string | undefined, sour
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useCancelChangeWalkthrough(sessionId: string | undefined, source: WalkthroughSource) {
|
||||
const queryClient = useQueryClient()
|
||||
const sourceKey = walkthroughSourceKey(source)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
const targetSessionId = sessionId!
|
||||
await cancelChangeWalkthrough(targetSessionId, source)
|
||||
return { sessionId: targetSessionId, sourceKey }
|
||||
},
|
||||
onSuccess: ({ sessionId: targetSessionId, sourceKey: targetSourceKey }) => {
|
||||
const queryKey = changeWalkthroughQueryKey(targetSessionId, targetSourceKey)
|
||||
queryClient.setQueryData<ChangeWalkthroughState>(queryKey, (cached) =>
|
||||
cached ? { ...cached, generating: false, error: null } : cached,
|
||||
)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user