Skip to content

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

fix(responses): keep commentary out of assistant answers

杨城峦309b71f6bdb4
diff --cc apps/desktop/src/lib/assistant-commentary.ts
index 6c7bee3ef,000000000..a99358227
mode 100644,000000..100644
--- a/apps/desktop/src/lib/assistant-commentary.ts
+++ b/apps/desktop/src/lib/assistant-commentary.ts
@@@ -1,67 -1,0 +1,63 @@@
- import { isResponsesCommentary, type AssistantCommentaryRange, type UiMessage } from "@pi-desktop/shared";
++import { isResponsesCommentary, type AssistantProviderReplay, type UiMessage } from "@pi-desktop/shared";
++import type { AssistantTurnPart } from "./assistant-turns";
+
- type AssistantTextProjection = {
- reply: UiMessage;
- progress: UiMessage[];
- };
++type MessagePart = Extract<AssistantTurnPart, { kind: "message" }>;
++type CommentaryProjection = { progress: MessagePart[]; reply: MessagePart };
+
- const projections = new WeakMap<UiMessage, AssistantTextProjection | undefined>();
++const projections = new WeakMap<UiMessage, CommentaryProjection | undefined>();
+
- function savedCommentaryRanges(message: UiMessage, source: "layout" | "replay"): AssistantCommentaryRange[] | undefined {
- const replay = message.providerReplay;
- const blocks = source === "layout" ? message.responseLayout : replay?.version === 1 ? replay.blocks : undefined;
- if (!Array.isArray(blocks)) return undefined;
- const ranges: AssistantCommentaryRange[] = [];
++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;
- for (const block of blocks) {
- if (!block || typeof block !== "object") return undefined;
- if (block.type === "thinking" || (source === "layout" && block.type === "search")) continue;
- if (block.type !== "text" && !(source === "layout" && block.type === "commentary")) return undefined;
- if (!Number.isSafeInteger(block.length) || block.length < 0) return undefined;
++ 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 > message.content.length) return undefined;
- const marked = source === "layout" ? block.type === "commentary" : isResponsesCommentary(block.signature);
- if (end > offset && marked) ranges.push({ start: offset, end });
- offset = end;
- }
- // The host may return abbreviated content. Do not apply offsets to text
- // other than the full string these lengths describe, even if thinking alone was clipped.
- return offset === message.content.length ? ranges : undefined;
- }
-
- function splitAssistantText(message: UiMessage): AssistantTextProjection | undefined {
- const ranges = message.commentaryRanges ?? savedCommentaryRanges(message, "replay") ?? savedCommentaryRanges(message, "layout");
- if (!Array.isArray(ranges) || !ranges.length) return undefined;
- const progress: UiMessage[] = [];
- let offset = 0;
- let reply = "";
- for (const range of ranges) {
- if (!range) return undefined;
- const { start, end } = range;
- if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||
- start < offset || end <= start || end > message.content.length) return undefined;
- const content = message.content.slice(start, end);
- if (content.trim()) {
- progress.push({
- id: `${message.id}:commentary:${start}`,
- role: "assistant",
- content,
- createdAt: message.createdAt,
- status: message.status,
- });
++ 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,
++ },
++ });
++ }
+ }
- reply += message.content.slice(offset, start);
+ 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;
+ return {
- reply: { ...message, content: reply + message.content.slice(offset) },
+ progress,
++ reply: {
++ kind: "message",
++ message: { ...message, content: replyText + content.slice(replyStart), providerReplay: undefined },
++ },
+ };
+}
+
- /** Separate the display text without changing the stored row or replay data. */
- export function projectAssistantCommentary(message: UiMessage): AssistantTextProjection | undefined {
- if (!message.commentaryRanges && !message.providerReplay && !message.responseLayout) return undefined;
- if (!projections.has(message)) projections.set(message, splitAssistantText(message));
++/** Display parts belong to an immutable renderer snapshot, not the saved message. */
++export function projectAssistantCommentary(message: UiMessage): CommentaryProjection | undefined {
++ if (message.role !== "assistant" || !message.providerReplay) return undefined;
++ if (!projections.has(message)) projections.set(message, splitCommentary(message, message.providerReplay));
+ return projections.get(message);
+}
diff --cc apps/desktop/src/lib/assistant-turns.ts
index 33e4960e9,96d5e7816..ec8181d2f
--- a/apps/desktop/src/lib/assistant-turns.ts
+++ b/apps/desktop/src/lib/assistant-turns.ts
@@@ -570,9 -570,12 +570,7 @@@ export function assistantTurnResponseOu
);
}
--export function assistantTurnContent(entry: AssistantTurnEntry): string {
- return getAssistantTurnContent(entry);
- return assistantTurnMessages(entry)
- .map((message) => (message.content || "").trim())
- .filter(Boolean)
- .join("\n\n");
--}
++export { getAssistantTurnContent as assistantTurnContent } from "./transcript-summary";
export function assistantTurnUsage(
entry: AssistantTurnEntry,
diff --cc apps/desktop/src/lib/transcript-summary.ts
index 479635a2a,219e578f8..8a573d60d
--- a/apps/desktop/src/lib/transcript-summary.ts
+++ b/apps/desktop/src/lib/transcript-summary.ts
@@@ -1,7 -1,5 +1,6 @@@
import type { MessageUsage, UiMessage } from "@pi-desktop/shared";
import type { AssistantActivityItem, AssistantTurnEntry, AssistantTurnPart } from "./assistant-turns";
+import { projectAssistantCommentary } from "./assistant-commentary";
- import { orderedActivityParts, projectResponseLayout } from "./assistant-response-layout";
const contentFacts = new WeakMap<UiMessage, { trimmedContent: string; hasContent: boolean }>();
@@@ -69,21 -66,10 +67,20 @@@ export function getAssistantTurnSummary
}
const message = part.message;
result.messages.push(message);
- const projected = projectResponseLayout(message) ?? projectAssistantCommentary(message);
- if (projected && "steps" in projected) {
- // With no activity slot (e.g. just commentary + final), the text part owns the progress rows.
- if (projected.steps.every(step => step.kind === "message")) result.process.push(...projected.steps);
- } else if (projected) {
- for (const progress of projected.progress) {
- result.process.push({ kind: "message", message: progress, sourceMessageId: message.id });
- }
- if (part === answer || message.error) result.responses.push(part);
- else result.process.push(part);
- if (messageContentFacts(message).hasContent) {
- result.actionMessage = message;
++ const projection = projectAssistantCommentary(message);
++ if (projection) {
++ for (const progress of projection.progress) result.process.push(progress);
+ }
- const reply = projected ? { ...part, message: projected.reply } : part;
++ const reply = projection?.reply ?? part;
+ const hasReply = messageContentFacts(reply.message).hasContent;
- if ((part === last && hasReply) || message.error) result.responses.push(reply);
- else if (hasReply || !projected) result.process.push(reply);
++ // Only the marked prose moves. A notice/error still belongs to its row,
++ // and usage and timing below count the source message, not display parts.
++ if (!projection || hasReply || message.error || message.outputTruncated) {
++ if (part === answer || message.error) result.responses.push(reply);
++ else result.process.push(reply);
++ }
+ if (hasReply) {
- result.actionMessage = message;
++ result.actionMessage = reply.message;
result.hasContent = true;
}
if (message.modelId || message.usage || message.responseDurationMs || message.responseOutputTokens) {
@@@ -119,7 -105,7 +116,7 @@@
/** Do not retain duplicated reply text in the session-wide projection cache. */
export function getAssistantTurnContent(entry: AssistantTurnEntry): string {
return getAssistantTurnSummary(entry).messages
- .map((message) => messageContentFacts((projectResponseLayout(message) ?? projectAssistantCommentary(message))?.reply ?? message).trimmedContent)
- .map((message) => messageContentFacts(message).trimmedContent)
++ .map((message) => messageContentFacts(projectAssistantCommentary(message)?.reply.message ?? message).trimmedContent)
.filter(Boolean)
.join("\n\n");
}
diff --cc apps/desktop/src/lib/turn-process.ts
index 34710bc45,d589c7f36..a9f47d23d
--- a/apps/desktop/src/lib/turn-process.ts
+++ b/apps/desktop/src/lib/turn-process.ts
@@@ -31,9 -31,9 +32,9 @@@ export function processContainsMessage
messageId: string,
): boolean {
return parts.some((part) => {
- if (part.kind === "message") return part.message.id === messageId;
+ if (part.kind === "message") return part.message.id === messageId || part.sourceMessageId === messageId;
return part.items.some((item) => {
- if (item.message.id === messageId || (item.kind === "thinking" && item.sourceMessageId === messageId)) return true;
+ if (item.message.id === messageId) return true;
return (
item.kind === "tool" &&
Boolean(item.delegate?.items.some((row) => row.message.id === messageId))
@@@ -298,8 -298,25 +299,9 @@@ export function liveHistoryTurnId
return undefined;
}
-/**
- * Only a trailing assistant text can be the answer: text followed by tools is
- * progress. The stream carries no final-answer marker, so a live trailing text
- * remains visible until a later activity establishes that it was intermediate.
- * Errors remain outside the disclosure even when more activity follows them.
- */
++/** Share the renderer's answer/process partition, including signed progress. */
export function projectTurnProcess(entry: AssistantTurnEntry) {
- const last = entry.parts.at(-1);
- const answer =
- last?.kind === "message" && last.message.content.trim() ? last : undefined;
- const process: AssistantTurnPart[] = [];
- const responses: Extract<AssistantTurnPart, { kind: "message" }>[] = [];
- for (const part of entry.parts) {
- if (part.kind === "message" && (part === answer || part.message.error)) {
- responses.push(part);
- } else {
- process.push(part);
- }
- }
+ const { process, responses } = getAssistantTurnSummary(entry);
return { process, responses };
}
diff --cc apps/desktop/test/transcript-summary.test.mjs
index 8223de468,4066a85ea..646f82d2d
--- a/apps/desktop/test/transcript-summary.test.mjs
+++ b/apps/desktop/test/transcript-summary.test.mjs
@@@ -6,9 -6,9 +6,10 @@@ const
assistantTurnContent, assistantTurnMessages, assistantTurnUsage,
assistantTurnResponseDuration, assistantTurnResponseOutputTokens,
assistantTurnResponseOutputIsEstimated, assistantTurnTools,
++ buildTranscriptEntries,
} = await import("../src/lib/assistant-turns.ts");
const { getAssistantTurnSummary, getAssistantTurnContent, messageContentFacts, reuseReferences } = await import("../src/lib/transcript-summary.ts");
--const { projectTurnProcess } = await import("../src/lib/turn-process.ts");
++const { processContainsMessage, projectTurnProcess } = await import("../src/lib/turn-process.ts");
const { activitySummary, visibleActivityItems } = await import("../src/lib/activity-summary.ts");
const { cachedActivitySummary, cachedVisibleActivityItems, cachedVisibleProcessSteps, activityTimingInputs } = await import("../src/lib/transcript-activity-summary.ts");
const { collectDelegationStatuses, collectDelegationTimings, delegationTimingBounds } = await import("../src/lib/subagent-topology.ts");
@@@ -19,55 -19,6 +20,90 @@@ const message = (id, content, extra = {
});
const entry = (messages) => ({ kind: "assistant-turn", id: "turn", parts: messages.map((message) => ({ kind: "message", message })) });
- test("provider commentary in a saved assistant message is process text, not reply text", () => {
- const commentary = ["Looking up the docs 🔍.", "Checking the routing details."];
- const answer = "Here is the answer.";
- const row = message("reply", [...commentary, answer].join(""), {
- providerReplay: { version: 1, blocks: [...commentary, answer].map((text, index) => ({
- type: "text",
- length: text.length,
- signature: JSON.stringify({ v: 1, id: `msg_${index}`, phase: index < 2 ? "commentary" : "final_answer" }),
- })) },
++const commentarySignature = JSON.stringify({ v: 1, id: "msg_progress", phase: "commentary" });
++const textBlock = (text, signature) => ({ type: "text", length: text.length, signature });
++
++test("Responses commentary alone is progress, not thinking, an answer or an action target", () => {
++ const content = "Checking the files 🔍.";
++ const providerReplay = { version: 1, blocks: [textBlock(content, commentarySignature)] };
++ for (const extra of [{ status: "streaming" }, { status: "complete" },
++ { status: "error", error: { code: "INTERNAL", message: "Offline" } },
++ { status: "complete", outputTruncated: true }]) {
++ const row = message("reply", content, { providerReplay, ...extra });
++ const [turn] = buildTranscriptEntries([row]).entries;
++ const summary = getAssistantTurnSummary(turn);
++ assert.deepEqual(summary.process.map((part) => [part.kind, part.message.content]), [["message", content]]);
++ assert.ok(processContainsMessage(summary.process, row.id));
++ assert.equal(cachedVisibleProcessSteps(summary.process, true, row.status === "streaming"), 1);
++ assert.deepEqual(summary.responses.map(({ message }) => [message.content, message.error, message.outputTruncated]),
++ row.error || row.outputTruncated ? [["", row.error, row.outputTruncated]] : []);
++ assert.equal(summary.hasContent, false);
++ assert.equal(summary.actionMessage, undefined);
++ assert.equal(getAssistantTurnContent(turn), "");
++ assert.equal(assistantTurnContent(turn), "");
++ }
++});
++
++test("signed Responses blocks do not enter the raw reply or duplicate its metrics", () => {
++ const intro = message("intro", "Unmarked earlier text.");
++ const progress = "Looking up references.";
++ const second = "Checking the result.";
++ const raw = `**A 🔍${progress} and ${second}B**`;
++ const reply = "**A 🔍 and B**";
++ const row = message("reply", raw, {
++ status: "complete", thinking: "Why", responseDurationMs: 17,
++ usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 },
++ providerReplay: { version: 1, blocks: [
++ textBlock("**A 🔍"), textBlock(progress, commentarySignature),
++ { type: "thinking", length: 3, signature: commentarySignature },
++ textBlock(" and ", "opaque-provider-signature"), textBlock(second, commentarySignature),
++ textBlock("B**", JSON.stringify({ v: 1, id: "msg_final", phase: "final_answer" })),
++ ] },
+ });
- const turn = entry([row]);
++ const [turn] = buildTranscriptEntries([intro, row]).entries;
++ const { process, responses } = projectTurnProcess(turn);
++ assert.deepEqual(process.filter((part) => part.kind === "message").map((part) => part.message.content), [intro.content, progress, second]);
++ assert.deepEqual(responses.map((part) => part.message.content), [reply]);
+ const summary = getAssistantTurnSummary(turn);
- assert.deepEqual(summary.responses.map((part) => part.message.content), [answer]);
- assert.deepEqual(summary.process.map((part) => part.message.content), commentary);
- assert.equal(getAssistantTurnContent(turn), answer);
++ assert.deepEqual(summary.activityItems.map((item) => item.kind), ["thinking"]);
+ assert.equal(summary.actionMessage.id, row.id);
- assert.equal(row.content, [...commentary, answer].join(""));
++ assert.equal(summary.actionMessage.content, reply);
++ assert.deepEqual(summary.usage, row.usage);
++ assert.equal(summary.responseDurationMs, 17);
++ assert.equal(summary.responseOutputTokens, 2);
++ assert.equal(getAssistantTurnContent(turn), `${intro.content}\n\n${reply}`);
++ assert.equal(assistantTurnContent(turn), `${intro.content}\n\n${reply}`);
++ assert.equal(row.content, raw);
+});
+
- test("unusable commentary offsets leave the full text visible", () => {
- const content = "I will check. This still belongs to the answer.";
- const fields = [
- {},
- { commentaryRanges: [{ start: 0, end: content.length + 1 }] },
- { providerReplay: { version: 1, blocks: [{
- type: "text", length: content.length - 1,
- signature: JSON.stringify({ v: 1, id: "msg_short", phase: "commentary" }),
- }] } },
++test("unknown signatures and unusable Responses replay offsets leave the original row intact", () => {
++ const content = "Checking. Answer.";
++ const marked = textBlock("Checking.", commentarySignature);
++ const rest = textBlock(" Answer.");
++ const invalidBlocks = [
++ null, [marked], [marked, { ...rest, length: rest.length + 1 }],
++ [marked, null, rest], [marked, { type: "unknown", length: 0 }, rest],
++ [marked, { ...rest, length: -1 }], [marked, { ...rest, length: 1.5 }],
++ [marked, { ...rest, length: String(rest.length) }],
++ [marked, { type: "thinking" }, rest], [marked, { ...rest, signature: 42 }],
+ ];
- for (const extra of fields) {
- const turn = entry([message("reply", content, extra)]);
++ const replays = [
++ undefined, { version: 2, blocks: [marked, rest] },
++ ...invalidBlocks.map((blocks) => ({ version: 1, blocks })),
++ ...[undefined, "msg_legacy", "{", '{"v":2,"id":"m","phase":"commentary"}', '{"v":1,"phase":"commentary"}']
++ .map((signature) => ({ version: 1, blocks: [textBlock(content, signature)] })),
++ ];
++ for (const providerReplay of replays) {
++ const row = message("reply", content, { providerReplay });
++ const turn = entry([row]);
++ const summary = getAssistantTurnSummary(turn);
++ assert.deepEqual(summary.process, []);
++ assert.equal(summary.responses[0].message, row);
++ assert.equal(summary.actionMessage, row);
+ assert.equal(getAssistantTurnContent(turn), content);
- assert.equal(getAssistantTurnSummary(turn).responses[0].message.content, content);
+ }
+});
+
- test("commentary without a reply does not swallow an assistant error", () => {
- const content = "Checking.";
- const turn = entry([message("partial", content, {
- commentaryRanges: [{ start: 0, end: content.length }],
- error: { code: "INTERNAL", message: "Offline" },
- })]);
- const summary = getAssistantTurnSummary(turn);
- assert.equal(summary.process[0].message.content, content);
- assert.equal(summary.responses[0].message.error.message, "Offline");
- assert.equal(summary.responses[0].message.content, "");
- assert.equal(getAssistantTurnContent(turn), "");
- });
-
test("tail text updates do not read historical assistant content", () => {
let reads = 0;
const old = Array.from({ length: 1024 }, (_, index) => ({
diff --cc docs/spec/03-runtime/02-agent-runtime.md
index 6ea55280d,4ce17e13e..53bf0bd28
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@@ -509,6 -492,6 +492,10 @@@ The complete visible transcript and th
the same session. A durable checkpoint summarizes older model context while
the renderer continues to show every original user, assistant, and tool row.
++Responses text explicitly marked `commentary` is progress, not a subagent
++report, one-shot result, or final answer. Signed transcript rows retain the
++provider's original text for replay. Unmarked text is treated as before.
++
When restoring a checkpoint, tool-call reconstruction respects its
`throughMessageId` boundary. A surviving tool row must not attach its call to
an assistant that the checkpoint removes. Legacy checkpoints can cut through
diff --cc docs/spec/04-ux/08-component-spec.md
index c163343df,429b58c4f..e0c16ccad
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@@ -967,21 -966,6 +966,11 @@@ can reclassify provisional answer text
stored message. Assistant errors and stopped trailing partial answers also stay
outside it. User/system messages and compaction boundaries are unchanged.
- Responses assistant text explicitly marked `commentary` is progress even
- when it is the only text so far or shares a message with `final_answer`.
- It streams inside the process once the provider marks it, remains there on
- history reopen when replay metadata matches the saved text, and is excluded
- from the turn's Copy action. Missing or unusable phase metadata leaves the
- existing trailing-text rule in place. This does not move reasoning, rewrite
- saved text, or change the assistant messages sent back to the provider.
-
- Responses `responseLayout` preserves thinking/commentary/search/text block order
- within one message, live and reopened. Final text stays outside the process;
- Copy excludes thinking, commentary and searches. Independent disclosure choices
- survive deltas and completion, and expanded groups keep block order. Empty starts
- do not manufacture visible content. No-layout messages keep legacy display;
- replay, tool/group and thinking/folding policies are unchanged.
++An explicitly signed Responses `commentary` text is progress from its first
++identified chunk. The answer and its Copy action exclude it; unmarked text
++keeps its normal behavior. Reopened rows use matching provider replay lengths
++and signatures, never a guess based on wording.
+
The disclosure owns every row the turn produced before its answer: ordinary
activity groups and `Bash` run rows alike. A turn therefore renders exactly one
top-level process disclosure, including a Bash-only turn; no run row is a sibling
diff --cc docs/spec/06-delivery/e2e/conversation.md
index c91bd2ec8,9f0d0c203..de6d6bbb6
--- a/docs/spec/06-delivery/e2e/conversation.md
+++ b/docs/spec/06-delivery/e2e/conversation.md
@@@ -1803,6 -1803,6 +1803,9 @@@ this does not claim an installed full-a
tool, and denied tool. 7) Toggle `Show thinking` off and on and inspect the
active-thinking, failure/recovery and completed states. 8) Remount rows within
the retained pane, then reload the renderer and reopen the session.
++ 9) Stream explicitly marked Responses commentary followed by a final answer;
++ check that only the process shows the commentary, then copy the answer before
++ and after reopening the signed transcript row. Neither copy includes progress.
- **Expected**: A turn renders exactly one process disclosure containing every
pre-answer row, the `Bash`/run rows included; the trailing answer, assistant
errors and stopped trailing text stay outside it, as do pending actions. The
diff --cc packages/agent-runtime/src/agent-messages.test.ts
index 3631d9bba,3631d9bba..7e23c23f0
--- a/packages/agent-runtime/src/agent-messages.test.ts
+++ b/packages/agent-runtime/src/agent-messages.test.ts
@@@ -1,5 -1,5 +1,5 @@@
import { describe, expect, it } from "vitest";
--import { toJsonObject, toJsonValue } from "./agent-messages.js";
++import { assistantContent, toJsonObject, toJsonValue } from "./agent-messages.js";
describe("agent message JSON projections", () => {
it("keeps JSON objects and rejects readonly arrays as object maps", () => {
@@@ -9,4 -9,4 +9,17 @@@
expect(toJsonObject(values)).toEqual({});
expect(toJsonValue(values)).toEqual([{ nested: "value" }]);
});
++
++ it("excludes only explicitly signed Responses commentary from answer text", () => {
++ const message = assistantContent([
++ { type: "text", text: "I will check. " },
++ { type: "text", text: "Working…", textSignature: '{"v":1,"id":"msg_c","phase":"commentary"}' },
++ { type: "thinking", thinking: "real reasoning" },
++ { type: "text", text: "A", textSignature: "{invalid" },
++ { type: "text", text: "B", textSignature: '{"phase":"commentary"}' },
++ { type: "text", text: "C", textSignature: '{"v":1,"id":"msg_f","phase":"final_answer"}' },
++ ]);
++ expect(message.text).toBe("I will check. ABC");
++ expect(message.thinking).toBe("real reasoning");
++ });
});
diff --cc packages/agent-runtime/src/agent-messages.ts
index 12a9ebb2f,4d0ba9260..c8c8562ab
--- a/packages/agent-runtime/src/agent-messages.ts
+++ b/packages/agent-runtime/src/agent-messages.ts
@@@ -7,7 -7,7 +7,7 @@@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { JsonObject, JsonValue, Usage } from "@earendil-works/pi-ai";
- import { isResponsesCommentary, type AssistantCommentaryRange, type MessageUsage, type ResponseLayoutBlock, type UiMessage, type UsageProvenance } from "@pi-desktop/shared";
-import type { MessageUsage, UsageProvenance } from "@pi-desktop/shared";
++import { responsesTextPhase, type AssistantProviderReplay, type MessageUsage, type UsageProvenance } from "@pi-desktop/shared";
export function nowIso(): string {
return new Date().toISOString();
@@@ -118,25 -118,15 +118,29 @@@ export function usageToPi(usage: Messag
};
}
++/** Only the transcript needs the signed original; report and recovery callers consume `text`. */
++export type CommentaryTranscript = { text: string; replay: AssistantProviderReplay };
++
++/** Appends to the trailing text block need only a delta. A different partition needs one snapshot. */
++export function sameCommentaryBoundaries(previous?: CommentaryTranscript, next?: CommentaryTranscript): boolean {
++ if (!previous || !next) return previous === next;
++ const before = previous.replay.blocks;
++ const after = next.replay.blocks;
++ return before.length === after.length && before.every((block, i) =>
++ block.signature === after[i].signature && (i === before.length - 1 || block.length === after[i].length));
++}
++
export type AssistantContent = {
text: string;
thinking: string;
hasText: boolean;
hasThinking: boolean;
- commentaryRanges?: AssistantCommentaryRange[];
- responseLayout?: ResponseLayoutBlock[];
++ hasFinalAnswer?: true;
++ transcript?: CommentaryTranscript;
};
- /** An empty event can retain the live bubble. Never attach its old layout to replacement text. */
- export function responseLayoutForBubble(content: AssistantContent, previous: UiMessage, text: string, thinking: string) {
- if ((content.responseLayout || content.hasText || content.hasThinking) && text === content.text && thinking === content.thinking) {
- return content.responseLayout;
- }
- return text === previous.content && thinking === (previous.thinking ?? "") ? previous.responseLayout : undefined;
- }
-
/** Flatten a pi-ai assistant content array into visible text and reasoning. */
- export function assistantContent(content: unknown, api?: string): AssistantContent {
+ export function assistantContent(content: unknown): AssistantContent {
if (typeof content === "string") {
return { text: content, thinking: "", hasText: true, hasThinking: false };
}
@@@ -148,39 -138,27 +152,40 @@@
let thinking = "";
let hasText = false;
let hasThinking = false;
- let commentaryRanges: AssistantCommentaryRange[] | undefined;
- let searchIds: Set<string> | undefined;
- const layout: ResponseLayoutBlock[] | undefined =
- api === "openai-responses" || api === "openai-codex-responses" || api === "azure-openai-responses" ? [] : undefined;
- for (const [index, block] of content.entries()) {
- for (const part of content) {
- if (!part || typeof part !== "object") continue;
- const block = part as {
- type?: string;
- text?: string;
- thinking?: string;
- };
++ let hasFinalAnswer = false;
++ let transcript: CommentaryTranscript | undefined;
++ for (const block of content) {
+ if (!isRecord(block)) continue;
if (block.type === "text" && typeof block.text === "string") {
hasText = true;
- const commentary = isResponsesCommentary(block.textSignature);
- layout?.push({ type: commentary ? "commentary" : "text", length: block.text.length });
- if (block.text && commentary) {
- (commentaryRanges ??= []).push({ start: text.length, end: text.length + block.text.length });
- text += block.text;
++ const phase = responsesTextPhase(block.textSignature);
++ if (phase === "commentary" && !transcript) {
++ transcript = { text, replay: { version: 1, blocks: text ? [{ type: "text", length: text.length }] : [] } };
+ }
- text += block.text;
++ if (transcript) {
++ transcript.text += block.text;
++ transcript.replay.blocks.push({
++ type: "text", length: block.text.length,
++ ...(phase && typeof block.textSignature === "string" ? { signature: block.textSignature } : {}),
++ });
++ }
++ if (phase !== "commentary") text += block.text;
++ if (phase === "final_answer" && block.text.length) hasFinalAnswer = true;
} else if (block.type === "thinking") {
hasThinking = true;
- // Some compatible adapters expose reasoning as `text`.
- const value = typeof block.thinking === "string" ? block.thinking : typeof block.text === "string" ? block.text : "";
- layout?.push({ type: "thinking", length: value.length });
- thinking += value;
- } else if (layout && block.type === "hostedSearch" && block.phase === "web_search_call") {
- const id = typeof block.blockId === "string" && block.blockId ? block.blockId : `anon-${index}`;
- searchIds ??= new Set();
- if (searchIds.has(id)) continue;
- searchIds.add(id);
- layout.push({ type: "search", id });
+ if (typeof block.thinking === "string") {
+ thinking += block.thinking;
+ } else if (typeof block.text === "string") {
+ // Accept OpenAI-compatible adapters that expose thinking as `text`.
+ thinking += block.text;
+ }
}
}
- return { text, thinking, hasText, hasThinking };
+ return {
+ text, thinking, hasText, hasThinking,
- ...(commentaryRanges ? { commentaryRanges } : {}),
- ...(layout?.some(block => block.type !== "text") ? { responseLayout: layout } : {}),
++ ...(hasFinalAnswer ? { hasFinalAnswer: true } : {}),
++ ...(transcript ? { transcript } : {}),
+ };
}
/**
diff --cc packages/agent-runtime/src/one-shot-complete.test.ts
index 000000000,000000000..b47e86279
new file mode 100644
--- /dev/null
+++ b/packages/agent-runtime/src/one-shot-complete.test.ts
@@@ -1,0 -1,0 +1,38 @@@
++import { describe, expect, it } from "vitest";
++import { createFauxCore, fauxAssistantMessage, normalizeContext, type TextContent } from "@earendil-works/pi-ai";
++import { completeOneShot } from "./one-shot-complete.js";
++import type { RuntimeProviderConfig } from "./provider-binding.js";
++
++const provider: RuntimeProviderConfig = {
++ id: "fixture", name: "Fixture", modelId: "fixture-model", apiStyle: "responses",
++ baseUrl: "https://example.invalid/v1", apiKey: "", authKind: "none",
++ supportsReasoning: false, supportedThinkingLevels: ["off"],
++};
++const commentary: TextContent = {
++ type: "text", text: "I have the result.\n",
++ textSignature: JSON.stringify({ v: 1, id: "msg_progress", phase: "commentary" }),
++};
++
++function completeWithText(...content: TextContent[]) {
++ const faux = createFauxCore({ api: "openai-responses", provider: provider.id });
++ faux.setResponses([fauxAssistantMessage(content)]);
++ return completeOneShot(provider, { messages: [{ role: "user", content: "What is 6 × 7?", timestamp: 1 }] }, "off", {
++ stream: (model, context, options) => faux.streamSimple(model, normalizeContext(context), options),
++ });
++}
++
++describe("completeOneShot Responses answers", () => {
++ it("returns the final answer without its preceding commentary", async () => {
++ const result = await completeWithText(commentary, {
++ type: "text", text: "42",
++ textSignature: JSON.stringify({ v: 1, id: "msg_answer", phase: "final_answer" }),
++ });
++ expect(result.text).toBe("42");
++ });
++
++ it("rejects commentary alone as an empty completion", async () => {
++ await expect(completeWithText(commentary)).rejects.toMatchObject({
++ errorCode: "EMPTY_COMPLETION", message: "The model returned no text.",
++ });
++ });
++});
diff --cc packages/agent-runtime/src/runtime.test.ts
index 6743d5d5f,c8388b902..7eb8cec95
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@@ -11,7 -11,7 +11,8 @@@ import
toToolDeclaration,
type AssistantMessage,
} from "@earendil-works/pi-ai";
--import { formatSessionMessage, type SessionMessageOrigin } from "@pi-desktop/shared";
++import { applyMessageUpdate, deltaStreamPayloadFits, formatSessionMessage, type SessionMessageOrigin } from "@pi-desktop/shared";
++import { restoreAssistantProviderReplay } from "./assistant-provider-replay.js";
import { estimateContextTokens as estimateTranscriptTokens } from "@earendil-works/pi-ai/utils/estimate";
import { buildSessionContext } from "./session-context.js";
import { estimateContextTokens as estimateAgentContextTokens, estimateTokens } from "./pi-runtime-estimates.js";
@@@ -20,6 -20,6 +21,7 @@@ import
DesktopAgentRuntime,
PATH_INSTRUCTION_RESOLUTION_TIMEOUT_MS,
isolatedWorkspaceGuidance,
++ isProgressOnlyAssistantTurn,
delegateWorktreeNote,
looksLikePseudoToolCall,
toolResultFromUi,
@@@ -6269,6 -6210,6 +6212,81 @@@ describe("DesktopAgentRuntime tool hist
});
describe("DesktopAgentRuntime assistant thinking events", () => {
++ it.each(["provider", "interrupted"])("counts visible commentary in the %s abort estimate", async (termination) => {
++ const onEvent = vi.fn();
++ const runtime = createRuntime({ onEvent });
++ const internal = runtime as unknown as { handleAgentEvent(event: unknown): Promise<void>; finalizeCurrentAssistant(status: "aborted"): void };
++ const content = [
++ { type: "text", text: "Checking", textSignature: '{"v":1,"id":"c","phase":"commentary"}' },
++ { type: "text", text: "Done" },
++ ];
++ try {
++ await internal.handleAgentEvent({ type: "message_start", message: { role: "assistant", content } });
++ if (termination === "provider") {
++ await internal.handleAgentEvent({ type: "message_end", message: { role: "assistant", content: [], stopReason: "aborted" } });
++ } else internal.finalizeCurrentAssistant("aborted");
++ const { event } = onEvent.mock.calls.at(-1)![0] as AgentEventEnvelope;
++ if (event.type !== "message_end") throw new Error("missing aborted message");
++ expect(event.message).toMatchObject({ status: "aborted", content: "Done", responseOutputTokens: 3 });
++ } finally { await runtime.dispose(); }
++ });
++
++ it("keeps the answer clean when a Responses replay exceeds the existing storage limit", async () => {
++ const onEvent = vi.fn();
++ const runtime = createRuntime({ onEvent });
++ const internal = runtime as unknown as { handleAgentEvent(event: unknown): Promise<void> };
++ try {
++ const content = [
++ { type: "thinking", thinking: "reasoning", thinkingSignature: "x".repeat(65_536) },
++ { type: "text", text: "Checking.", textSignature: '{"v":1,"id":"c","phase":"commentary"}' },
++ { type: "text", text: "Answer." },
++ ];
++ for (const type of ["message_start", "message_end"]) await internal.handleAgentEvent({ type, message: { role: "assistant", content } });
++ const { event } = onEvent.mock.calls.at(-1)![0] as AgentEventEnvelope;
++ if (event.type !== "message_end") throw new Error("missing settled message");
++ expect(event.message.content).toBe("Answer.");
++ expect(event.message.providerReplay).toBeUndefined();
++ } finally { await runtime.dispose(); }
++ });
++
++ it("streams Responses commentary as signed progress without sending replay on every delta", async () => {
++ const onEvent = vi.fn();
++ const runtime = createRuntime({ onEvent });
++ const internal = runtime as unknown as { handleAgentEvent(event: unknown): Promise<void>; streamSink: { flush(): void } };
++ const signed = (text: string, phase: string) => ({ type: "text" as const, text,
++ textSignature: JSON.stringify({ v: 1, id: `msg_${phase}`, phase }) });
++ const send = async (type: string, content: ReturnType<typeof signed>[]) => {
++ await internal.handleAgentEvent({ type, message: { role: "assistant", content } });
++ internal.streamSink.flush();
++ return onEvent.mock.calls.at(-1)![0].event as AgentEventEnvelope["event"];
++ };
++ try {
++ const progress = signed("Checking", "commentary");
++ const full = signed("Checking 🔎", "commentary");
++ const start = await send("message_start", [progress]);
++ if (start.type !== "message_start") throw new Error("missing start");
++ expect(start.message.providerReplay?.blocks[0]).toMatchObject({ length: progress.text.length, signature: progress.textSignature });
++ const delta = await send("message_update", [full]);
++ if (delta.type !== "message_update") throw new Error("missing progress delta");
++ expect(deltaStreamPayloadFits({ event: delta }, 64_000)).toBe(true);
++ expect(delta.message.providerReplay).toBeUndefined();
++ expect(applyMessageUpdate(start.message, delta).providerReplay?.blocks[0].length).toBe(full.text.length);
++ const boundary = await send("message_update", [full, signed("", "final_answer")]);
++ if (boundary.type !== "message_update") throw new Error("missing phase boundary");
++ expect(boundary.message.providerReplay?.blocks).toHaveLength(2);
++ const final = signed("Answer", "final_answer");
++ const answer = await send("message_update", [full, final]);
++ if (answer.type !== "message_update") throw new Error("missing answer delta");
++ expect(answer.deltaText).toBe("Answer");
++ expect(deltaStreamPayloadFits({ event: answer }, 64_000)).toBe(true);
++ const end = await send("message_end", [full, final]);
++ if (end.type !== "message_end") throw new Error("missing settled message");
++ expect(restoreAssistantProviderReplay(end.message.providerReplay, "", end.message.content)).toEqual([full, final]);
++ expect(isProgressOnlyAssistantTurn({ role: "assistant", content: [full] })).toBe(true);
++ expect(isProgressOnlyAssistantTurn({ role: "assistant", content: [full, signed("Next, use option B.", "final_answer")] })).toBe(false);
++ } finally { await runtime.dispose(); }
++ });
++
it("normalizes thinking blocks and emits independent thinking deltas", async () => {
const onEvent = vi.fn();
const runtime = createRuntime({ onEvent });
diff --cc packages/agent-runtime/src/runtime.ts
index 84dd8c065,aae9c51ae..31abc72be
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@@ -151,7 -151,6 +151,8 @@@ import
} from "./assistant-provider-replay.js";
import {
assistantContent,
- responseLayoutForBubble,
++ sameCommentaryBoundaries,
++ type CommentaryTranscript,
isRecord,
nowIso,
timestampMs,
@@@ -1180,9 -1179,9 +1181,10 @@@ function hasProgressForwardIntent(text
export function isProgressOnlyAssistantTurn(message: unknown): boolean {
if (!isRecord(message) || message.role !== "assistant") return false;
if (messageRequestsTools(message)) return false;
-- const content = isRecord(message) ? message.content : undefined;
-- const text = assistantContent(content).text.trim();
-- if (!text || !hasProgressForwardIntent(text)) return false;
++ const content = assistantContent(message.content);
++ const text = content.text.trim();
++ if (!text && content.transcript?.text.trim()) return true;
++ if (content.hasFinalAnswer || !text || !hasProgressForwardIntent(text)) return false;
if (!PROGRESS_TERMINAL_LEAD.test(text)) return true;
// A report can mention a completed step and still announce the next one.
@@@ -1861,6 -1860,6 +1863,7 @@@ export class DesktopAgentRuntime
private planningState: PlanningState;
private pendingPlanId?: string;
private currentAssistant?: UiMessage;
++ private liveCommentary?: CommentaryTranscript;
private pluginTools: PluginToolDef[];
private pluginSkills: PluginSkillDef[];
private trustedExtensionSpecs: TrustedExtensionSpec[];
@@@ -6729,6 -6728,6 +6732,17 @@@ Do not invent objections or turn specul
}
private emit(event: AgentEventEnvelope["event"], turnId?: string, ts = Date.now()) {
++ // Business state is answer-only. Only the transcript transports the original
++ // signed text, so an old or restarted host can replay the same provider input.
++ if (this.liveCommentary &&
++ (event.type === "message_start" || event.type === "message_update" || event.type === "message_end") &&
++ event.message.id === this.currentAssistant?.id) {
++ const replay = event.type === "message_end" ? event.message.providerReplay : this.liveCommentary.replay;
++ // A failed or oversized terminal replay cannot identify raw progress on reload.
++ if (replay?.blocks.length) {
++ event = { ...event, message: { ...event.message, content: this.liveCommentary.text, providerReplay: replay } };
++ }
++ }
this.onEvent({
sessionId: this.sessionId,
turnId: turnId ?? this.turnId,
@@@ -8539,7 -8551,7 +8566,7 @@@
if (event.message.role === "assistant") {
this.clearAgentActivity();
this.streamStartedAt = Date.now();
- const content = assistantContent(event.message.content, event.message.api);
- const content = assistantContent((event.message as any).content);
++ const content = assistantContent(event.message.content);
const retryingAssistant =
this.providerRetryInProgress ||
this.overflowRecoveryInProgress ||
@@@ -8562,6 -8574,6 +8589,7 @@@
: this.progressTurnRerunInProgress || this.overflowRecoveryInProgress
? retryingAssistant?.content ?? ""
: content.text;
++ this.liveCommentary = initialText === content.text ? content.transcript : undefined;
this.currentAssistant = {
id: retryingAssistant?.id ?? randomUUID(),
role: "assistant",
@@@ -8606,25 -8614,16 +8630,18 @@@
}
case "message_update": {
if (this.currentAssistant && event.message.role === "assistant") {
- const content = assistantContent(event.message.content, event.message.api);
- const previousLayout = this.currentAssistant.responseLayout;
- const previousSearch = this.currentAssistant.hostedSearch;
- const hostedSearch = this.snapshotHostedSearch(event.message, previousSearch);
+ this.applyHostedSearch(event.message);
- const content = assistantContent((event.message as any).content);
++ const content = assistantContent(event.message.content);
++ const previousCommentary = this.liveCommentary;
++ if (content.hasText) this.liveCommentary = content.transcript;
const previousText = this.currentAssistant.content;
const previousThinking = this.currentAssistant.thinking ?? "";
const nextText = content.hasText ? content.text : previousText;
const nextThinking = content.hasThinking
? content.thinking
: previousThinking;
- const responseLayout = responseLayoutForBubble(content, this.currentAssistant, nextText, nextThinking);
const textDelta = content.hasText
-- ? cumulativeDelta(previousText, content.text)
++ ? cumulativeDelta(previousCommentary?.text ?? previousText, this.liveCommentary?.text ?? content.text)
: { delta: "", reset: false };
const thinkingDelta = content.hasThinking
? cumulativeDelta(previousThinking, content.thinking)
@@@ -8642,7 -8638,7 +8656,9 @@@
: {}),
status: "streaming",
};
-- if (
++ if (!sameCommentaryBoundaries(previousCommentary, this.liveCommentary) || (this.liveCommentary && textDelta.reset)) {
++ this.emit({ type: "message_update", message: this.currentAssistant });
++ } else if (
textDelta.delta ||
thinkingDelta.delta ||
textDelta.reset ||
@@@ -8675,6 -8669,6 +8689,7 @@@
} });
}
this.currentAssistant = undefined;
++ this.liveCommentary = undefined;
if (steering.toolNames.length) {
this.activateDeferredTools(steering.toolNames);
this.setAgentTools(this.activeTools());
@@@ -8696,7 -8690,7 +8711,9 @@@
}
if (this.currentAssistant && event.message.role === "assistant") {
const assistantId = this.currentAssistant.id;
- const content = assistantContent(event.message.content, event.message.api);
- const content = assistantContent((event.message as any).content);
++ const content = assistantContent(event.message.content);
++ const visibleTranscript = content.hasText ? content.transcript?.text : this.liveCommentary?.text;
++ this.liveCommentary = content.transcript;
// pi-agent-core encodes stream failures in the final message
// (stopReason "error"/"aborted" + errorMessage) and resolves the
// prompt normally, so this is where provider/model errors surface.
@@@ -8810,6 -8798,6 +8821,7 @@@
!failed &&
!aborted &&
responseText.trim().length === 0 &&
++ !content.transcript?.text.trim() &&
!messageRequestsTools(event.message);
// A completion notice needs no acknowledgement, so its own reply may
// stay silent (D446). The exception covers exactly that reply: the
@@@ -8967,7 -8955,7 +8979,7 @@@
const responseOutputTokens =
aborted && (!usage || usage.outputTokens <= 0)
? estimateVisibleResponseOutputTokens({
-- content: nextText,
++ content: visibleTranscript ?? nextText,
thinking: nextThinking,
})
: undefined;
@@@ -9010,13 -8998,13 +9022,14 @@@
providerReplay: failed
? undefined
: providerReplayForBubble(
-- captureAssistantProviderReplay((event.message as any).content),
++ captureAssistantProviderReplay(event.message.content),
nextText === content.text && nextThinking === content.thinking,
),
};
if (!this.currentAssistant.providerReplay) delete this.currentAssistant.providerReplay;
if (!this.currentAssistant.responseModelId) delete this.currentAssistant.responseModelId;
this.emit({ type: "message_end", message: this.currentAssistant });
++ this.liveCommentary = undefined;
this.activeProviderRetryAttempt = 0;
this.streamStartedAt = undefined;
this.currentAssistant = undefined;
@@@ -9230,7 -9218,7 +9243,10 @@@
(responseDurationMs ?? 0);
const responseOutputTokens =
status === "aborted"
-- ? estimateVisibleResponseOutputTokens(this.currentAssistant)
++ ? estimateVisibleResponseOutputTokens({
++ content: this.liveCommentary?.text ?? this.currentAssistant.content,
++ thinking: this.currentAssistant.thinking,
++ })
: undefined;
this.currentAssistant = {
...this.currentAssistant,
@@@ -9250,6 -9238,6 +9266,7 @@@
// burns its retries before giving up shows here as a large providerWaitMs.
this.streamStartedAt = undefined;
this.currentAssistant = undefined;
++ this.liveCommentary = undefined;
}
/** Keep a pre-flight user message in context so a reused runtime and the
@@@ -9325,6 -9313,6 +9342,7 @@@
this.turnEpoch += 1;
this.abortDelegationsFromPreviousTurns();
this.currentAssistant = undefined;
++ this.liveCommentary = undefined;
this.requestStartedAt = Date.now();
// An approved plan runs as a plain Agent turn, never as a mode run turn.
this.modeState.clearTurn();
diff --cc packages/agent-runtime/src/subagent.test.ts
index 92d384110,92d384110..301b005d7
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@@ -4,7 -4,7 +4,9 @@@ import { tmpdir } from "node:os"
import { join } from "node:path";
import { Type } from "typebox";
import type { AgentEventEnvelope, SubagentDefinition } from "@pi-desktop/shared";
--import { createAssistantMessageEventStream, type Message } from "@earendil-works/pi-ai";
++import {
++ createAssistantMessageEventStream, createFauxCore, fauxAssistantMessage, type Message, type TextContent,
++} from "@earendil-works/pi-ai";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
composeSubagentSystemPrompt,
@@@ -399,6 -399,6 +401,36 @@@ describe("SubagentRun event forwarding"
});
});
++describe("SubagentRun Responses reports", () => {
++ const commentary: TextContent = {
++ type: "text", text: "I found the dialog.\n",
++ textSignature: JSON.stringify({ v: 1, id: "msg_progress", phase: "commentary" }),
++ };
++
++ function runWithText(...content: TextContent[]) {
++ const { run } = createRun({ provider: { ...provider, apiStyle: "responses" } });
++ const faux = createFauxCore({ api: "openai-responses", provider: provider.id });
++ faux.setResponses([fauxAssistantMessage(content)]);
++ run.agent.streamFunction = faux.streamSimple;
++ return (run as unknown as SubagentRun).run();
++ }
++
++ it("returns only the final answer in the parent's report", async () => {
++ const report = "PermissionDialog.tsx:17 renders the dialog.";
++ const result = await runWithText(commentary, {
++ type: "text", text: report,
++ textSignature: JSON.stringify({ v: 1, id: "msg_report", phase: "final_answer" }),
++ });
++ expect(result).toMatchObject({ status: "completed", report });
++ });
++
++ it("fails without a report when the only text is commentary", async () => {
++ const result = await runWithText(commentary);
++ expect(result).toMatchObject({ status: "failed", error: { code: "SUBAGENT_NO_REPORT" } });
++ expect(result.report).not.toContain(commentary.text.trim());
++ });
++});
++
describe("SubagentRun reporting", () => {
it("keeps the last non-empty assistant text as the report", () => {
const { run } = createRun();
diff --cc packages/shared/src/index.ts
index 34b63590b,bcd89987a..b13571a25
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@@ -81,6 -80,6 +80,7 @@@ export * from "./tray-sessions.js"
export * from "./window-chrome.js";
export * from "./fast-mode.js";
export * from "./native-web-search.js";
++export * from "./responses-message-phase.js";
export * from "./native-web-search-transport.js";
export * from "./header-value.js";
export * from "./secret-refs.js";
diff --cc packages/shared/src/message-stream.test.ts
index fd25bac43,1c88a3b28..a290f900e
--- a/packages/shared/src/message-stream.test.ts
+++ b/packages/shared/src/message-stream.test.ts
@@@ -160,6 -134,6 +134,17 @@@ describe("mergeMessageUpdates", () =>
expect(merged.resetText).toBe(true);
});
++ it("extends signed progress locally when a pending snapshot absorbs a delta", () => {
++ const original = assistant({ id: "m", content: "A", providerReplay: {
++ version: 1, blocks: [{ type: "text", length: 1, signature: '{"v":1,"id":"m","phase":"commentary"}' }],
++ } });
++ const append = toWireMessageUpdate({ type: "message_update", message: original, deltaText: "🔎" });
++ const { message } = mergeMessageUpdates({ type: "message_update", message: original }, append);
++ expect(message.providerReplay?.blocks[0].length).toBe(message.content.length);
++ expect(original.providerReplay?.blocks[0].length).toBe(1);
++ expect(applyMessageUpdate(message, { ...append, resetText: true, deltaText: "replacement" }).providerReplay).toBeUndefined();
++ });
++
it("applies a later delta onto a pending snapshot replacement", () => {
const snapshot = assistant({ id: "m1", content: "Hello" });
const merged = mergeMessageUpdates(
diff --cc packages/shared/src/message-stream.ts
index 13da2598c,e320e3547..1db4580f6
--- a/packages/shared/src/message-stream.ts
+++ b/packages/shared/src/message-stream.ts
@@@ -161,8 -159,8 +159,20 @@@ export function applyMessageUpdate
else if (event.deltaText) content += event.deltaText;
if (event.resetThinking) thinking = event.deltaThinking ?? "";
else if (event.deltaThinking) thinking += event.deltaThinking;
++ // A streaming Responses snapshot establishes the signed text boundaries once.
++ // An append grows its last block; a replacement must not reuse stale offsets.
++ let replay = seed.providerReplay;
++ if (replay?.version === 1 && Array.isArray(replay.blocks) && seed.status === "streaming") {
++ const tail = replay.blocks.at(-1);
++ if (event.resetText) replay = undefined;
++ else if (tail?.type === "text" && event.deltaText) {
++ const blocks = [...replay.blocks.slice(0, -1), { ...tail, length: tail.length + event.deltaText.length }];
++ replay = { ...replay, blocks };
++ }
++ }
return {
...seed,
++ ...(replay !== seed.providerReplay ? { providerReplay: replay } : {}),
id: event.message.id,
role: event.message.role,
createdAt: event.message.createdAt || seed.createdAt,
diff --cc packages/shared/src/responses-message-phase.ts
index 474e542c0,000000000..3aa1f8670
mode 100644,000000..100644
--- a/packages/shared/src/responses-message-phase.ts
+++ b/packages/shared/src/responses-message-phase.ts
@@@ -1,10 -1,0 +1,15 @@@
+/** Responses adapters encode the item ID and optional phase in textSignature. */
- export function isResponsesCommentary(signature: unknown): boolean {
- if (typeof signature !== "string" || !signature.startsWith("{")) return false;
++export function responsesTextPhase(signature: unknown): "commentary" | "final_answer" | undefined {
++ if (typeof signature !== "string" || !signature.startsWith("{")) return undefined;
+ try {
+ const item = JSON.parse(signature) as { v?: unknown; id?: unknown; phase?: unknown } | null;
- return item?.v === 1 && typeof item.id === "string" && item.phase === "commentary";
++ if (item?.v === 1 && typeof item.id === "string" && item.id &&
++ (item.phase === "commentary" || item.phase === "final_answer")) return item.phase;
+ } catch {
- return false;
++ // Other providers use opaque signatures, including non-JSON strings.
+ }
+}
++
++export function isResponsesCommentary(signature: unknown): boolean {
++ return responsesTextPhase(signature) === "commentary";
++}
diff --cc patches/@[email protected]
index 84e112beb,7fe190c98..f4885ce01
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@@ -457,7 -457,7 +457,7 @@@ index c1b6038c2220633a8caf710288a8f6e63
openRouterRouting: model.compat.openRouterRouting ?? {},
vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-shared.js
- index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..17e350684857d863e8dfc51ff21944d8a92c5475 100644
-index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..14bd2b28a9988025bc8bb397e340f8662e255e5a 100644
++index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..b8c0fa9a522fa67a9ed98abb8b97501b8aa27e08 100644
--- a/dist/api/openai-responses-shared.js
+++ b/dist/api/openai-responses-shared.js
@@ -1,3 +1,4 @@
@@@ -487,20 -487,18 +487,31 @@@
else if (block.type === "toolCall") {
const toolCall = block;
const [callId, itemIdRaw] = toolCall.id.split("|");
- @@ -408,7 +417,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ @@ -362,9 +371,7 @@ export function convertResponsesTools(tools, options) {
+ parameters: getJsonSchemaToolParameters(tool, strict === true),
+ ...(options?.toolSearchResult ? { defer_loading: true } : {}),
+ };
+ - if (supportsStrictMode) {
+ - functionTool.strict = strict;
+ - }
+ + functionTool.strict = supportsStrictMode ? strict : false;
+ return functionTool;
+ });
+ }
-@@ -458,6 +465,28 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -408,7 +415,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ }
+ if (item.type === "message") {
+ applyMessagePhaseStopReason(item);
+- const block = { type: "text", text: "" };
++ const block = {
++ type: "text",
++ text: "",
++ ...(item.phase ? { textSignature: encodeTextSignatureV1(item.id, item.phase) } : {}),
++ };
+ output.content.push(block);
+ const slot = { type: "text", block, contentIndex: output.content.length - 1 };
+ outputSlots.set(outputIndex, slot);
- @@ -458,6 +471,28 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -458,6 +469,28 @@ export async function processResponsesStream(openaiStream, output, stream, model
stream.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
return slot;
}
@@@ -529,7 -527,7 +540,7 @@@
return undefined;
};
const getOrCreateSlot = (outputIndex, item) => {
- @@ -539,11 +574,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
-@@ -539,11 +568,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -539,11 +572,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "thinking");
if (!slot)
continue;
@@@ -543,7 -541,7 +554,7 @@@
partial: output,
});
}
- @@ -563,11 +598,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
-@@ -563,11 +592,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -563,11 +596,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "thinking");
if (!slot)
continue;
@@@ -557,7 -555,7 +568,7 @@@
partial: output,
});
}
- @@ -575,23 +610,44 @@ export async function processResponsesStream(openaiStream, output, stream, model
-@@ -575,23 +604,44 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -575,23 +608,44 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "text");
if (!slot)
continue;
@@@ -606,7 -604,7 +617,7 @@@
partial: output,
});
}
- @@ -599,8 +655,8 @@ export async function processResponsesStream(openaiStream, output, stream, model
-@@ -599,8 +649,8 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -599,8 +653,8 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "toolCall");
if (slot?.input.kind !== "json")
continue;
@@@ -617,17 -615,7 +628,17 @@@
}
else if (event.type === "response.function_call_arguments.done") {
const slot = getSlot(event.output_index, "toolCall");
- @@ -643,7 +699,8 @@ export async function processResponsesStream(openaiStream, output, stream, model
-@@ -680,9 +730,25 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -643,7 +697,8 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ }
+ else if (item.type === "message" && slot?.type === "text") {
+ slot.block.text = item.content?.map((c) => (c.type === "output_text" ? c.text : c.refusal)).join("") || "";
+- slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);
++ const phase = item.phase ?? parseTextSignature(slot.block.textSignature)?.phase;
++ slot.block.textSignature = encodeTextSignatureV1(item.id, phase);
+ stream.push({
+ type: "text_end",
+ contentIndex: slot.contentIndex,
- @@ -680,9 +737,25 @@ export async function processResponsesStream(openaiStream, output, stream, model
++@@ -680,9 +735,25 @@ export async function processResponsesStream(openaiStream, output, stream, model
});
outputSlots.delete(event.output_index);
}
diff --cc pnpm-lock.yaml
index 9510a2a7e,6ce47146b..4a90769d1
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@@ -206,7 -206,7 +206,7 @@@ overrides
patchedDependencies:
'@earendil-works/[email protected]': f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da
- '@earendil-works/[email protected]': 66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96
- '@earendil-works/[email protected]': 39770d873534adf2d3dfc080f411c35c8049d23e5309e78b1aa691603ab31b82
++ '@earendil-works/[email protected]': 13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc
'@earendil-works/[email protected]': b1ad25365da34b5862e5263254f499e8c28a8344d66609110df5d2061c519bf9
importers:
@@@ -234,7 -234,7 +234,7 @@@
devDependencies:
'@earendil-works/pi-ai':
specifier: 1.5.2
- version: 1.5.2(patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- version: 1.5.2(patch_hash=39770d873534adf2d3dfc080f411c35c8049d23e5309e78b1aa691603ab31b82)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
++ version: 1.5.2(patch_hash=13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-mcp':
specifier: 1.5.2
version: 1.5.2
@@@ -438,7 -438,7 +438,7 @@@
version: 1.5.2(patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-ai':
specifier: 1.5.2
- version: 1.5.2(patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- version: 1.5.2(patch_hash=39770d873534adf2d3dfc080f411c35c8049d23e5309e78b1aa691603ab31b82)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
++ version: 1.5.2(patch_hash=13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-coding-agent':
specifier: 1.5.2
version: 1.5.2(patch_hash=b1ad25365da34b5862e5263254f499e8c28a8344d66609110df5d2061c519bf9)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
@@@ -5149,7 -5149,7 +5149,7 @@@ snapshots
'@earendil-works/[email protected](patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
dependencies:
- '@earendil-works/pi-ai': 1.5.2(patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- '@earendil-works/pi-ai': 1.5.2(patch_hash=39770d873534adf2d3dfc080f411c35c8049d23e5309e78b1aa691603ab31b82)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
++ '@earendil-works/pi-ai': 1.5.2(patch_hash=13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-schema': 1.5.2
transitivePeerDependencies:
- '@aws-sdk/credential-provider-node'
@@@ -5164,7 -5164,7 +5164,7 @@@
- ws
- zod
- '@earendil-works/[email protected](patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
- '@earendil-works/[email protected](patch_hash=39770d873534adf2d3dfc080f411c35c8049d23e5309e78b1aa691603ab31b82)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
++ '@earendil-works/[email protected](patch_hash=13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
dependencies:
'@anthropic-ai/sdk': 0.129.0([email protected])
'@aws-sdk/client-bedrock-runtime': 3.1127.0
@@@ -5189,7 -5189,7 +5189,7 @@@
- ws
- zod
- '@earendil-works/[email protected](patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
- '@earendil-works/[email protected](patch_hash=39770d873534adf2d3dfc080f411c35c8049d23e5309e78b1aa691603ab31b82)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
++ '@earendil-works/[email protected](patch_hash=13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
dependencies:
'@anthropic-ai/sdk': 0.129.0([email protected])
'@aws-sdk/client-bedrock-runtime': 3.1127.0
@@@ -5221,7 -5221,7 +5221,7 @@@
'@earendil-works/[email protected](patch_hash=b1ad25365da34b5862e5263254f499e8c28a8344d66609110df5d2061c519bf9)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':
dependencies:
'@earendil-works/pi-agent-core': 1.5.2(patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- '@earendil-works/pi-ai': 1.5.2(patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- '@earendil-works/pi-ai': 1.5.2(patch_hash=39770d873534adf2d3dfc080f411c35c8049d23e5309e78b1aa691603ab31b82)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
++ '@earendil-works/pi-ai': 1.5.2(patch_hash=13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-codemode': 1.5.2
'@earendil-works/pi-mcp': 1.5.2
'@earendil-works/pi-tui': 1.5.2
diff --cc scripts/e2e/turn-process.tsx
index 88abbf9df,6c363ebea..4b409ecef
--- a/scripts/e2e/turn-process.tsx
+++ b/scripts/e2e/turn-process.tsx
@@@ -3,13 -3,7 +3,7 @@@ import { flushSync } from "react-dom"
import { createInstance } from "i18next";
import { I18nextProvider } from "react-i18next";
import { en } from "@pi-desktop/i18n";
- import {
- applyMessageUpdate,
- toWireMessageUpdate,
- type AppSettings,
- type HostedSearchRound,
- type UiMessage,
- } from "@pi-desktop/shared";
-import type { AppSettings, UiMessage } from "@pi-desktop/shared";
++import { applyMessageUpdate, type AppSettings, type UiMessage } from "@pi-desktop/shared";
import { AssistantTurn } from "../../apps/desktop/src/features/chat/transcript/AssistantTurn";
import { ShowThinkingRow } from "../../apps/desktop/src/components/settings/ShowThinkingRow";
import { TranscriptDisplayModeRow } from "../../apps/desktop/src/components/settings/TranscriptDisplayModeRow";
@@@ -193,156 -186,6 +186,60 @@@ export async function turnProcessProbe(
const contiguous = [read, grep, bash1, bash2, edit, answer];
try {
- // The same provider message holds both progress and the final answer.
+ setSettings({ smoothStreaming: false, showThinking: false });
+ const progress = "Checking references.";
- const finalText = "Here is the result.";
- const phased = message("phased", "assistant", "", { status: "streaming" });
- const commentaryRanges = [{ start: 0, end: progress.length }];
- const live = applyMessageUpdate(phased, toWireMessageUpdate({
- type: "message_update", deltaText: progress,
- message: { ...phased, content: progress, commentaryRanges },
- }));
- render([live], true, null, "live-phased-response");
- check(firstProcess()?.textContent?.includes(progress) && !row("phased"), "live commentary is only in the process");
- const answered = applyMessageUpdate(live, toWireMessageUpdate({
- type: "message_update", deltaText: finalText,
- message: { ...live, content: progress + finalText },
- }));
- render([answered], true, null, "live-phased-response");
- check(row("phased")?.textContent === finalText && !row("phased")?.closest(".turn-process"), "final text streams outside the process");
-
- const savedPhaseMessage = { ...answered, status: "complete" as const, commentaryRanges: undefined,
- providerReplay: { version: 1 as const, blocks: [{
- type: "text" as const, length: progress.length,
- signature: JSON.stringify({ v: 1, id: "msg_progress", phase: "commentary" }),
- }, { type: "text" as const, length: finalText.length }] },
- };
- render([savedPhaseMessage], false, null, "reopened-phased-response");
- check(processHeaders()[0]?.getAttribute("aria-expanded") === "false" && row("phased")?.textContent === finalText, "reloaded commentary starts folded without polluting the answer");
- click(processHeaders()[0]);
- check(firstProcess()?.textContent?.includes(progress) && row("phased")?.textContent === finalText, "reopening the process reveals the saved commentary only there");
- setSettings();
-
- // Responses slices use canonical UTF-16 text; only clipboard I/O is mocked.
- const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, "clipboard");
- let copied: string | undefined;
- Object.defineProperty(navigator, "clipboard", {
- configurable: true, value: { writeText: async (text: string) => { copied = text; } },
++ const markdown = "**Ready.**";
++ const marked = { type: "text" as const, length: progress.length,
++ signature: JSON.stringify({ v: 1, id: "msg_progress", phase: "commentary" }) };
++ const unmarked = { type: "text" as const, length: markdown.length };
++ const identity = message("phased", "assistant", "", { status: "streaming" });
++ const append = (snapshot: UiMessage, deltaText: string) => applyMessageUpdate(snapshot, {
++ type: "message_update", stream: "delta", message: identity, deltaText,
+ });
- try {
- const thought1 = "First reasoning 🧭.", thought2 = "Second reasoning after the first search.";
- const commentary1 = "Checking the first source 🔎.", commentary2 = "Checking the second source.";
- const answerLead = "Verified answer", finalAnswer = `${answerLead} 🚀.`;
- const searches = ["first", "second"].map((name, index) => ({
- id: `ws-layout-${index}`, query: `${name} layout search`, status: "searching" as const, sources: [],
- } satisfies HostedSearchRound));
- const found = searches.map((round) => ({ ...round, status: "completed" as const,
- sources: [{ url: `https://example.test/${round.id}`, title: `${round.query} source details` }],
- }));
- const firstLayout = [
- { type: "thinking", length: thought1.length }, { type: "commentary", length: commentary1.length },
- { type: "search", id: searches[0].id },
- ] as const;
- const secondThoughtLayout = [...firstLayout, { type: "thinking", length: thought2.length }] as const;
- const processLayout = [...secondThoughtLayout,
- { type: "commentary", length: commentary2.length }, { type: "search", id: searches[1].id },
- ] as const;
- // No client tools: Commands first has the same grouping as Fully folded.
- for (const mode of ["flat", "fully-folded"] as const) {
- setSettings({ transcriptDisplayMode: mode, smoothStreaming: false,
- showThinking: true, autoCollapseThinking: false });
- const key = `responses-layout-${mode}`;
- let current = message(key, "assistant", "", {
- status: "streaming", responseLayout: [{ type: "thinking", length: 0 }],
- });
- const paint = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
- const advance = async (responseLayout: NonNullable<UiMessage["responseLayout"]>,
- deltaText = "", deltaThinking = "", hostedSearch = current.hostedSearch) => {
- current = applyMessageUpdate(current, toWireMessageUpdate({
- type: "message_update", deltaText, deltaThinking,
- message: { ...current, responseLayout, hostedSearch,
- content: current.content + deltaText, thinking: (current.thinking ?? "") + deltaThinking },
- }));
- render([current], true, null, key);
- await paint();
- };
- const headers = (selector: string) => [...container.querySelectorAll<HTMLButtonElement>(selector)];
- const thoughts = () => headers(".thinking > .tool-row-header");
- const searchRows = () => headers(".hosted-search > .tool-row-header");
- const checkChoices = (phase: string) => check(
- thoughts().length === 2 && searchRows().length === 2 &&
- thoughts()[0]?.getAttribute("aria-expanded") === "true" &&
- thoughts()[1]?.getAttribute("aria-expanded") === "false" &&
- searchRows()[0]?.getAttribute("aria-expanded") === "true",
- `${mode}: ${phase} preserves independent thinking/search choices`,
- );
- const checkOrder = (phase: string) => {
- const text = firstProcess()?.innerText ?? "";
- let offset = 0;
- check([thought1, commentary1, searches[0].query, thought2, commentary2, searches[1].query]
- .every((fragment) => {
- const index = text.indexOf(fragment, offset);
- offset = index + fragment.length;
- return index >= 0;
- }), `${mode}: ${phase} preserves Responses block order`);
- };
- const checkAnswer = (text: string) => check(
- row(key)?.textContent === text && !row(key)?.closest(".turn-process") &&
- !firstProcess()?.textContent?.includes(text),
- `${mode}: only the answer renders outside the process under its original message ID`,
- );
- render([current], true, null, key, true);
- check(!container.querySelector(".assistant-turn"), `${mode}: empty thinking start has no turn`);
- await advance([{ type: "thinking", length: thought1.length }, { type: "commentary", length: 0 }], "", thought1);
- check(firstProcess()?.innerText.includes(thought1) && !row(key),
- `${mode}: thinking delta renders before empty commentary start without an answer`);
- await advance(firstLayout, commentary1, "", { status: "searching", rounds: [searches[0]] });
- check(firstProcess()?.innerText.includes(commentary1) && !row(key),
- `${mode}: commentary streams inside the process`);
- click(searchRows()[0] ?? null);
- await advance(secondThoughtLayout, "", thought2, { status: "completed", rounds: [found[0]] });
- await advance(processLayout, commentary2, "", { status: "searching", rounds: [found[0], searches[1]] });
- checkOrder("live");
- check([...container.querySelectorAll(".hosted-search-sources a")].some((link) =>
- visible(link) && link.textContent?.includes(found[0].sources[0].title)),
- `${mode}: opened search sources survive later blocks and group growth`);
- click(thoughts()[1] ?? null);
- await advance([...processLayout, { type: "text", length: 0 }], "", "", { status: "completed", rounds: found });
- check(!row(key), `${mode}: empty final text start does not expose progress as answer`);
- await advance([...processLayout, { type: "text", length: answerLead.length }], answerLead);
- checkAnswer(answerLead);
- await advance([...processLayout, { type: "text", length: finalAnswer.length }], " 🚀.");
- checkChoices("answer deltas");
- checkAnswer(finalAnswer);
- const completed: UiMessage = { ...current, status: "complete", commentaryRanges: undefined };
- for (const [phase, snapshot, renderKey] of [
- ["completed", completed, key], ["reloaded", structuredClone(completed), `${key}-reloaded`],
- ] as const) {
- render([snapshot], false, null, renderKey);
- check(processHeaders().length === 1 && processHeaders()[0]?.getAttribute("aria-expanded") === "false",
- `${mode}: ${phase} process starts folded`);
- checkAnswer(finalAnswer);
- click(processHeaders()[0] ?? null);
- for (const header of headers(".process-activity-group.grouped > .tool-activity-header")) {
- if (header.getAttribute("aria-expanded") === "false") click(header);
- }
- if (phase === "completed") { checkChoices(phase); click(thoughts()[1] ?? null); }
- await paint();
- checkOrder(`${phase} expanded`);
- copied = undefined;
- click(headers(".message-actions button").find((button) =>
- button.getAttribute("aria-label") === i18n.t("chat.copy")) ?? null);
- await Promise.resolve();
- check(copied === finalAnswer, `${mode}: ${phase} Copy excludes reasoning, commentary and searches`);
- }
++ const live = append({ ...identity,
++ providerReplay: { version: 1, blocks: [{ ...marked, length: 0 }] },
++ }, progress);
++ const copyButton = () => container.querySelector<HTMLButtonElement>(`.message-actions button[aria-label="${i18n.t("chat.copy")}"]`);
++ const copyReply = async () => {
++ // Exercise the mounted toolbar button without touching the user's clipboard.
++ const clipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
++ let payload: string | undefined;
++ Object.defineProperty(navigator, "clipboard", { configurable: true,
++ value: { writeText: async (text: string) => { payload = text; } } });
++ try {
++ click(copyButton());
++ await Promise.resolve();
++ return payload;
++ } finally {
++ if (clipboard) Object.defineProperty(navigator, "clipboard", clipboard);
++ else Reflect.deleteProperty(navigator, "clipboard");
+ }
- } finally {
- if (clipboardDescriptor) Object.defineProperty(navigator, "clipboard", clipboardDescriptor);
- else Reflect.deleteProperty(navigator, "clipboard");
++ };
++ render([live], true, null, "phased");
++ check(visible(firstProcess()) && firstProcess()?.querySelector(".message-bubble")?.textContent === progress &&
++ !container.querySelector(".message-col > .message-bubble, .thinking") && !copyButton(),
++ "live commentary is visible only as process prose with thinking hidden");
++ const answered = append({ ...live,
++ providerReplay: { version: 1, blocks: [marked, { ...unmarked, length: 0 }] },
++ }, markdown);
++ render([answered], true, null, "phased");
++ check(row("phased")?.textContent === "Ready." && !row("phased")?.closest(".turn-process"),
++ "the answer streams outside the commentary disclosure");
++ const settled = { ...answered, status: "complete" as const };
++ for (const [key, savedRow] of [["phased", settled], ["reopened", structuredClone(settled)]] as const) {
++ render([savedRow], false, null, key);
++ check(processHeaders()[0]?.getAttribute("aria-expanded") === "false" && row("phased")?.textContent === "Ready.",
++ `${key}: completion folds progress without hiding the answer`);
++ click(processHeaders()[0]);
++ check(firstProcess()?.querySelector(".message-bubble")?.textContent === progress && await copyReply() === markdown,
++ `${key}: opening the process reveals the commentary, but Copy writes only the raw answer`);
+ }
++ render([{ ...settled, providerReplay: { version: 1, blocks: [{ ...marked, signature: "msg_legacy" }, unmarked] } }],
++ false, null, "legacy-unsigned");
++ check(!processHeaders().length && row("phased")?.textContent === `${progress}Ready.` && await copyReply() === settled.content,
++ "legacy saved text without an explicit phase still displays and copies in full");
+ setSettings();
+
// One disclosure per turn: the Bash rows are rows inside the turn's process,
// not siblings of it, so a long turn collapses in one gesture.
render(mixed, true, null, "settling-activity-group");