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): coalesce pipe-run assistant turns + show real work duration

Louis Beaumont7ffb2acaaf8d
diff --git a/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts b/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts
index 6cd52a076..13fcedc8f 100644
--- a/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts
+++ b/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts
@@ -191,25 +191,22 @@ describe("parsePipeNdjsonToMessages", () => {
].join("\n");
const msgs = parsePipeNdjsonToMessages(stdout);
- // user, assistant (with tool), assistant (final)
- expect(msgs.length).toBeGreaterThanOrEqual(3);
+ // user, then a single coalesced assistant covering tool + final text
+ expect(msgs.length).toBe(2);
expect(msgs[0].role).toBe("user");
expect(msgs[0].content).toBe("Check my activity");
- // First assistant has tool call
- expect(msgs[1].role).toBe("assistant");
- expect(msgs[1].contentBlocks).toBeDefined();
- const toolBlock = msgs[1].contentBlocks!.find(
+ // Coalesced assistant: tool call + final text in one message
+ const assistant = msgs[1];
+ expect(assistant.role).toBe("assistant");
+ expect(assistant.contentBlocks).toBeDefined();
+ const toolBlock = assistant.contentBlocks!.find(
(b: any) => b.type === "tool"
);
expect(toolBlock).toBeDefined();
expect(toolBlock.toolCall.toolName).toBe("bash");
-
- // Second assistant has final text
- const lastAssistant = msgs[msgs.length - 1];
- expect(lastAssistant.role).toBe("assistant");
- expect(lastAssistant.content).toContain("focused on coding");
+ expect(assistant.content).toContain("focused on coding");
});
// ─── agent_end fallback ───────────────────────────────────────────
@@ -256,31 +253,30 @@ describe("parsePipeNdjsonToMessages", () => {
].join("\n");
const msgs = parsePipeNdjsonToMessages(stdout);
- // user, assistant+tool, assistant+tool, assistant (final)
- expect(msgs.length).toBe(4);
+ // user, then one coalesced assistant covering all turns
+ expect(msgs.length).toBe(2);
expect(msgs[0].role).toBe("user");
expect(msgs[0].content).toBe("Check meetings");
- // First assistant: text + tool call
- expect(msgs[1].role).toBe("assistant");
- expect(msgs[1].content).toBe("Let me check.");
- const tool1 = msgs[1].contentBlocks?.find((b: any) => b.type === "tool");
- expect(tool1).toBeDefined();
- expect(tool1.toolCall.toolName).toBe("bash");
- // toolResult should be attached
- expect(tool1.toolCall.result).toContain("No meetings found");
-
- // Second assistant: text + tool call
- expect(msgs[2].role).toBe("assistant");
- expect(msgs[2].content).toBe("Let me search audio.");
- const tool2 = msgs[2].contentBlocks?.find((b: any) => b.type === "tool");
- expect(tool2).toBeDefined();
- expect(tool2.toolCall.result).toContain("Some audio fragments");
-
- // Final assistant: just text
- expect(msgs[3].role).toBe("assistant");
- expect(msgs[3].content).toBe("No real meetings detected. Just ambient audio.");
+ // Coalesced assistant: text + tool + text + tool + text (in order)
+ const assistant = msgs[1];
+ expect(assistant.role).toBe("assistant");
+ const blockTypes = assistant.contentBlocks!.map((b: any) => b.type);
+ expect(blockTypes).toEqual(["text", "tool", "text", "tool", "text"]);
+
+ const tools = assistant.contentBlocks!.filter((b: any) => b.type === "tool");
+ expect(tools).toHaveLength(2);
+ expect(tools[0].toolCall.toolName).toBe("bash");
+ expect(tools[0].toolCall.result).toContain("No meetings found");
+ expect(tools[1].toolCall.result).toContain("Some audio fragments");
+
+ // Final answer is the last text block
+ const finalText = assistant.contentBlocks![assistant.contentBlocks!.length - 1];
+ expect(finalText.text).toContain("No real meetings detected");
+
+ // The coalesced assistant's content also surfaces the final text
+ expect(assistant.content).toContain("No real meetings detected");
});
it("hides Codex-style function return messages from agent_end", () => {
@@ -295,15 +291,24 @@ describe("parsePipeNdjsonToMessages", () => {
const msgs = parsePipeNdjsonToMessages(stdout);
- expect(msgs.map((m) => m.content)).toEqual([
- "Analyze my screen",
- "Let me search.",
- "I found usable screen data.",
- ]);
+ // The "Return of functions.bash" pseudo-user is a tool-return marker,
+ // not a real user turn — so the assistant chain isn't broken by it
+ // and both assistant turns coalesce into one message.
+ expect(msgs).toHaveLength(2);
+ expect(msgs[0].role).toBe("user");
+ expect(msgs[0].content).toBe("Analyze my screen");
expect(
msgs.some((m) => String(m.content).includes("Return of functions.bash")),
).toBe(false);
- const toolBlock = msgs[1].contentBlocks?.find((b: any) => b.type === "tool");
+
+ const assistant = msgs[1];
+ expect(assistant.role).toBe("assistant");
+ const textBlocks = assistant.contentBlocks!.filter((b: any) => b.type === "text");
+ expect(textBlocks.map((b: any) => b.text)).toEqual([
+ "Let me search.",
+ "I found usable screen data.",
+ ]);
+ const toolBlock = assistant.contentBlocks?.find((b: any) => b.type === "tool");
expect(toolBlock?.toolCall.result).toContain('"data"');
});
@@ -334,22 +339,18 @@ describe("parsePipeNdjsonToMessages", () => {
const msgs = parsePipeNdjsonToMessages(stdout);
- // Should use agent_end which has complete text
- expect(msgs.length).toBeGreaterThanOrEqual(3);
+ // Should use agent_end which has complete text. Both assistant
+ // turns coalesce into one message.
+ expect(msgs).toHaveLength(2);
- // User prompt
expect(msgs[0].role).toBe("user");
expect(msgs[0].content).toContain("Execute the pipe");
- // First assistant with tool
- expect(msgs[1].role).toBe("assistant");
- expect(msgs[1].content).toBe("Checking activity.");
- expect(msgs[1].contentBlocks?.some((b: any) => b.type === "tool")).toBe(true);
-
- // Final assistant with summary
- const lastAssistant = msgs[msgs.length - 1];
- expect(lastAssistant.role).toBe("assistant");
- expect(lastAssistant.content).toContain("coding for the past hour");
+ const assistant = msgs[1];
+ expect(assistant.role).toBe("assistant");
+ expect(assistant.contentBlocks?.some((b: any) => b.type === "tool")).toBe(true);
+ expect(assistant.content).toContain("Checking activity.");
+ expect(assistant.content).toContain("coding for the past hour");
});
// ─── error handling ───────────────────────────────────────────────
@@ -432,26 +433,21 @@ describe("parsePipeNdjsonToMessages", () => {
const msgs = parsePipeNdjsonToMessages(stdout);
- // Should have: user, assistant (tool call), assistant (final text)
- expect(msgs.length).toBeGreaterThanOrEqual(3);
+ // user, then a single coalesced assistant covering tool + final text
+ expect(msgs).toHaveLength(2);
- // First: user with time range
expect(msgs[0].role).toBe("user");
expect(msgs[0].content).toContain("Time range:");
- // Second: assistant with tool call to read SKILL.md
- expect(msgs[1].role).toBe("assistant");
- expect(msgs[1].contentBlocks).toBeDefined();
- const toolBlock = msgs[1].contentBlocks!.find(
+ const assistant = msgs[1];
+ expect(assistant.role).toBe("assistant");
+ expect(assistant.contentBlocks).toBeDefined();
+ const toolBlock = assistant.contentBlocks!.find(
(b: any) => b.type === "tool"
);
expect(toolBlock).toBeDefined();
expect(toolBlock.toolCall.toolName).toBe("read");
-
- // Last: assistant with final verdict
- const lastMsg = msgs[msgs.length - 1];
- expect(lastMsg.role).toBe("assistant");
- expect(lastMsg.content).toContain("focused");
+ expect(assistant.content).toContain("focused");
});
// ─── real-world: obsidian-sync multi-turn ─────────────────────────
@@ -482,27 +478,22 @@ describe("parsePipeNdjsonToMessages", () => {
const msgs = parsePipeNdjsonToMessages(stdout);
- // user, assistant (query + tool), assistant (final)
- expect(msgs.length).toBeGreaterThanOrEqual(3);
+ // user, then a single coalesced assistant covering both turns
+ expect(msgs).toHaveLength(2);
const user = msgs[0];
expect(user.role).toBe("user");
expect(user.content).toContain("Time range:");
- const firstAssistant = msgs[1];
- expect(firstAssistant.role).toBe("assistant");
- expect(firstAssistant.contentBlocks).toBeDefined();
- // Should have text and tool blocks (tool_result is attached to the tool block)
- const blockTypes = firstAssistant.contentBlocks!.map((b: any) => b.type);
+ const assistant = msgs[1];
+ expect(assistant.role).toBe("assistant");
+ expect(assistant.contentBlocks).toBeDefined();
+ const blockTypes = assistant.contentBlocks!.map((b: any) => b.type);
expect(blockTypes).toContain("text");
expect(blockTypes).toContain("tool");
- // Tool result should be attached to the tool block
- const toolBlock = firstAssistant.contentBlocks!.find((b: any) => b.type === "tool");
+ const toolBlock = assistant.contentBlocks!.find((b: any) => b.type === "tool");
expect(toolBlock.toolCall.result).toContain("WezTerm");
-
- const lastAssistant = msgs[msgs.length - 1];
- expect(lastAssistant.role).toBe("assistant");
- expect(lastAssistant.content).toContain("Obsidian vault");
+ expect(assistant.content).toContain("Obsidian vault");
});
// ─── skips non-assistant message_start/end ────────────────────────
@@ -546,6 +537,67 @@ describe("parsePipeNdjsonToMessages", () => {
const uniqueIds = new Set(ids);
expect(uniqueIds.size).toBe(ids.length);
});
+
+ // ─── coalescing: many single-tool turns → one assistant ─────────────
+
+ it("coalesces N consecutive single-tool assistant turns into one assistant", () => {
+ // Reproduces the pipe-history screenshot: each agent step is a
+ // separate assistant message holding just one tool call. Before
+ // coalescing this rendered as N stacked "ran 1 command" headers;
+ // after, it's one assistant message whose tool calls the renderer
+ // can fold into a single "Worked for X min" rail.
+ const stdout = [
+ '{"type":"agent_end","messages":[' +
+ '{"role":"user","content":[{"type":"text","text":"sync messages"}],"timestamp":1000}' +
+ ',{"role":"assistant","content":[{"type":"toolCall","id":"t1","name":"read","arguments":{"path":"state.json"}}],"timestamp":2000}' +
+ ',{"role":"toolResult","content":[{"type":"text","text":"r1"}],"timestamp":2500}' +
+ ',{"role":"assistant","content":[{"type":"toolCall","id":"t2","name":"bash","arguments":{"command":"bun run /tmp/sync.ts"}}],"timestamp":3000}' +
+ ',{"role":"toolResult","content":[{"type":"text","text":"r2"}],"timestamp":3500}' +
+ ',{"role":"assistant","content":[{"type":"toolCall","id":"t3","name":"bash","arguments":{"command":"ls"}}],"timestamp":4000}' +
+ ',{"role":"toolResult","content":[{"type":"text","text":"r3"}],"timestamp":4500}' +
+ ',{"role":"assistant","content":[{"type":"text","text":"Sync complete."}],"timestamp":5000}' +
+ ']}',
+ ].join("\n");
+
+ const msgs = parsePipeNdjsonToMessages(stdout);
+ expect(msgs).toHaveLength(2);
+
+ const assistant = msgs[1];
+ expect(assistant.role).toBe("assistant");
+ const tools = assistant.contentBlocks!.filter((b: any) => b.type === "tool");
+ expect(tools).toHaveLength(3);
+ expect(tools[0].toolCall.toolName).toBe("read");
+ expect(tools[1].toolCall.toolName).toBe("bash");
+ expect(tools[2].toolCall.toolName).toBe("bash");
+ expect(tools[0].toolCall.result).toBe("r1");
+ expect(tools[1].toolCall.result).toBe("r2");
+ expect(tools[2].toolCall.result).toBe("r3");
+
+ // Wall-clock duration captured from timestamps
+ expect(assistant.workDurationMs).toBe(3000); // first asst 2000 → last toolResult 5000? no — last asst is 5000, but last seen ts is 5000
+ });
+
+ it("captures workDurationMs from streaming message timestamps", () => {
+ const stdout = [
+ '{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"hi"}]}}',
+ '{"type":"message_end","message":{"role":"user","content":[{"type":"text","text":"hi"}]}}',
+ '{"type":"message_start","message":{"role":"assistant","content":[],"timestamp":1000}}',
+ '{"type":"message_update","assistantMessageEvent":{"type":"toolcall_start","contentIndex":0,"toolName":"bash","partial":{}}}',
+ '{"type":"message_update","assistantMessageEvent":{"type":"toolcall_end","contentIndex":0,"toolCall":{"type":"toolCall","id":"t1","name":"bash","arguments":{"command":"ls"}},"partial":{}}}',
+ '{"type":"message_end","message":{"role":"assistant","content":[],"timestamp":2000}}',
+ '{"type":"turn_end"}',
+ '{"type":"turn_start"}',
+ '{"type":"message_start","message":{"role":"assistant","content":[],"timestamp":3000}}',
+ '{"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"done","partial":{}}}',
+ '{"type":"message_end","message":{"role":"assistant","content":[],"timestamp":4000}}',
+ ].join("\n");
+
+ const msgs = parsePipeNdjsonToMessages(stdout);
+ expect(msgs).toHaveLength(2);
+ const assistant = msgs[1];
+ // first asst ts = 1000, last ts seen = 4000
+ expect(assistant.workDurationMs).toBe(3000);
+ });
});
// ─── pipeExecutionToConversation ──────────────────────────────────
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 884fa8459..599f09f8b 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -760,6 +760,7 @@ interface Message {
retryPrompt?: string; // when set, renders a retry CTA on error messages
interruptedBySteer?: boolean;
steeredResponse?: boolean;
+ workDurationMs?: number; // wall-clock work duration for coalesced pipe-run assistants
}
type QueuedDisplayPayload = {
@@ -2207,7 +2208,11 @@ function groupContentBlocks(blocks: ContentBlock[]): GroupedBlock[] {
}
function collapseHiddenWorkGroups(grouped: GroupedBlock[], hideThinkingBlocks: boolean): GroupedBlock[] {
- if (!hideThinkingBlocks) return grouped;
+ // Run always: collapsing consecutive tool-groups into a single
+ // "Worked for X min" rail is useful regardless of the thinking-block
+ // visibility setting. `hideThinkingBlocks` only controls whether
+ // thinking blocks get absorbed into the work-group (true) or shown
+ // as separate pills (false).
const out: GroupedBlock[] = [];
let pendingToolCalls: ToolCall[] = [];
@@ -2250,8 +2255,15 @@ function collapseHiddenWorkGroups(grouped: GroupedBlock[], hideThinkingBlocks: b
}
if (group.type === "thinking") {
- pendingDurationMs += group.durationMs ?? 0;
- pendingKey ??= group.key;
+ if (hideThinkingBlocks) {
+ pendingDurationMs += group.durationMs ?? 0;
+ pendingKey ??= group.key;
+ continue;
+ }
+ // Show thinking pills inline — flush pending tool work first so
+ // ordering is preserved and the thinking pill renders separately.
+ flushPending();
+ out.push(group);
continue;
}
@@ -2454,12 +2466,17 @@ function MessageContent({
return <ToolCallGroup key={`tools-${group.key}`} toolCalls={group.toolCalls} defaultExpanded={!hasText} />;
}
if (group.type === "work-group") {
+ // Fall back to message-level workDurationMs when the
+ // grouping pass collected no thinking-block duration (e.g.
+ // pipe runs whose agent emits no thinking deltas — the
+ // parser captures wall-clock time on the ChatMessage).
+ const durationMs = group.durationMs > 0 ? group.durationMs : (message.workDurationMs ?? 0);
return (
<ToolCallGroup
key={`work-${group.key}`}
toolCalls={group.toolCalls}
defaultExpanded={!hasText}
- summaryOverride={formatWorkDuration(group.durationMs)}
+ summaryOverride={formatWorkDuration(durationMs)}
hideCount={hasText}
/>
);
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 5db92cf63..d0b084283 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -98,6 +98,11 @@ export interface ChatMessage {
images?: any[];
interruptedBySteer?: boolean;
steeredResponse?: boolean;
+ /** Wall-clock work duration for coalesced assistant messages (pipe
+ * runs). Used by the chat renderer as a fallback when no thinking
+ * blocks contributed a duration, so the work-group can still show
+ * "Worked for X min" even when the agent emitted no thinking. */
+ workDurationMs?: number;
}
/** What kind of session a conversation represents.
diff --git a/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts b/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts
index e3902f047..45068c131 100644
--- a/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts
+++ b/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts
@@ -43,6 +43,11 @@ function extractToolCalls(content: any[], msgIndex: number): any[] {
*
* Strategy: prefer agent_end (has full conversation) over streaming events.
* Fall back to streaming events and cleanPipeStdout for truncated data.
+ *
+ * Consecutive `assistant` messages between user boundaries are coalesced
+ * into a single ChatMessage so the chat renderer can group their tool
+ * calls into one "Worked for X min" rail instead of stacking a tower of
+ * single-tool headers.
*/
export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
let agentEndMessages: any[] | null = null;
@@ -66,18 +71,46 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
// If we have agent_end, use it as the authoritative source
if (agentEndMessages && agentEndMessages.length > 0) {
const messages: ChatMessage[] = [];
- let lastToolBlocks: any[] = [];
+ let pendingBlocks: any[] = [];
+ let pendingTexts: string[] = [];
+ let pendingTools: any[] = [];
+ let pendingFirstTs: number | null = null;
+ let pendingLastTs: number | null = null;
+
+ const flushPendingAssistant = () => {
+ if (pendingBlocks.length === 0) return;
+ const text = pendingTexts.filter((t) => t.trim()).join("\n\n").trim();
+ const durationMs =
+ pendingFirstTs !== null && pendingLastTs !== null && pendingLastTs > pendingFirstTs
+ ? pendingLastTs - pendingFirstTs
+ : undefined;
+ const chatMsg: ChatMessage = {
+ id: `pipe-msg-${messageCounter++}`,
+ role: "assistant",
+ content: text,
+ timestamp: ts,
+ contentBlocks: pendingBlocks.length > 0 ? pendingBlocks : undefined,
+ };
+ if (durationMs !== undefined) chatMsg.workDurationMs = durationMs;
+ messages.push(chatMsg);
+ pendingBlocks = [];
+ pendingTexts = [];
+ pendingTools = [];
+ pendingFirstTs = null;
+ pendingLastTs = null;
+ };
for (let i = 0; i < agentEndMessages.length; i++) {
const msg = agentEndMessages[i];
const role = msg.role;
const content = msg.content;
const text = extractText(content);
+ const msgTs = typeof msg.timestamp === "number" ? msg.timestamp : null;
if (isToolReturnMessage(msg, text)) {
const resultText = toolReturnResultText(text);
- if (resultText && lastToolBlocks.length > 0) {
- const lastTool = lastToolBlocks[lastToolBlocks.length - 1];
+ if (resultText && pendingTools.length > 0) {
+ const lastTool = pendingTools[pendingTools.length - 1];
if (lastTool?.toolCall && !lastTool.toolCall.result) {
lastTool.toolCall.result =
resultText.length > 2000
@@ -85,10 +118,12 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
: resultText;
}
}
+ if (msgTs !== null) pendingLastTs = msgTs;
continue;
}
if (role === "user") {
+ flushPendingAssistant();
if (!text.trim()) continue;
const isPipePrompt = text.includes("Time range:") && text.includes("Execute the pipe now.");
const chatMsg: any = {
@@ -113,28 +148,27 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
}
if (role === "assistant") {
+ if (msgTs !== null) {
+ if (pendingFirstTs === null) pendingFirstTs = msgTs;
+ pendingLastTs = msgTs;
+ }
const toolBlocks = Array.isArray(content) ? extractToolCalls(content, i) : [];
- lastToolBlocks = toolBlocks;
- const contentBlocks: any[] = [];
if (text.trim()) {
- contentBlocks.push({ type: "text", text: text.trim() });
+ pendingBlocks.push({ type: "text", text: text.trim() });
+ pendingTexts.push(text.trim());
+ }
+ for (const tb of toolBlocks) {
+ pendingBlocks.push(tb);
+ pendingTools.push(tb);
}
- contentBlocks.push(...toolBlocks);
- messages.push({
- id: `pipe-msg-${messageCounter++}`,
- role: "assistant",
- content: text.trim(),
- timestamp: ts,
- contentBlocks: contentBlocks.length > 0 ? contentBlocks : undefined,
- });
continue;
}
if (role === "toolResult") {
- // Attach tool result to the last tool block in the previous assistant message
+ // Attach tool result to the last tool block in the pending assistant
const resultText = extractText(content);
- if (resultText && lastToolBlocks.length > 0) {
- const lastTool = lastToolBlocks[lastToolBlocks.length - 1];
+ if (resultText && pendingTools.length > 0) {
+ const lastTool = pendingTools[pendingTools.length - 1];
if (lastTool?.toolCall && !lastTool.toolCall.result) {
const truncated = resultText.length > 2000
? resultText.slice(0, 2000) + "\n... (truncated)"
@@ -142,11 +176,14 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
lastTool.toolCall.result = truncated;
}
}
+ if (msgTs !== null) pendingLastTs = msgTs;
continue;
}
}
- if (messages.some((m) => m.role === "assistant" && m.content?.trim())) {
+ flushPendingAssistant();
+
+ if (messages.some((m) => m.role === "assistant" && (m.content?.trim() || (m.contentBlocks?.length ?? 0) > 0))) {
return messages;
}
}
@@ -157,10 +194,23 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
let currentBlocks: any[] = [];
let currentToolCall: { name: string; input: string } | null = null;
let inAssistantTurn = false;
+ let workFirstTs: number | null = null;
+ let workLastTs: number | null = null;
+
+ function commitPendingText() {
+ const text = currentText.trim();
+ if (!text) return;
+ const last = currentBlocks[currentBlocks.length - 1];
+ if (last?.type === "text") {
+ last.text = ((last.text ?? "") + (last.text ? "\n" : "") + text).trim();
+ } else {
+ currentBlocks.push({ type: "text", text });
+ }
+ currentText = "";
+ }
function flushAssistant() {
if (!inAssistantTurn) return;
- const text = currentText.trim();
// Trailing prose that arrived after the last toolcall_start (or
// when no tool call ever fired) is still sitting in currentText
// and was never converted into a content-block. The chat renderer
@@ -169,27 +219,33 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
// render as just the thinking pill — the prose was on disk but
// invisible. Promote the trailing text to a final text block here
// so the renderer actually shows it.
- if (text) {
- const last = currentBlocks[currentBlocks.length - 1];
- if (last?.type === "text") {
- last.text = ((last.text ?? "") + (last.text ? "\n" : "") + text).trim();
- } else {
- currentBlocks.push({ type: "text", text });
- }
- }
- if (text || currentBlocks.length > 0) {
- messages.push({
+ commitPendingText();
+ if (currentBlocks.length > 0) {
+ const fullText = currentBlocks
+ .filter((b) => b.type === "text")
+ .map((b) => b.text)
+ .join("\n\n")
+ .trim();
+ const durationMs =
+ workFirstTs !== null && workLastTs !== null && workLastTs > workFirstTs
+ ? workLastTs - workFirstTs
+ : undefined;
+ const chatMsg: ChatMessage = {
id: `pipe-msg-${messageCounter++}`,
role: "assistant",
- content: text,
+ content: fullText,
timestamp: ts,
- contentBlocks: currentBlocks.length > 0 ? [...currentBlocks] : undefined,
- });
+ contentBlocks: [...currentBlocks],
+ };
+ if (durationMs !== undefined) chatMsg.workDurationMs = durationMs;
+ messages.push(chatMsg);
}
currentText = "";
currentBlocks = [];
currentToolCall = null;
inAssistantTurn = false;
+ workFirstTs = null;
+ workLastTs = null;
}
for (const line of raw.split("\n")) {
@@ -223,8 +279,17 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
}
if (evtType === "message_start" && evt.message?.role === "assistant") {
- flushAssistant();
+ // Don't flush — coalesce consecutive assistant turns into one
+ // ChatMessage so the renderer can group their tool calls.
+ // Convert any pending text into a block to preserve order with
+ // subsequent tool calls from this new turn.
+ commitPendingText();
inAssistantTurn = true;
+ const msgTs = typeof evt.message?.timestamp === "number" ? evt.message.timestamp : null;
+ if (msgTs !== null) {
+ if (workFirstTs === null) workFirstTs = msgTs;
+ workLastTs = msgTs;
+ }
continue;
}
@@ -238,7 +303,7 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
if (lastBlock?.type === "thinking") lastBlock.text += ae.delta;
else currentBlocks.push({ type: "thinking", text: ae.delta });
} else if (ae.type === "toolcall_start") {
- if (currentText.trim()) { currentBlocks.push({ type: "text", text: currentText.trim() }); currentText = ""; }
+ commitPendingText();
let toolName = ae.toolName || "unknown";
if (toolName === "unknown" && ae.partial?.content) {
for (const c of ae.partial.content) { if (c.type === "toolCall" && c.name) { toolName = c.name; break; } }
@@ -258,6 +323,11 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
if (evtType === "message_end" && evt.message?.role === "assistant") {
const content = evt.message.content;
+ const msgTs = typeof evt.message?.timestamp === "number" ? evt.message.timestamp : null;
+ if (msgTs !== null) {
+ if (workFirstTs === null) workFirstTs = msgTs;
+ workLastTs = msgTs;
+ }
if (Array.isArray(content) && !currentText.trim()) {
currentText = extractText(content);
for (const block of content) {
@@ -279,10 +349,15 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
if (lastBlock?.type === "tool" && lastBlock.toolCall && !lastBlock.toolCall.result) lastBlock.toolCall.result = truncated;
}
}
+ const evtTs = typeof evt.timestamp === "number" ? evt.timestamp : null;
+ if (evtTs !== null) workLastTs = evtTs;
continue;
}
- if (evtType === "turn_end") { flushAssistant(); continue; }
+ // turn_end no longer flushes — assistant turns are coalesced until
+ // the next user message or end-of-stream so the renderer can
+ // group all tool calls into a single work bucket.
+ if (evtType === "turn_end") { commitPendingText(); continue; }
}
flushAssistant();