Skip to content

Commit 6bcf01f

Browse files
committed
Chat: stream reasoning and split tool rendering
1 parent 7dffd81 commit 6bcf01f

28 files changed

Lines changed: 847 additions & 139 deletions

‎src/agents/pi-embedded-subscribe.handlers.compaction.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ export function handleAutoCompactionStart(ctx: EmbeddedPiSubscribeContext) {
99
ctx.state.compactionInFlight = true;
1010
ctx.ensureCompactionPromise();
1111
ctx.log.debug(`embedded run compaction start: runId=${ctx.params.runId}`);
12-
emitAgentEvent({
13-
runId: ctx.params.runId,
12+
void ctx.params.onAgentEvent?.({
1413
stream: "compaction",
1514
data: { phase: "start" },
1615
});
17-
void ctx.params.onAgentEvent?.({
16+
emitAgentEvent({
17+
runId: ctx.params.runId,
1818
stream: "compaction",
1919
data: { phase: "start" },
2020
});
@@ -71,12 +71,12 @@ export function handleAutoCompactionEnd(
7171
ctx.maybeResolveCompactionWait();
7272
clearStaleAssistantUsageOnSessionMessages(ctx);
7373
}
74-
emitAgentEvent({
75-
runId: ctx.params.runId,
74+
void ctx.params.onAgentEvent?.({
7675
stream: "compaction",
7776
data: { phase: "end", willRetry, completed: hasResult && !wasAborted },
7877
});
79-
void ctx.params.onAgentEvent?.({
78+
emitAgentEvent({
79+
runId: ctx.params.runId,
8080
stream: "compaction",
8181
data: { phase: "end", willRetry, completed: hasResult && !wasAborted },
8282
});

‎src/agents/pi-embedded-subscribe.handlers.lifecycle.test.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { createInlineCodeState } from "../markdown/code-spans.js";
3-
import { handleAgentEnd } from "./pi-embedded-subscribe.handlers.lifecycle.js";
3+
import {
4+
handleAgentEnd,
5+
handleAgentStart,
6+
} from "./pi-embedded-subscribe.handlers.lifecycle.js";
47
import type { EmbeddedPiSubscribeContext } from "./pi-embedded-subscribe.handlers.types.js";
8+
import { emitAgentEvent } from "../infra/agent-events.js";
59

610
vi.mock("../infra/agent-events.js", () => ({
711
emitAgentEvent: vi.fn(),
@@ -180,3 +184,29 @@ describe("handleAgentEnd", () => {
180184
expect(ctx.state.pendingToolAudioAsVoice).toBe(false);
181185
});
182186
});
187+
188+
describe("handleAgentStart", () => {
189+
it("notifies local listeners before broadcasting the global lifecycle event", () => {
190+
const order: string[] = [];
191+
const onAgentEvent = vi.fn(() => {
192+
order.push("local");
193+
});
194+
vi.mocked(emitAgentEvent).mockImplementation(() => {
195+
order.push("global");
196+
});
197+
const ctx = createContext(undefined, { onAgentEvent });
198+
199+
handleAgentStart(ctx);
200+
201+
expect(order).toEqual(["local", "global"]);
202+
expect(onAgentEvent).toHaveBeenCalledWith({
203+
stream: "lifecycle",
204+
data: { phase: "start" },
205+
});
206+
expect(emitAgentEvent).toHaveBeenCalledWith({
207+
runId: "run-1",
208+
stream: "lifecycle",
209+
data: expect.objectContaining({ phase: "start", startedAt: expect.any(Number) }),
210+
});
211+
});
212+
});

‎src/agents/pi-embedded-subscribe.handlers.lifecycle.ts‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ export {
2020

2121
export function handleAgentStart(ctx: EmbeddedPiSubscribeContext) {
2222
ctx.log.debug(`embedded run agent start: runId=${ctx.params.runId}`);
23+
// Let local consumers (for example webchat run-id linking) observe the
24+
// start before the global agent event fan-out sees the first lifecycle tick.
25+
void ctx.params.onAgentEvent?.({
26+
stream: "lifecycle",
27+
data: { phase: "start" },
28+
});
2329
emitAgentEvent({
2430
runId: ctx.params.runId,
2531
stream: "lifecycle",
@@ -28,10 +34,6 @@ export function handleAgentStart(ctx: EmbeddedPiSubscribeContext) {
2834
startedAt: Date.now(),
2935
},
3036
});
31-
void ctx.params.onAgentEvent?.({
32-
stream: "lifecycle",
33-
data: { phase: "start" },
34-
});
3537
}
3638

3739
export function handleAgentEnd(ctx: EmbeddedPiSubscribeContext) {
@@ -68,24 +70,28 @@ export function handleAgentEnd(ctx: EmbeddedPiSubscribeContext) {
6870
...observedError,
6971
consoleMessage: `embedded run agent end: runId=${safeRunId} isError=true model=${safeModel} provider=${safeProvider} error=${safeErrorText}${rawErrorConsoleSuffix}`,
7072
});
71-
emitAgentEvent({
72-
runId: ctx.params.runId,
73+
void ctx.params.onAgentEvent?.({
7374
stream: "lifecycle",
7475
data: {
7576
phase: "error",
7677
error: safeErrorText,
77-
endedAt: Date.now(),
7878
},
7979
});
80-
void ctx.params.onAgentEvent?.({
80+
emitAgentEvent({
81+
runId: ctx.params.runId,
8182
stream: "lifecycle",
8283
data: {
8384
phase: "error",
8485
error: safeErrorText,
86+
endedAt: Date.now(),
8587
},
8688
});
8789
} else {
8890
ctx.log.debug(`embedded run agent end: runId=${ctx.params.runId} isError=${isError}`);
91+
void ctx.params.onAgentEvent?.({
92+
stream: "lifecycle",
93+
data: { phase: "end" },
94+
});
8995
emitAgentEvent({
9096
runId: ctx.params.runId,
9197
stream: "lifecycle",
@@ -94,10 +100,6 @@ export function handleAgentEnd(ctx: EmbeddedPiSubscribeContext) {
94100
endedAt: Date.now(),
95101
},
96102
});
97-
void ctx.params.onAgentEvent?.({
98-
stream: "lifecycle",
99-
data: { phase: "end" },
100-
});
101103
}
102104

103105
ctx.flushBlockReplyBuffer();

‎src/agents/pi-embedded-subscribe.handlers.messages.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -306,12 +306,12 @@ export function handleMessageUpdate(
306306
delta: deltaText,
307307
mediaUrls,
308308
});
309-
emitAgentEvent({
310-
runId: ctx.params.runId,
309+
void ctx.params.onAgentEvent?.({
311310
stream: "assistant",
312311
data,
313312
});
314-
void ctx.params.onAgentEvent?.({
313+
emitAgentEvent({
314+
runId: ctx.params.runId,
315315
stream: "assistant",
316316
data,
317317
});
@@ -402,12 +402,12 @@ export function handleMessageEnd(
402402
delta: cleanedText,
403403
mediaUrls,
404404
});
405-
emitAgentEvent({
406-
runId: ctx.params.runId,
405+
void ctx.params.onAgentEvent?.({
407406
stream: "assistant",
408407
data,
409408
});
410-
void ctx.params.onAgentEvent?.({
409+
emitAgentEvent({
410+
runId: ctx.params.runId,
411411
stream: "assistant",
412412
data,
413413
});

‎src/agents/pi-embedded-subscribe.handlers.tools.ts‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,11 @@ export async function handleToolExecutionStart(
369369
);
370370

371371
const shouldEmitToolEvents = ctx.shouldEmitToolResult();
372+
// Best-effort typing signal; do not block tool summaries on slow emitters.
373+
void ctx.params.onAgentEvent?.({
374+
stream: "tool",
375+
data: { phase: "start", name: toolName, toolCallId },
376+
});
372377
emitAgentEvent({
373378
runId: ctx.params.runId,
374379
stream: "tool",
@@ -379,11 +384,6 @@ export async function handleToolExecutionStart(
379384
args: args as Record<string, unknown>,
380385
},
381386
});
382-
// Best-effort typing signal; do not block tool summaries on slow emitters.
383-
void ctx.params.onAgentEvent?.({
384-
stream: "tool",
385-
data: { phase: "start", name: toolName, toolCallId },
386-
});
387387

388388
if (
389389
ctx.params.onToolResult &&
@@ -430,22 +430,22 @@ export function handleToolExecutionUpdate(
430430
const toolCallId = String(evt.toolCallId);
431431
const partial = evt.partialResult;
432432
const sanitized = sanitizeToolResult(partial);
433-
emitAgentEvent({
434-
runId: ctx.params.runId,
433+
void ctx.params.onAgentEvent?.({
435434
stream: "tool",
436435
data: {
437436
phase: "update",
438437
name: toolName,
439438
toolCallId,
440-
partialResult: sanitized,
441439
},
442440
});
443-
void ctx.params.onAgentEvent?.({
441+
emitAgentEvent({
442+
runId: ctx.params.runId,
444443
stream: "tool",
445444
data: {
446445
phase: "update",
447446
name: toolName,
448447
toolCallId,
448+
partialResult: sanitized,
449449
},
450450
});
451451
}
@@ -549,26 +549,26 @@ export async function handleToolExecutionEnd(
549549
ctx.state.successfulCronAdds += 1;
550550
}
551551

552-
emitAgentEvent({
553-
runId: ctx.params.runId,
552+
void ctx.params.onAgentEvent?.({
554553
stream: "tool",
555554
data: {
556555
phase: "result",
557556
name: toolName,
558557
toolCallId,
559558
meta,
560559
isError: isToolError,
561-
result: sanitizedResult,
562560
},
563561
});
564-
void ctx.params.onAgentEvent?.({
562+
emitAgentEvent({
563+
runId: ctx.params.runId,
565564
stream: "tool",
566565
data: {
567566
phase: "result",
568567
name: toolName,
569568
toolCallId,
570569
meta,
571570
isError: isToolError,
571+
result: sanitizedResult,
572572
},
573573
});
574574

‎src/agents/pi-embedded-subscribe.subscribe-embedded-pi-session.subscribeembeddedpisession.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { AssistantMessage } from "@mariozechner/pi-ai";
22
import { describe, expect, it, vi } from "vitest";
3+
import { onAgentEvent } from "../infra/agent-events.js";
34
import {
45
THINKING_TAG_CASES,
56
createStubSessionHarness,
@@ -236,6 +237,44 @@ describe("subscribeEmbeddedPiSession", () => {
236237
expect(onReasoningEnd).toHaveBeenCalledTimes(1);
237238
});
238239

240+
it("emits thinking agent events even without an onReasoningStream callback", () => {
241+
const { session, emit } = createStubSessionHarness();
242+
const agentEvents: Array<{ stream?: string; data?: Record<string, unknown> }> = [];
243+
const stop = onAgentEvent((evt) => {
244+
agentEvents.push(evt as { stream?: string; data?: Record<string, unknown> });
245+
});
246+
247+
try {
248+
subscribeEmbeddedPiSession({
249+
session,
250+
runId: "run",
251+
reasoningMode: "stream",
252+
});
253+
254+
emit({
255+
type: "message_update",
256+
message: {
257+
role: "assistant",
258+
content: [{ type: "thinking", thinking: "Checking files" }],
259+
},
260+
assistantMessageEvent: {
261+
type: "thinking_delta",
262+
delta: "Checking files",
263+
},
264+
});
265+
266+
const thinkingEvents = agentEvents.filter((evt) => evt?.stream === "thinking");
267+
268+
expect(thinkingEvents).toHaveLength(1);
269+
expect(thinkingEvents[0]?.data).toMatchObject({
270+
text: "Reasoning:\n_Checking files_",
271+
delta: "Reasoning:\n_Checking files_",
272+
});
273+
} finally {
274+
stop();
275+
}
276+
});
277+
239278
it("emits reasoning end once when native and tagged reasoning end overlap", () => {
240279
const onReasoningEnd = vi.fn();
241280

‎src/agents/pi-embedded-subscribe.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ export function subscribeEmbeddedPiSession(params: SubscribeEmbeddedPiSessionPar
4848
reasoningMode,
4949
includeReasoning: reasoningMode === "on",
5050
shouldEmitPartialReplies: !(reasoningMode === "on" && !params.onBlockReply),
51-
streamReasoning: reasoningMode === "stream" && typeof params.onReasoningStream === "function",
51+
// Stream reasoning agent events whenever the run requests reasoning streaming.
52+
// UI callbacks are optional consumers of that stream and should not gate it.
53+
streamReasoning: reasoningMode === "stream",
5254
deltaBuffer: "",
5355
blockBuffer: "",
5456
// Track if a streamed chunk opened a <think> block (stateful across chunks).
@@ -573,7 +575,7 @@ export function subscribeEmbeddedPiSession(params: SubscribeEmbeddedPiSessionPar
573575
if (params.silentExpected) {
574576
return;
575577
}
576-
if (!state.streamReasoning || !params.onReasoningStream) {
578+
if (!state.streamReasoning) {
577579
return;
578580
}
579581
const formatted = formatReasoningMessage(text);
@@ -599,9 +601,11 @@ export function subscribeEmbeddedPiSession(params: SubscribeEmbeddedPiSessionPar
599601
},
600602
});
601603

602-
void params.onReasoningStream({
603-
text: formatted,
604-
});
604+
if (params.onReasoningStream) {
605+
void params.onReasoningStream({
606+
text: formatted,
607+
});
608+
}
605609
};
606610

607611
const resetForCompactionRetry = () => {

‎src/gateway/server-chat.agent-events.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,34 @@ describe("agent event handler", () => {
216216
nowSpy?.mockRestore();
217217
});
218218

219+
it("emits chat delta for streamed thinking events", () => {
220+
const { broadcast, nodeSendToSession, chatRunState, handler, nowSpy } = createHarness({
221+
now: 1_000,
222+
});
223+
chatRunState.registry.add("run-1", { sessionKey: "session-1", clientRunId: "client-1" });
224+
225+
handler({
226+
runId: "run-1",
227+
seq: 1,
228+
stream: "thinking",
229+
ts: Date.now(),
230+
data: { text: "Reasoning:\nCheck files" },
231+
});
232+
233+
const chatCalls = chatBroadcastCalls(broadcast);
234+
expect(chatCalls).toHaveLength(1);
235+
const payload = chatCalls[0]?.[1] as {
236+
state?: string;
237+
message?: {
238+
content?: Array<{ type?: string; text?: string; thinking?: string }>;
239+
};
240+
};
241+
expect(payload.state).toBe("delta");
242+
expect(payload.message?.content).toEqual([{ type: "thinking", thinking: "Reasoning:\nCheck files" }]);
243+
expect(sessionChatCalls(nodeSendToSession)).toHaveLength(1);
244+
nowSpy?.mockRestore();
245+
});
246+
219247
it("does not emit chat delta for NO_REPLY streaming text", () => {
220248
const { broadcast, nodeSendToSession, nowSpy } = emitRun1AssistantText(
221249
createHarness({ now: 1_000 }),

0 commit comments

Comments
 (0)