Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): Separate Responses commentary from replies
杨城峦92376038da8f
diff --git a/apps/desktop/src/lib/assistant-commentary.ts b/apps/desktop/src/lib/assistant-commentary.tsnew file mode 100644index 000000000..17eb6e8bc--- /dev/null+++ b/apps/desktop/src/lib/assistant-commentary.ts@@ -0,0 +1,64 @@+import { isResponsesCommentary, type AssistantCommentaryRange, type UiMessage } from "@pi-desktop/shared";++type AssistantTextProjection = {+ reply: UiMessage;+ progress: UiMessage[];+};++const projections = new WeakMap<UiMessage, AssistantTextProjection | undefined>();++function savedCommentaryRanges(message: UiMessage): AssistantCommentaryRange[] | undefined {+ const replay = message.providerReplay;+ if (replay?.version !== 1 || !Array.isArray(replay.blocks)) return undefined;+ const ranges: AssistantCommentaryRange[] = [];+ let offset = 0;+ for (const block of replay.blocks) {+ if (!block || (block.type !== "text" && block.type !== "thinking")) return undefined;+ if (block.type === "thinking") continue;+ if (!Number.isSafeInteger(block.length) || block.length < 0) return undefined;+ const end = offset + block.length;+ if (end > message.content.length) return undefined;+ if (end > offset && isResponsesCommentary(block.signature)) ranges.push({ start: offset, end });+ offset = end;+ }+ // The host may return abbreviated content. Do not apply offsets to text+ // other than the full string that these replay lengths describe.+ return offset === message.content.length ? ranges : undefined;+}++function splitAssistantText(message: UiMessage): AssistantTextProjection | undefined {+ const ranges = message.commentaryRanges ?? savedCommentaryRanges(message);+ 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,+ });+ }+ reply += message.content.slice(offset, start);+ offset = end;+ }+ return {+ reply: { ...message, content: reply + message.content.slice(offset) },+ progress,+ };+}++/** Separate the display text without changing the stored row or replay data. */+export function projectAssistantCommentary(message: UiMessage): AssistantTextProjection | undefined {+ if (!message.commentaryRanges && !message.providerReplay) return undefined;+ if (!projections.has(message)) projections.set(message, splitAssistantText(message));+ return projections.get(message);+}diff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.tsindex 96d5e7816..ef3ed2fb0 100644--- a/apps/desktop/src/lib/assistant-turns.ts+++ b/apps/desktop/src/lib/assistant-turns.ts@@ -48,7 +48,7 @@ export type SubagentRun = {};export type AssistantTurnPart =- | { kind: "message"; message: UiMessage }+ | { kind: "message"; message: UiMessage; sourceMessageId?: string }| {kind: "activity";items: AssistantActivityItem[];diff --git a/apps/desktop/src/lib/transcript-summary.ts b/apps/desktop/src/lib/transcript-summary.tsindex 219e578f8..3a2b580a2 100644--- a/apps/desktop/src/lib/transcript-summary.ts+++ b/apps/desktop/src/lib/transcript-summary.ts@@ -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";const contentFacts = new WeakMap<UiMessage, { trimmedContent: string; hasContent: boolean }>();@@ -51,7 +52,6 @@ export function getAssistantTurnSummary(entry: AssistantTurnEntry): AssistantTurhasContent: false, process: [], responses: [],};const last = entry.parts.at(-1);- const answer = last?.kind === "message" && messageContentFacts(last.message).hasContent ? last : undefined;for (const part of entry.parts) {if (part.kind === "activity") {result.process.push(part);@@ -66,9 +66,17 @@ export function getAssistantTurnSummary(entry: AssistantTurnEntry): AssistantTur}const message = part.message;result.messages.push(message);- if (part === answer || message.error) result.responses.push(part);- else result.process.push(part);- if (messageContentFacts(message).hasContent) {+ const projected = projectAssistantCommentary(message);+ if (projected) {+ for (const progress of projected.progress) {+ result.process.push({ kind: "message", message: progress, sourceMessageId: message.id });+ }+ }+ const reply = projected ? { ...part, message: projected.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);+ if (hasReply) {result.actionMessage = message;result.hasContent = true;}@@ -105,7 +113,7 @@ export function getAssistantTurnSummary(entry: AssistantTurnEntry): AssistantTur/** 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(message).trimmedContent)+ .map((message) => messageContentFacts(projectAssistantCommentary(message)?.reply ?? message).trimmedContent).filter(Boolean).join("\n\n");}diff --git a/apps/desktop/src/lib/turn-process.ts b/apps/desktop/src/lib/turn-process.tsindex d589c7f36..49e2deea4 100644--- a/apps/desktop/src/lib/turn-process.ts+++ b/apps/desktop/src/lib/turn-process.ts@@ -8,6 +8,7 @@ import type {import { isStandaloneRunActivity } from "./assistant-turns";import type { TranscriptDisplayMode } from "./transcript-display-mode";import { isDelegationStartTool } from "./tool-display";+import { getAssistantTurnSummary } from "./transcript-summary";export function isThinkingActive(message: UiMessage, active: boolean): boolean {return active && message.status === "streaming" && !message.content.trim();@@ -31,7 +32,7 @@ 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) return true;return (@@ -298,25 +299,8 @@ 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.- */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 --git a/apps/desktop/test/transcript-summary.test.mjs b/apps/desktop/test/transcript-summary.test.mjsindex 4066a85ea..8223de468 100644--- a/apps/desktop/test/transcript-summary.test.mjs+++ b/apps/desktop/test/transcript-summary.test.mjs@@ -19,6 +19,55 @@ 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 turn = entry([row]);+ 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.equal(summary.actionMessage.id, row.id);+ assert.equal(row.content, [...commentary, answer].join(""));+});++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" }),+ }] } },+ ];+ for (const extra of fields) {+ const turn = entry([message("reply", content, extra)]);+ 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 --git a/docs/adr/turn-process-and-thinking-display.md b/docs/adr/turn-process-and-thinking-display.mdindex 661e68a81..20516d193 100644--- a/docs/adr/turn-process-and-thinking-display.md+++ b/docs/adr/turn-process-and-thinking-display.md@@ -17,11 +17,12 @@ some readers want a thinking indicator without rapidly changing reasoning text.Every loaded assistant turn is projected into one collapsible process disclosureplus its trailing answer. Thinking, tools, intermediate text, and the turn's-`Bash` run rows keep their order inside it. Trailing text stays visible while-streaming and moves into the process if later activity follows, without changing-the stored message. `UiMessage` has no final-answer marker, so the renderer never-guesses intent from wording; user/system messages and compaction dividers keep-their turn boundaries.+`Bash` run rows keep their order inside it. A Responses `commentary` item goes+into the process, including when it shares a stored message with the answer.+Untagged trailing text stays visible while streaming and moves into the process+if later activity follows. The renderer never guesses intent from wording.+Neither projection changes stored model history; user/system messages and+compaction dividers keep their turn boundaries.One turn renders exactly one disclosure holding every row produced before theanswer, so a long turn collapses in one gesture. An untouched process closes whendiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 4ce17e13e..3d776f227 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -197,6 +197,14 @@ truncated tool calls retain their existing behavior.visible assistant error message12. finalize and persist successful answer/thinking blocks independently+For Responses text with a known `commentary` phase, live assistant updates+carry presentation-only UTF-16 ranges in `commentaryRanges`, relative to the+whole reconstructed `content`. A delta carries the current ranges, not an+incremental range list. Persisted messages still use the original content+and existing provider replay signatures, which retain the phase after reload.+Classification does not change stop reasons, tool execution, usage, or the+messages sent back to the provider.+While an active turn has no new transcript row, the runtime emits a normalized`status` event that names the quiet interval: `starting` for the prompthandoff, `waiting-model` while a provider request waits for its first assistantdiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 3c03ce2d2..9e2e5d09e 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -967,6 +967,14 @@ can reclassify provisional answer text into the process without changing thestored message. Assistant errors and stopped trailing partial answers also stayoutside 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.+The disclosure owns every row the turn produced before its answer: ordinaryactivity groups and `Bash` run rows alike. A turn therefore renders exactly onetop-level process disclosure, including a Bash-only turn; no run row is a siblingdiff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.mdindex eb09e0a39..443c85954 100644--- a/docs/spec/06-delivery/e2e/conversation.md+++ b/docs/spec/06-delivery/e2e/conversation.md@@ -4437,6 +4437,11 @@ command, a delegate, and an explicit Stop. Accepted input is delivered once.singleton segment, literal-final-item leaf selection, failure/denial/recovery,retained-pane remounts, run rows keeping their details closed until opened, anda legacy search reveal.+ Stream a Responses assistant message containing explicitly labelled progress+ followed by final text in the same message. Check that the progress is+ inside the disclosure before the final text appears. Settle and reload the+ message; only the final text should remain outside the collapsed process,+ and expanding it should reveal the progress without changing the answer.In AI settings, check the display selector in English and Simplified Chineseat 800px, 1000px, and 1440px window widths with 100% and 150% font scales.Select all three values and verify each remains visibly selected and saved.diff --git a/packages/agent-runtime/src/agent-messages.ts b/packages/agent-runtime/src/agent-messages.tsindex 4d0ba9260..934d3b5e7 100644--- a/packages/agent-runtime/src/agent-messages.ts+++ b/packages/agent-runtime/src/agent-messages.ts@@ -7,7 +7,7 @@import type { AgentMessage } from "@earendil-works/pi-agent-core";import type { JsonObject, JsonValue, Usage } from "@earendil-works/pi-ai";-import type { MessageUsage, UsageProvenance } from "@pi-desktop/shared";+import { isResponsesCommentary, type AssistantCommentaryRange, type MessageUsage, type UsageProvenance } from "@pi-desktop/shared";export function nowIso(): string {return new Date().toISOString();@@ -123,6 +123,7 @@ export type AssistantContent = {thinking: string;hasText: boolean;hasThinking: boolean;+ commentaryRanges?: AssistantCommentaryRange[];};/** Flatten a pi-ai assistant content array into visible text and reasoning. */@@ -138,15 +139,20 @@ export function assistantContent(content: unknown): AssistantContent {let thinking = "";let hasText = false;let hasThinking = false;+ let commentaryRanges: AssistantCommentaryRange[] | undefined;for (const part of content) {if (!part || typeof part !== "object") continue;const block = part as {type?: string;text?: string;thinking?: string;+ textSignature?: unknown;};if (block.type === "text" && typeof block.text === "string") {hasText = true;+ if (block.text && isResponsesCommentary(block.textSignature)) {+ (commentaryRanges ??= []).push({ start: text.length, end: text.length + block.text.length });+ }text += block.text;} else if (block.type === "thinking") {hasThinking = true;@@ -158,7 +164,7 @@ export function assistantContent(content: unknown): AssistantContent {}}}- return { text, thinking, hasText, hasThinking };+ return { text, thinking, hasText, hasThinking, ...(commentaryRanges ? { commentaryRanges } : {}) };}/**diff --git a/packages/agent-runtime/src/hosted-search-contract.test.ts b/packages/agent-runtime/src/hosted-search-contract.test.tsindex 7c870baa9..b9db9fa9c 100644--- a/packages/agent-runtime/src/hosted-search-contract.test.ts+++ b/packages/agent-runtime/src/hosted-search-contract.test.ts@@ -53,7 +53,14 @@ async function processEvents(events: AnyRecord[]): Promise<{maxTokens: 8_192,} as never;const sink = {- push: (event: AnyRecord) => stream.push(event),+ push: (event: AnyRecord) => {+ if (event.type !== "text_start") {+ stream.push(event);+ return;+ }+ const block = (event.partial as AssistantMessage).content[Number(event.contentIndex)];+ stream.push({ ...event, textSignatureAtPush: block?.type === "text" ? block.textSignature : undefined });+ },} as unknown as Parameters<typeof processResponsesStream>[2];const asyncEvents = (async function* () {for (const event of events) yield event;@@ -70,6 +77,24 @@ async function processEvents(events: AnyRecord[]): Promise<{}, stream };}+describe("Responses assistant text phases", () => {+ it("keeps the commentary phase before the item finishes, even when done omits it", async () => {+ const item = { type: "message", role: "assistant", id: "msg_progress" };+ const { output, stream } = await processEvents([+ { type: "response.output_item.added", output_index: 0, item: { ...item, phase: "commentary" } },+ { type: "response.output_text.delta", output_index: 0, content_index: 0, delta: "Checking." },+ { type: "response.output_item.done", output_index: 0, item: {+ ...item, status: "completed", content: [{ type: "output_text", text: "Checking.", annotations: [] }],+ } },+ { type: "response.completed", response: { id: "resp_test", usage: {} } },+ ]);+ const expected = JSON.stringify({ v: 1, id: item.id, phase: "commentary" });+ const start = stream.find((event) => event.type === "text_start");+ expect(start?.textSignatureAtPush).toBe(expected);+ expect(output.content[0]).toMatchObject({ type: "text", textSignature: expected });+ });+});+describe("pi-ai hosted web search: responses stream extraction", () => {it("captures a web_search_call as a hostedSearch content block", async () => {const { output } = await processEvents([diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 4f1412f26..cf8874afa 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -297,6 +297,51 @@ describe("Pi 1.4 client identity", () => {});});+describe("Responses commentary routing", () => {+ it("carries stage ranges while streaming and leaves the saved model text intact", async () => {+ const progress = "Checking references.";+ const answer = "Here is the result.";+ const items = [progress, answer].map((text, index) => ({+ id: `msg_fixture_${index}`, type: "message", role: "assistant", status: "completed",+ phase: index === 0 ? "commentary" : "final_answer",+ content: [{ type: "output_text", text, annotations: [] }],+ }));+ const frames = [+ { type: "response.created", response: { id: "resp_fixture" } },+ ...items.flatMap((item, index) => [+ { type: "response.output_item.added", output_index: index, item: { ...item, content: [] } },+ { type: "response.output_text.delta", output_index: index, content_index: 0, delta: item.content[0].text },+ { type: "response.output_item.done", output_index: index, item },+ ]),+ { type: "response.completed", response: { id: "resp_fixture", status: "completed", output: items } },+ ];+ vi.stubGlobal("fetch", vi.fn(async () => new Response(+ frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join(""),+ { headers: { "content-type": "text/event-stream" } },+ )));+ const events: AgentEventEnvelope["event"][] = [];+ const runtime = createRuntime({+ provider: { ...provider, apiStyle: "responses", baseUrl: "https://responses-fixture.invalid/v1" },+ onEvent: (value) => { events.push((value as AgentEventEnvelope).event); },+ });+ try {+ await runtime.prompt("Check the references and answer.", "fixture-user", "fixture-turn");+ // The runtime may batch progress and answer tokens into one update.+ const update = events.find((event) => event.type === "message_update" && event.deltaText?.startsWith(progress));+ expect(update).toMatchObject({ message: { commentaryRanges: [{ start: 0, end: progress.length }] } });+ const finish = events.find((event) => event.type === "message_end" && event.message.role === "assistant");+ expect(finish).toMatchObject({ message: { content: progress + answer, status: "complete" } });+ expect(finish?.type === "message_end" && finish.message.providerReplay?.blocks).toEqual(items.map((item) => ({+ type: "text", length: item.content[0].text.length,+ signature: JSON.stringify({ v: 1, id: item.id, phase: item.phase }),+ })));+ } finally {+ await runtime.dispose();+ vi.unstubAllGlobals();+ }+ });+});+describe("ordered read preparation", () => {it.each([["Bash", false], ["Write", false], ["Edit", false], ["Bash", true],diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex aae9c51ae..c78f0b866 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -8619,6 +8619,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst previousText = this.currentAssistant.content;const previousThinking = this.currentAssistant.thinking ?? "";const nextText = content.hasText ? content.text : previousText;+ const previousCommentary = this.currentAssistant.commentaryRanges;+ const commentaryRanges = content.hasText ? content.commentaryRanges : previousCommentary;+ const commentaryChanged = commentaryRanges?.length !== previousCommentary?.length ||+ commentaryRanges?.some(({ start, end }, index) =>+ start !== previousCommentary?.[index]?.start || end !== previousCommentary?.[index]?.end,+ );const nextThinking = content.hasThinking? content.thinking: previousThinking;@@ -8631,6 +8637,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.currentAssistant = {...this.currentAssistant,content: nextText,+ commentaryRanges,...(nextThinking? { thinking: nextThinking }: content.hasThinking@@ -8642,7 +8649,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetextDelta.delta ||thinkingDelta.delta ||textDelta.reset ||- thinkingDelta.reset+ thinkingDelta.reset ||+ commentaryChanged) {this.emit({type: "message_update",@@ -8964,6 +8972,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.currentAssistant = {...this.currentAssistant,content: nextText,+ commentaryRanges: content.hasText ? content.commentaryRanges : this.currentAssistant.commentaryRanges,...(nextThinking? { thinking: nextThinking }: content.hasThinkingdiff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 169501f33..e4487788e 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -72,6 +72,7 @@ export * from "./racp.js";export * from "./trusted-extensions.js";export * from "./provider-retry.js";export * from "./message-stream.js";+export * from "./responses-message-phase.js";export * from "./session-collaboration.js";export * from "./session-presentation.js";export * from "./session-outcomes.js";diff --git a/packages/shared/src/message-stream.test.ts b/packages/shared/src/message-stream.test.tsindex 1c88a3b28..6d9dce9ac 100644--- a/packages/shared/src/message-stream.test.ts+++ b/packages/shared/src/message-stream.test.ts@@ -64,6 +64,28 @@ describe("toWireMessageUpdate / applyMessageUpdate", () => {expect(applied.id).toBe("m1");});+ it("carries the latest commentary ranges through batching and clears them on replacement", () => {+ const start = assistant({ id: "m1", content: "" });+ const ranges = [{ start: 0, end: 9 }];+ const progress = toWireMessageUpdate({+ type: "message_update", deltaText: "Checking.",+ message: { ...start, content: "Checking.", commentaryRanges: ranges },+ });+ const final = toWireMessageUpdate({+ type: "message_update", deltaText: "Answer.",+ message: { ...start, content: "Checking.Answer.", commentaryRanges: ranges },+ });+ expect(progress.message.content).toBe("");+ const applied = applyMessageUpdate(start, mergeMessageUpdates(progress, final));+ expect(applied.content).toBe("Checking.Answer.");+ expect(applied.commentaryRanges).toEqual(ranges);+ const replacement = toWireMessageUpdate({+ type: "message_update", deltaText: "Replacement", resetText: true,+ message: { ...start, content: "Replacement" },+ });+ expect(applyMessageUpdate(applied, replacement).commentaryRanges).toBeUndefined();+ });+it("keeps snapshot updates as replacements", () => {const snapshot = assistant({ id: "m1", content: "replaced" });const event = { type: "message_update" as const, message: snapshot };diff --git a/packages/shared/src/message-stream.ts b/packages/shared/src/message-stream.tsindex e320e3547..4172d58dd 100644--- a/packages/shared/src/message-stream.ts+++ b/packages/shared/src/message-stream.ts@@ -45,6 +45,7 @@ export function streamingMessageIdentity(message: UiMessage): UiMessage {: {}),...(message.agentName ? { agentName: message.agentName } : {}),...(message.hostedSearch ? { hostedSearch: message.hostedSearch } : {}),+ ...(message.commentaryRanges ? { commentaryRanges: message.commentaryRanges } : {}),};}@@ -166,6 +167,7 @@ export function applyMessageUpdate(createdAt: event.message.createdAt || seed.createdAt,status: event.message.status ?? seed.status,content,+ commentaryRanges: event.message.commentaryRanges,...(thinking ? { thinking } : { thinking: undefined }),...(event.message.modelId ? { modelId: event.message.modelId } : {}),...(event.message.providerId ? { providerId: event.message.providerId } : {}),diff --git a/packages/shared/src/responses-message-phase.ts b/packages/shared/src/responses-message-phase.tsnew file mode 100644index 000000000..474e542c0--- /dev/null+++ b/packages/shared/src/responses-message-phase.ts@@ -0,0 +1,10 @@+/** 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;+ 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";+ } catch {+ return false;+ }+}diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 45184ece2..ce4fadceb 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -109,12 +109,17 @@ export type ToolTokenUsage = {estimated: true;};+export type AssistantCommentaryRange = { start: number; end: number };+export type UiMessage = {id: string;/** Durable root conversation identity for display grouping, never authorization. */turnId?: string;role: UiMessageRole;content: string;+ /** Live presentation metadata: UTF-16 ranges of provider-labelled progress in content.+ * Completed history derives these from providerReplay instead of persisting them twice. */+ commentaryRanges?: readonly AssistantCommentaryRange[];/** Internal model instructions/tool declarations; never a visible chat row. */modelSystem?: {version: 1;diff --git a/patches/@[email protected] b/patches/@[email protected]index f4074daab..84e112beb 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -457,7 +457,7 @@ index c1b6038c2220633a8caf710288a8f6e6301f7a28..2b6e6d5a48731a37812cd42740156fe8openRouterRouting: 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..60b63766576f463b83a964ef9b16d39472222693 100644+index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..17e350684857d863e8dfc51ff21944d8a92c5475 100644--- a/dist/api/openai-responses-shared.js+++ b/dist/api/openai-responses-shared.js@@ -1,3 +1,4 @@@@ -487,7 +487,20 @@ index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..60b63766576f463b83a964ef9b16d394else if (block.type === "toolCall") {const toolCall = block;const [callId, itemIdRaw] = toolCall.id.split("|");-@@ -458,6 +467,28 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -408,7 +417,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, modelstream.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });return slot;}@@ -516,7 +529,7 @@ index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..60b63766576f463b83a964ef9b16d394return undefined;};const getOrCreateSlot = (outputIndex, item) => {-@@ -539,11 +570,11 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -539,11 +574,11 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "thinking");if (!slot)continue;@@ -530,7 +543,7 @@ index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..60b63766576f463b83a964ef9b16d394partial: output,});}-@@ -563,11 +594,11 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -563,11 +598,11 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "thinking");if (!slot)continue;@@ -544,7 +557,7 @@ index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..60b63766576f463b83a964ef9b16d394partial: output,});}-@@ -575,23 +606,44 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -575,23 +610,44 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "text");if (!slot)continue;@@ -593,7 +606,7 @@ index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..60b63766576f463b83a964ef9b16d394partial: output,});}-@@ -599,8 +651,8 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -599,8 +655,8 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "toolCall");if (slot?.input.kind !== "json")continue;@@ -604,7 +617,17 @@ index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..60b63766576f463b83a964ef9b16d394}else if (event.type === "response.function_call_arguments.done") {const slot = getSlot(event.output_index, "toolCall");-@@ -680,9 +732,25 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -643,7 +699,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});outputSlots.delete(event.output_index);}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2984ef9b4..9510a2a7e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -206,7 +206,7 @@ overrides:patchedDependencies:'@earendil-works/[email protected]': f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da- '@earendil-works/[email protected]': b7b4aa9dd844d3ab0678ff1a62a2e1bff5ceace6b6fa2fe8654eeadd39bce6ec+ '@earendil-works/[email protected]': 66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96'@earendil-works/[email protected]': b1ad25365da34b5862e5263254f499e8c28a8344d66609110df5d2061c519bf9importers:@@ -234,7 +234,7 @@ importers:devDependencies:'@earendil-works/pi-ai':specifier: 1.5.2- version: 1.5.2(patch_hash=b7b4aa9dd844d3ab0678ff1a62a2e1bff5ceace6b6fa2fe8654eeadd39bce6ec)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 1.5.2(patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-mcp':specifier: 1.5.2version: 1.5.2@@ -438,7 +438,7 @@ importers: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=b7b4aa9dd844d3ab0678ff1a62a2e1bff5ceace6b6fa2fe8654eeadd39bce6ec)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 1.5.2(patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-coding-agent':specifier: 1.5.2version: 1.5.2(patch_hash=b1ad25365da34b5862e5263254f499e8c28a8344d66609110df5d2061c519bf9)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])@@ -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=b7b4aa9dd844d3ab0678ff1a62a2e1bff5ceace6b6fa2fe8654eeadd39bce6ec)(@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-schema': 1.5.2transitivePeerDependencies:- '@aws-sdk/credential-provider-node'@@ -5164,7 +5164,7 @@ snapshots:- ws- zod- '@earendil-works/[email protected](patch_hash=b7b4aa9dd844d3ab0678ff1a62a2e1bff5ceace6b6fa2fe8654eeadd39bce6ec)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@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 @@ snapshots:- ws- zod- '@earendil-works/[email protected](patch_hash=b7b4aa9dd844d3ab0678ff1a62a2e1bff5ceace6b6fa2fe8654eeadd39bce6ec)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=66b23c9c830eb8361c7b9c5653a76a333a4e669a788c4fb9156fe741fc59fb96)(@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 @@ snapshots:'@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=b7b4aa9dd844d3ab0678ff1a62a2e1bff5ceace6b6fa2fe8654eeadd39bce6ec)(@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-codemode': 1.5.2'@earendil-works/pi-mcp': 1.5.2'@earendil-works/pi-tui': 1.5.2diff --git a/scripts/e2e/turn-process.tsx b/scripts/e2e/turn-process.tsxindex 6c363ebea..826af55a3 100644--- a/scripts/e2e/turn-process.tsx+++ b/scripts/e2e/turn-process.tsx@@ -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 type { AppSettings, UiMessage } from "@pi-desktop/shared";+import { applyMessageUpdate, toWireMessageUpdate, 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";@@ -186,6 +186,37 @@ 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();+// 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");