Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(chat): keep mid-tool-call assistant reply in one bubble across background switch-away (#3644)

Harsh Kumara0e06846a291
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
index 5b1248cb6..b2a4e9553 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
@@ -34,7 +34,7 @@ function piEvt(sessionId: string, event: AgentInnerEvent): AgentEventEnvelope {
}
function reset() {
- useChatStore.setState({ sessions: {}, currentId: null });
+ useChatStore.setState({ sessions: {}, currentId: null, panelSessionId: null });
}
function seed(id: string, overrides: Partial<SessionRecord> = {}) {
@@ -181,6 +181,71 @@ describe("pi-event-router: background content accumulation (the parallel-chat re
expect(useChatStore.getState().sessions.A.messages ?? []).toEqual([]);
expect(useChatStore.getState().sessions.A.streamingMessageId).toBeFalsy();
});
+
+ it("keeps one assistant message across turn_end + assistant restart after switch-away", async () => {
+ // Reproduces the user's bug: switch away while a tool-using reply is
+ // mid-stream, then background routing takes over and sees an internal
+ // turn_end followed by another assistant message_start. That must stay in
+ // the SAME assistant bubble instead of splitting into multiple rows.
+ seed("A", {
+ status: "streaming",
+ isLoading: true,
+ isStreaming: true,
+ streamingMessageId: "msg-1",
+ streamingText: "Let me check. ",
+ contentBlocks: [{ type: "text", text: "Let me check. " }],
+ messages: [
+ {
+ id: "msg-1",
+ role: "assistant",
+ content: "Let me check. ",
+ contentBlocks: [{ type: "text", text: "Let me check. " }],
+ timestamp: 1_234,
+ },
+ ],
+ messageCount: 1,
+ });
+ useChatStore.setState({ currentId: "B" });
+
+ await handlePiEvent(piEvt("A", { type: "turn_end" }));
+ await handlePiEvent(
+ piEvt("A", { type: "message_start", message: { role: "assistant" } }),
+ );
+ await handlePiEvent(
+ piEvt("A", {
+ type: "tool_execution_start",
+ toolCallId: "tool-1",
+ toolName: "bash",
+ args: { command: "echo hi" },
+ } as any),
+ );
+ await handlePiEvent(
+ piEvt("A", {
+ type: "tool_execution_end",
+ toolCallId: "tool-1",
+ result: { content: [{ text: "hi" }] },
+ } as any),
+ );
+ await handlePiEvent(
+ piEvt("A", {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "Done." },
+ }),
+ );
+
+ const session = useChatStore.getState().sessions.A;
+ expect(session.messages).toHaveLength(1);
+ expect(session.streamingMessageId).toBe("msg-1");
+ const assistant = session.messages![0] as any;
+ expect(assistant.id).toBe("msg-1");
+ expect(assistant.content).toBe("Let me check. Done.");
+ expect(assistant.contentBlocks.map((b: any) => b.type)).toEqual([
+ "text",
+ "tool",
+ "text",
+ ]);
+ expect(assistant.contentBlocks[1].toolCall.result).toBe("hi");
+ });
});
describe("pi-event-router: agent_terminated", () => {
diff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
index 23a106629..a7dc15340 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -446,9 +446,17 @@ function applyEventToSessionContent(sid: string, payload: PiInnerEvent) {
const t = payload.type;
- // Assistant message starts — create a new in-flight message shell
- // and remember its id as the streaming target.
+ // Assistant message starts. When a session moves to the background in the
+ // middle of a tool-using reply, Pi may emit another assistant
+ // `message_start` after an internal `turn_end`. Foreground chat keeps that
+ // work inside the SAME visible assistant bubble, so background routing must
+ // reuse the existing streaming target instead of creating a second message.
+ //
+ // Only create a fresh assistant shell when we truly have no in-flight
+ // assistant message for this session.
if (t === "message_start" && payload.message?.role === "assistant") {
+ const cur = store.sessions[sid];
+ if (cur?.streamingMessageId) return;
const newId = `pi-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const newMsg: MutableMessage = {
id: newId,
@@ -557,20 +565,12 @@ function applyEventToSessionContent(sid: string, payload: PiInnerEvent) {
}
// turn_end fires between LLM turns within a single agent run (typically
- // across a tool-call boundary). The agent is still streaming — only the
- // current message's accumulator should be cleared so the next
- // message_start gets a fresh slate. Calling endTurn here would briefly
- // flip isStreaming/isLoading false and falsely settle the session
- // mid-run.
+ // across a tool-call boundary). Foreground chat does NOT split the visible
+ // assistant reply here; it keeps appending follow-up tool work and prose to
+ // the same assistant bubble until the full run reaches agent_end. The
+ // background router must mirror that shape or switching away mid-response
+ // will fragment one reply into several tiny assistant messages.
if (t === "turn_end") {
- const cur = store.sessions[sid];
- if (cur?.streamingMessageId) {
- store.actions.setStreaming(sid, {
- streamingMessageId: null,
- streamingText: "",
- contentBlocks: [],
- });
- }
return;
}