Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(responses): strip commentary from live results and answer copy

vastsa3cf4c6935362
diff --git a/apps/desktop/electron/main/live-voice/live-session-events.ts b/apps/desktop/electron/main/live-voice/live-session-events.ts
index eccbad1bb..213ccfba9 100644
--- a/apps/desktop/electron/main/live-voice/live-session-events.ts
+++ b/apps/desktop/electron/main/live-voice/live-session-events.ts
@@ -1,4 +1,4 @@
-import type { AgentEvent, SessionSource } from "@pi-desktop/shared";
+import { responsesAnswerText, type AgentEvent, type SessionSource } from "@pi-desktop/shared";
import type { AgentSidecar } from "../agent-sidecar";
import type { RemoteHostsBoot } from "../bootstrap/remote-hosts";
@@ -28,7 +28,10 @@ export function subscribeLiveSessionEvents(input: {
}
if (event.type === "message_end" && event.message.role === "assistant" && !parentToolCallId && !agentName) {
results.set(turnId, {
- text: typeof event.message.content === "string" ? event.message.content : "",
+ // Commentary is progress, not the turn's result (#2461).
+ text: typeof event.message.content === "string"
+ ? responsesAnswerText(event.message.content, event.message.providerReplay)
+ : "",
messageId: event.message.id,
});
return;
diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
index 0227013d1..ac76f333f 100644
--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
@@ -28,6 +28,7 @@ import {
import { TranscriptHistory, TranscriptTail } from "./AssistantTurn";
import { collectLiveDelegationEntries } from "../../../lib/live-delegation-entries";
import { reuseReadonlyMap } from "../../../lib/assistant-turns";
+import { projectAssistantCommentary } from "../../../lib/assistant-commentary";
import { liveHistoryTurnId } from "../../../lib/turn-process";
import { useTranscriptScroll } from "./hooks/useTranscriptScroll";
import { useTranscriptContinuation } from "../../../hooks/use-transcript-continuation";
@@ -303,9 +304,11 @@ function TranscriptBody({
const findLastAnswer = (): string => {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
- if (message?.role === "assistant" && message.content.trim()) {
- return message.content;
- }
+ // Copy the answer only; Responses commentary stays in the process (#2461).
+ const answer = message?.role === "assistant"
+ ? projectAssistantCommentary(message)?.reply.message.content ?? message.content
+ : "";
+ if (answer.trim()) return answer;
}
return "";
};
diff --git a/apps/desktop/src/lib/assistant-commentary.ts b/apps/desktop/src/lib/assistant-commentary.ts
index a99358227..da3813bbd 100644
--- a/apps/desktop/src/lib/assistant-commentary.ts
+++ b/apps/desktop/src/lib/assistant-commentary.ts
@@ -1,4 +1,4 @@
-import { isResponsesCommentary, type AssistantProviderReplay, type UiMessage } from "@pi-desktop/shared";
+import { splitResponsesCommentary, type AssistantProviderReplay, type UiMessage } from "@pi-desktop/shared";
import type { AssistantTurnPart } from "./assistant-turns";
type MessagePart = Extract<AssistantTurnPart, { kind: "message" }>;
@@ -9,48 +9,23 @@ const projections = new WeakMap<UiMessage, CommentaryProjection | undefined>();
function splitCommentary(
message: UiMessage, replay: AssistantProviderReplay,
): CommentaryProjection | undefined {
- const { content } = message;
- if (typeof content !== "string" || replay.version !== 1 || !Array.isArray(replay.blocks)) return undefined;
- const progress: MessagePart[] = [];
- let offset = 0;
- let replyStart = 0;
- let replyText = "";
- for (const block of replay.blocks) {
- if (
- !block || (block.type !== "text" && block.type !== "thinking") ||
- !Number.isSafeInteger(block.length) || block.length < 0 ||
- (block.signature !== undefined && typeof block.signature !== "string")
- ) return undefined;
- // Thinking has its own string. Every text block, signed or not, consumes
- // exactly its UTF-16 length in the stored content.
- if (block.type === "thinking") continue;
- const end = offset + block.length;
- if (end > content.length) return undefined;
- if (end > offset && isResponsesCommentary(block.signature)) {
- replyText += content.slice(replyStart, offset);
- replyStart = end;
- const text = content.slice(offset, end);
- if (text.trim()) {
- progress.push({
- kind: "message",
- sourceMessageId: message.id,
- message: {
- id: `${message.id}:commentary:${offset}`, role: "assistant", content: text,
- createdAt: message.createdAt, status: message.status,
- },
- });
- }
- }
- offset = end;
- }
- // Never use a partial match (e.g. an abbreviated history row), and keep
- // ordinary rows by identity when no text was explicitly marked.
- if (offset !== content.length || replyStart === 0) return undefined;
+ const split = splitResponsesCommentary(message.content, replay);
+ if (!split) return undefined;
+ const progress: MessagePart[] = split.commentary
+ .filter(({ text }) => text.trim())
+ .map(({ offset, text }) => ({
+ kind: "message",
+ sourceMessageId: message.id,
+ message: {
+ id: `${message.id}:commentary:${offset}`, role: "assistant", content: text,
+ createdAt: message.createdAt, status: message.status,
+ },
+ }));
return {
progress,
reply: {
kind: "message",
- message: { ...message, content: replyText + content.slice(replyStart), providerReplay: undefined },
+ message: { ...message, content: split.answer, providerReplay: undefined },
},
};
}
diff --git a/apps/desktop/test/live-session-commentary.test.mjs b/apps/desktop/test/live-session-commentary.test.mjs
new file mode 100644
index 000000000..6afeaf989
--- /dev/null
+++ b/apps/desktop/test/live-session-commentary.test.mjs
@@ -0,0 +1,47 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { subscribeLiveSessionEvents } = await import("../electron/main/live-voice/live-session-events.ts");
+
+const signature = (phase) => JSON.stringify({ v: 1, id: `msg_${phase}`, phase });
+
+function nativeTurn(message) {
+ let listener;
+ const events = [];
+ const stop = subscribeLiveSessionEvents({
+ sessionId: "native-pi:s1",
+ source: "pi-native",
+ sidecar: { onNotification: (next) => { listener = next; return () => {}; } },
+ remoteHosts: null,
+ isInterrupted: () => false,
+ onEvent: (event) => events.push(event),
+ });
+ assert.ok(stop);
+ const send = (event) => listener("native.agent.event", { sessionId: "native-pi:s1", turnId: "t1", event });
+ send({ type: "message_end", message });
+ send({ type: "agent_end", messages: [] });
+ return events;
+}
+
+// Issue #2461: a live session reports the turn's answer, never the
+// Responses progress commentary stored ahead of it.
+test("a live session result omits Responses commentary", () => {
+ const events = nativeTurn({
+ id: "a1", role: "assistant", createdAt: "2026-11-20T00:00:00Z",
+ content: "正在核对。答案是 B。",
+ providerReplay: { version: 1, blocks: [
+ { type: "text", length: 5, signature: signature("commentary") },
+ { type: "text", length: 6, signature: signature("final_answer") },
+ ] },
+ });
+ assert.equal(events.find((event) => event.kind === "terminal")?.resultText, "答案是 B。");
+});
+
+test("a live session result keeps unmarked text as is", () => {
+ const events = nativeTurn({
+ id: "a1", role: "assistant", createdAt: "2026-11-20T00:00:00Z", content: "正在核对。答案是 B。",
+ });
+ assert.equal(events.find((event) => event.kind === "terminal")?.resultText, "正在核对。答案是 B。");
+});
diff --git a/packages/shared/src/responses-message-phase.test.ts b/packages/shared/src/responses-message-phase.test.ts
new file mode 100644
index 000000000..098cb0131
--- /dev/null
+++ b/packages/shared/src/responses-message-phase.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import { responsesAnswerText, splitResponsesCommentary } from "./responses-message-phase.js";
+import type { AssistantProviderReplay } from "./types/messages.js";
+
+const signature = (phase: string) => JSON.stringify({ v: 1, id: `msg_${phase}`, phase });
+const replay = (...blocks: AssistantProviderReplay["blocks"]): AssistantProviderReplay => ({ version: 1, blocks });
+
+describe("splitResponsesCommentary", () => {
+ it("removes every marked commentary range and keeps the answer", () => {
+ const content = "Checking.Still checking.Answer B.";
+ const split = splitResponsesCommentary(content, replay(
+ { type: "text", length: 9, signature: signature("commentary") },
+ { type: "thinking", length: 40 },
+ { type: "text", length: 15, signature: signature("commentary") },
+ { type: "text", length: 9, signature: signature("final_answer") },
+ ));
+ expect(split).toEqual({
+ commentary: [{ offset: 0, text: "Checking." }, { offset: 9, text: "Still checking." }],
+ answer: "Answer B.",
+ });
+ expect(responsesAnswerText(content, replay(
+ { type: "text", length: 24, signature: signature("commentary") },
+ { type: "text", length: 9 },
+ ))).toBe("Answer B.");
+ });
+
+ it("leaves unmarked, opaque, or partially described content untouched", () => {
+ const content = "Checking. Answer B.";
+ expect(splitResponsesCommentary(content, undefined)).toBeUndefined();
+ expect(splitResponsesCommentary(content, replay({ type: "text", length: 19, signature: "opaque" }))).toBeUndefined();
+ // An abbreviated row no longer matches its replay lengths.
+ expect(splitResponsesCommentary(content, replay(
+ { type: "text", length: 9, signature: signature("commentary") },
+ { type: "text", length: 4 },
+ ))).toBeUndefined();
+ expect(responsesAnswerText(content, undefined)).toBe(content);
+ });
+
+ it("reports a commentary-only message as an empty answer", () => {
+ expect(responsesAnswerText("Checking.", replay(
+ { type: "text", length: 9, signature: signature("commentary") },
+ ))).toBe("");
+ });
+});
diff --git a/packages/shared/src/responses-message-phase.ts b/packages/shared/src/responses-message-phase.ts
index 3aa1f8670..09ac20903 100644
--- a/packages/shared/src/responses-message-phase.ts
+++ b/packages/shared/src/responses-message-phase.ts
@@ -1,3 +1,5 @@
+import type { AssistantProviderReplay } from "./types/messages.js";
+
/** Responses adapters encode the item ID and optional phase in textSignature. */
export function responsesTextPhase(signature: unknown): "commentary" | "final_answer" | undefined {
if (typeof signature !== "string" || !signature.startsWith("{")) return undefined;
@@ -13,3 +15,52 @@ export function responsesTextPhase(signature: unknown): "commentary" | "final_an
export function isResponsesCommentary(signature: unknown): boolean {
return responsesTextPhase(signature) === "commentary";
}
+
+/** Stored assistant text split by its explicitly marked Responses phases. */
+export type ResponsesCommentarySplit = {
+ /** Progress commentary in order, with its UTF-16 offset in the content. */
+ commentary: { offset: number; text: string }[];
+ /** The content with every commentary range removed. */
+ answer: string;
+};
+
+/**
+ * Split stored assistant content into commentary and answer using the replay
+ * block lengths. Returns `undefined` unless the replay accounts for the whole
+ * content and marks at least one non-empty commentary range, so unmarked or
+ * abbreviated rows keep their text untouched (no wording heuristics).
+ */
+export function splitResponsesCommentary(
+ content: unknown, replay: AssistantProviderReplay | undefined,
+): ResponsesCommentarySplit | undefined {
+ if (typeof content !== "string" || !replay || replay.version !== 1 || !Array.isArray(replay.blocks)) return undefined;
+ const commentary: ResponsesCommentarySplit["commentary"] = [];
+ let offset = 0;
+ let answerStart = 0;
+ let answer = "";
+ for (const block of replay.blocks) {
+ if (
+ !block || (block.type !== "text" && block.type !== "thinking") ||
+ !Number.isSafeInteger(block.length) || block.length < 0 ||
+ (block.signature !== undefined && typeof block.signature !== "string")
+ ) return undefined;
+ // Thinking has its own string. Every text block, signed or not, consumes
+ // exactly its UTF-16 length in the stored content.
+ if (block.type === "thinking") continue;
+ const end = offset + block.length;
+ if (end > content.length) return undefined;
+ if (end > offset && isResponsesCommentary(block.signature)) {
+ answer += content.slice(answerStart, offset);
+ answerStart = end;
+ commentary.push({ offset, text: content.slice(offset, end) });
+ }
+ offset = end;
+ }
+ if (offset !== content.length || answerStart === 0) return undefined;
+ return { commentary, answer: answer + content.slice(answerStart) };
+}
+
+/** The answer part of stored assistant content; unmarked content is returned as is. */
+export function responsesAnswerText(content: string, replay: AssistantProviderReplay | undefined): string {
+ return splitResponsesCommentary(content, replay)?.answer ?? content;
+}