Skip to content

Commit 2164022

Browse files
byapparovclaude
andcommitted
fix(session): only the prompt that claims a session frees it (#225 review 2)
`cancel()` deleted the claim of a prompt that was still writing its user message. A newer prompt could then claim the session, and the cancelled prompt's loop cleanup would abort and free that newer claim. A cancelled `noReply` prompt never published idle. `cancel()` now only aborts. The prompt that owns the claim frees it on exit and publishes idle: always after its loop, and before the loop only when it was cancelled. So the session stays busy until the cancelled prompt unwinds. Also reword the run.ts race-guard comment, which still referred to the removed internal `loop()` call. Part of #223 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015nwvfUHdM3bgMgD9Zpz7Mj
1 parent 8a07575 commit 2164022

3 files changed

Lines changed: 142 additions & 12 deletions

File tree

‎packages/cli/src/cli/cmd/run.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,10 +1092,10 @@ export const RunCommand = cmd({
10921092
}
10931093

10941094
// Race loopDone against promptResult to handle early prompt failures.
1095-
// If SessionPrompt.prompt() rejects BEFORE it enters its internal loop()
1096-
// (e.g., Session.get() fails, model not found), no session.status idle event
1097-
// is emitted, so loopDone would hang forever. Racing ensures we surface
1098-
// the error and exit.
1095+
// If SessionPrompt.prompt() rejects before it starts its model loop
1096+
// (e.g., Session.get() fails, model not found, Session.BusyError), no
1097+
// session.status idle event is emitted, so loopDone would hang forever.
1098+
// Racing ensures we surface the error and exit.
10991099
const result = await Promise.race([
11001100
loopDone,
11011101
promptResult.then(

‎packages/cli/src/session/prompt.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -181,12 +181,12 @@ export namespace SessionPrompt {
181181
// fails before it leaves a message for the running loop to pick up.
182182
const abort = start(input.sessionID)
183183
const message = await recordPrompt(input).catch((error) => {
184-
release(input.sessionID, abort)
184+
endBeforeLoop(input.sessionID, abort)
185185
throw error
186186
})
187187

188188
if (input.noReply === true) {
189-
release(input.sessionID, abort)
189+
endBeforeLoop(input.sessionID, abort)
190190
return message
191191
}
192192

@@ -279,23 +279,31 @@ export namespace SessionPrompt {
279279
return controller.signal
280280
}
281281

282-
// Frees a claim that never reached the loop, without publishing idle.
282+
// Only the prompt that claimed a session frees it, so a cancelled prompt that
283+
// is still unwinding can never free a newer prompt's claim.
283284
function release(sessionID: string, abort: AbortSignal) {
284285
const s = state()
285286
if (s[sessionID]?.signal === abort) delete s[sessionID]
286287
}
287288

288-
// Returns false when a prompt was running: its loop publishes idle on exit.
289+
// Ends a prompt that stops before its loop: a failed message write, or noReply.
290+
// A cancelled prompt publishes idle, because cancel() leaves that to the owner.
291+
// Otherwise no idle is published: run.ts sees the rejection instead.
292+
function endBeforeLoop(sessionID: string, abort: AbortSignal) {
293+
release(sessionID, abort)
294+
if (abort.aborted) SessionStatus.set(sessionID, { type: "idle" })
295+
}
296+
297+
// Asks the running prompt to stop and returns false: the prompt that owns the
298+
// claim frees it and publishes idle. With no prompt running, publishes idle.
289299
export function cancel(sessionID: string) {
290300
log.info("cancel", { sessionID })
291-
const s = state()
292-
const match = s[sessionID]
301+
const match = state()[sessionID]
293302
if (!match) {
294303
SessionStatus.set(sessionID, { type: "idle" })
295304
return true
296305
}
297306
match.abort()
298-
delete s[sessionID]
299307
return false
300308
}
301309

@@ -306,7 +314,7 @@ export namespace SessionPrompt {
306314

307315
async function run(sessionID: string, abort: AbortSignal) {
308316
using _ = defer(() => {
309-
if (cancel(sessionID)) return
317+
release(sessionID, abort)
310318
// Keep idle after processor persistence. Headless consumers use this as
311319
// the boundary after which all terminal message events have been queued.
312320
SessionStatus.set(sessionID, { type: "idle" })

‎packages/cli/test/session/prompt-reliability.test.ts‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { describe, expect, spyOn, test } from "bun:test"
33
import { Log } from "../../src/util/log"
44
import { SessionRetry } from "../../src/session/retry"
55
import { Instance } from "../../src/project/instance"
6+
import { Bus } from "../../src/bus"
7+
import { SessionStatus } from "../../src/session/status"
68
import { SessionPrompt } from "../../src/session/prompt"
79
import { Session } from "../../src/session"
810
import { LLM } from "../../src/session/llm"
@@ -106,6 +108,126 @@ describe("prompt.ts reliability guards", () => {
106108
})
107109
})
108110

111+
// Holds the user-message write of the next prompt open until `resume` is called.
112+
function holdMessageWrite() {
113+
const original = Session.touch
114+
let reached!: () => void
115+
const writing = new Promise<void>((resolve) => (reached = resolve))
116+
let resume!: () => void
117+
const resumed = new Promise<void>((resolve) => (resume = resolve))
118+
const held = async (sessionID: string) => {
119+
touch.mockRestore()
120+
reached()
121+
await resumed
122+
return original(sessionID)
123+
}
124+
const touch = spyOn(Session, "touch").mockImplementation(Object.assign(held, original))
125+
return { writing, resume, restore: () => touch.mockRestore() }
126+
}
127+
128+
function idleEvents(sessionID: string) {
129+
const events: string[] = []
130+
const unsubscribe = Bus.subscribe(SessionStatus.Event.Status, (event) => {
131+
if (event.properties.sessionID === sessionID) events.push(event.properties.status.type)
132+
})
133+
return { count: () => events.filter((type) => type === "idle").length, unsubscribe }
134+
}
135+
136+
test("a prompt cancelled during its message write keeps the session until it unwinds", async () => {
137+
await using tmp = await tmpdir({ git: true, config: { provider } })
138+
await Instance.provide({
139+
directory: tmp.path,
140+
fn: async () => {
141+
const session = await Session.create({ title: "Cancel during write" })
142+
const stream = spyOn(LLM, "stream").mockImplementation(
143+
async () =>
144+
({
145+
fullStream: (async function* () {
146+
yield { type: "start-step" }
147+
yield { type: "text-start" }
148+
yield { type: "text-delta", text: "Done" }
149+
yield { type: "text-end" }
150+
yield { type: "finish-step", finishReason: "stop", usage: { inputTokens: 1, outputTokens: 1 } }
151+
})(),
152+
}) as unknown as Awaited<ReturnType<typeof LLM.stream>>,
153+
)
154+
const write = holdMessageWrite()
155+
const idle = idleEvents(session.id)
156+
const input = {
157+
sessionID: session.id,
158+
agent: "build",
159+
model: { providerID: "fixture", modelID: "gemini-fixture" },
160+
}
161+
try {
162+
const cancelled = SessionPrompt.prompt({ ...input, parts: [{ type: "text", text: "Cancelled" }] })
163+
const settled = cancelled.then(
164+
() => undefined,
165+
() => undefined,
166+
)
167+
await write.writing
168+
expect(SessionPrompt.cancel(session.id)).toBe(false)
169+
170+
// The cancelled prompt still owns the session until it unwinds.
171+
const early = SessionPrompt.prompt({ ...input, parts: [{ type: "text", text: "Too early" }] })
172+
await expect(early).rejects.toBeInstanceOf(Session.BusyError)
173+
174+
write.resume()
175+
await settled
176+
expect(idle.count()).toBe(1)
177+
expect(stream).not.toHaveBeenCalled()
178+
179+
const answer = await SessionPrompt.prompt({ ...input, parts: [{ type: "text", text: "Newer" }] })
180+
expect(answer.info.role).toBe("assistant")
181+
if (answer.info.role !== "assistant") throw new Error("expected assistant")
182+
expect(answer.info.error).toBeUndefined()
183+
expect(answer.info.finish).toBe("stop")
184+
expect(stream).toHaveBeenCalledTimes(1)
185+
} finally {
186+
write.resume()
187+
write.restore()
188+
idle.unsubscribe()
189+
stream.mockRestore()
190+
await Session.remove(session.id)
191+
}
192+
},
193+
})
194+
})
195+
196+
test("a noReply prompt cancelled during its message write publishes idle", async () => {
197+
await using tmp = await tmpdir({ git: true, config: { provider } })
198+
await Instance.provide({
199+
directory: tmp.path,
200+
fn: async () => {
201+
const session = await Session.create({ title: "Cancel noReply" })
202+
const write = holdMessageWrite()
203+
const idle = idleEvents(session.id)
204+
const input = {
205+
sessionID: session.id,
206+
agent: "build",
207+
model: { providerID: "fixture", modelID: "gemini-fixture" },
208+
noReply: true,
209+
parts: [{ type: "text" as const, text: "Hello" }],
210+
}
211+
try {
212+
const cancelled = SessionPrompt.prompt(input)
213+
await write.writing
214+
expect(SessionPrompt.cancel(session.id)).toBe(false)
215+
expect(idle.count()).toBe(0)
216+
217+
write.resume()
218+
expect((await cancelled).info.role).toBe("user")
219+
expect(idle.count()).toBe(1)
220+
expect((await SessionPrompt.prompt(input)).info.role).toBe("user")
221+
} finally {
222+
write.resume()
223+
write.restore()
224+
idle.unsubscribe()
225+
await Session.remove(session.id)
226+
}
227+
},
228+
})
229+
})
230+
109231
test("ensureTitle has catch handler", async () => {
110232
const source = await Bun.file(PROMPT_SRC).text()
111233
// Find the ensureTitle call site (not the function definition)

0 commit comments

Comments
 (0)