Skip to content

Commit fa54f67

Browse files
byapparovclaude
andcommitted
fix(run): flush a pending user_message when the event loop throws (#224 review)
- Move users.flush() into a finally around the event loop, so a handler that throws still emits the pending user_message before session_error. Regression test fakes a child permission request whose reply throws. - Type the collector's payload access through MessageV2.Info / Part accessors instead of reading `any` properties inline. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015nwvfUHdM3bgMgD9Zpz7Mj
1 parent 5bc92fd commit fa54f67

3 files changed

Lines changed: 89 additions & 18 deletions

File tree

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,16 @@ export const RunCommand = cmd({
642642
output.error({ reason, code, message, resetAt })
643643
}
644644

645+
// Emit a user message still pending when the stream ends, even if a handler throws.
645646
async function loop() {
647+
try {
648+
await consumeEvents()
649+
} finally {
650+
users.flush()
651+
}
652+
}
653+
654+
async function consumeEvents() {
646655
const toggles = new Map<string, boolean>()
647656

648657
eventsLoop: for await (const event of events.stream) {
@@ -930,7 +939,6 @@ export const RunCommand = cmd({
930939
})
931940
}
932941
}
933-
users.flush()
934942
}
935943

936944
// Validate agent if specified

‎packages/cli/src/cli/cmd/run.user-message.ts‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,27 @@ import type { MessageV2 } from "../../session/message-v2"
22

33
type Emit = (type: string, data: Record<string, unknown>) => unknown
44

5-
type BusEvent = { type: string; properties?: any }
5+
/** A bus event as `run` receives it: from the local GlobalBus or an attached server's SSE stream, unvalidated. */
6+
type StreamEvent = { type: string; properties?: Record<string, any> }
67

78
type UserMessage = { info: MessageV2.User; parts: MessageV2.Part[] }
89

910
/** The session a bus event is about, or undefined for events that name no session. */
10-
function eventSessionID(event: BusEvent) {
11+
function eventSessionID(event: StreamEvent): string | undefined {
1112
const properties = event.properties ?? {}
1213
return properties.sessionID ?? properties.info?.sessionID ?? properties.part?.sessionID
1314
}
1415

15-
function eventMessageID(event: BusEvent) {
16-
if (event.type === "message.updated") return event.properties.info.id
17-
if (event.type === "message.part.updated") return event.properties.part.messageID
16+
/** The payload of a `message.updated` event (`MessageV2.Event.Updated`). */
17+
function updatedMessage(event: StreamEvent): MessageV2.Info | undefined {
18+
if (event.type !== "message.updated") return
19+
return event.properties?.info
20+
}
21+
22+
/** The payload of a `message.part.updated` event (`MessageV2.Event.PartUpdated`). */
23+
function updatedPart(event: StreamEvent): MessageV2.Part | undefined {
24+
if (event.type !== "message.part.updated") return
25+
return event.properties?.part
1826
}
1927

2028
function upsertPart(parts: MessageV2.Part[], part: MessageV2.Part) {
@@ -51,23 +59,34 @@ export function userMessages(input: { sessionID: string; emit: Emit; nextSeq: ()
5159
})
5260
}
5361

54-
function isNewUserMessage(event: BusEvent) {
55-
if (event.type !== "message.updated") return false
56-
const info = event.properties.info
57-
return info.role === "user" && info.sessionID === input.sessionID && !emitted.has(info.id)
62+
function newUserMessage(event: StreamEvent): MessageV2.User | undefined {
63+
const info = updatedMessage(event)
64+
if (info?.role !== "user" || info.sessionID !== input.sessionID || emitted.has(info.id)) return
65+
return info
5866
}
5967

60-
function collect(event: BusEvent) {
61-
if (!pending) return
62-
if (event.type === "message.updated") pending.info = event.properties.info
63-
if (event.type === "message.part.updated") pending.parts = upsertPart(pending.parts, event.properties.part)
68+
/** Folds an update of the pending message into it; false when the event is about something else. */
69+
function collect(event: StreamEvent) {
70+
if (!pending) return false
71+
const info = updatedMessage(event)
72+
if (info?.role === "user" && info.id === pending.info.id) {
73+
pending.info = info
74+
return true
75+
}
76+
const part = updatedPart(event)
77+
if (part?.messageID === pending.info.id) {
78+
pending.parts = upsertPart(pending.parts, part)
79+
return true
80+
}
81+
return false
6482
}
6583

6684
return {
67-
observe(event: BusEvent) {
68-
if (pending && eventMessageID(event) === pending.info.id) return collect(event)
85+
observe(event: StreamEvent) {
86+
if (collect(event)) return
6987
if (eventSessionID(event) === input.sessionID) flush()
70-
if (isNewUserMessage(event)) pending = { info: event.properties.info, parts: [] }
88+
const info = newUserMessage(event)
89+
if (info) pending = { info, parts: [] }
7190
},
7291
/** Emits a message still pending when the event stream ends. */
7392
flush,

‎packages/cli/test/cli/run-user-message.test.ts‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,14 @@ function chunks(turn: Turn, call: string, directory: string) {
3737
]
3838
}
3939

40-
async function run(input: { args: string[]; turns?: Turn[]; files?: Record<string, string>; compaction?: boolean }) {
40+
async function run(input: {
41+
args: string[]
42+
turns?: Turn[]
43+
files?: Record<string, string>
44+
compaction?: boolean
45+
/** Source of a module preloaded into the CLI process, to fake bus traffic. */
46+
preload?: string
47+
}) {
4148
await using tmp = await tmpdir()
4249
const turns = input.turns ?? [{ text: "Plain response" }]
4350
let requests = 0
@@ -77,11 +84,13 @@ async function run(input: { args: string[]; turns?: Turn[]; files?: Record<strin
7784
for (const [name, content] of Object.entries(input.files ?? {})) await Bun.write(path.join(tmp.path, name), content)
7885
const home = path.join(tmp.path, "home")
7986
await fs.mkdir(home)
87+
if (input.preload) await Bun.write(path.join(tmp.path, "preload.ts"), input.preload)
8088
const proc = Bun.spawn(
8189
[
8290
"bun",
8391
"run",
8492
"--conditions=browser",
93+
...(input.preload ? ["--preload", path.join(tmp.path, "preload.ts")] : []),
8594
entry,
8695
"run",
8796
"--format",
@@ -225,6 +234,41 @@ describe("run --format json user_message (#223)", () => {
225234
}, 25_000)
226235
})
227236

237+
const source = (file: string) => JSON.stringify(path.resolve(import.meta.dir, "../../src", file))
238+
239+
// The prompt stores a user message, then a child-session permission request makes the
240+
// event handler throw before any later primary-session event could complete the message.
241+
const throwingHandler = `import { SessionPrompt } from ${source("session/prompt.ts")}
242+
import { PermissionNext } from ${source("permission/next.ts")}
243+
import { GlobalBus } from ${source("bus/global.ts")}
244+
const publish = (type, properties) => GlobalBus.emit("event", { payload: { type, properties } })
245+
PermissionNext.reply = async () => {
246+
throw new Error("Fixture handler failure")
247+
}
248+
SessionPrompt.prompt = async ({ sessionID }) => {
249+
publish("session.created", { info: { id: "ses_child", parentID: sessionID, title: "child" } })
250+
publish("message.updated", {
251+
info: { id: "msg_user", sessionID, role: "user", time: { created: 1 }, agent: "build",
252+
model: { providerID: "alibaba", modelID: "qwen-plus" } },
253+
})
254+
publish("message.part.updated", {
255+
part: { id: "prt_user", messageID: "msg_user", sessionID, type: "text", text: "Hello" },
256+
})
257+
publish("permission.asked", { id: "per_child", sessionID: "ses_child", permission: "bash", patterns: ["ls"], metadata: {} })
258+
}
259+
`
260+
261+
test("a pending user message is emitted when an event handler throws", async () => {
262+
const result = await run({ args: ["Hello"], preload: throwingHandler })
263+
expect(result.exit).toBe(1)
264+
expect(result.stderr).toContain("Fixture handler failure")
265+
expect(userMessageEvents(result.events)).toMatchObject([
266+
{ messageID: "msg_user", parts: [{ id: "prt_user", text: "Hello" }], sequenceNum: 1 },
267+
])
268+
const types = result.events.map((event) => event.type)
269+
expect(types.indexOf("user_message")).toBeLessThan(types.indexOf("session_error"))
270+
}, 25_000)
271+
228272
describe("userMessages", () => {
229273
const sessionID = "ses_primary"
230274
const info = (id: string, session = sessionID) => ({

0 commit comments

Comments
 (0)