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(runtime): replay Gemini function-call signatures after a rebuild
zszz3c633e52dc87c
diff --git a/apps/desktop/electron/main/runtime/event-persistence.ts b/apps/desktop/electron/main/runtime/event-persistence.tsindex 467d5638d..77109f8e3 100644--- a/apps/desktop/electron/main/runtime/event-persistence.ts+++ b/apps/desktop/electron/main/runtime/event-persistence.ts@@ -342,8 +342,10 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined}// Empty assistant bubbles are dropped by default so provider retries do// not grow the transcript. Keep structured failures and tool-call rows- // durable, plus rows reserved by accepted steering and the first completed- // reply to a Host-verified completion notice (D446), tracked by turn ID.+ // durable, plus rows reserved by accepted steering, the first completed+ // reply to a Host-verified completion notice (D446), tracked by turn ID,+ // and call-only replies whose function calls carry provider signatures+ // that a rebuilt runtime must replay (#1972).const empty =!(event.message.content || "").trim() &&!(event.message.thinking || "").trim();@@ -356,7 +358,10 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefinedevent.message.status === "complete" &&messageTurnId !== undefined &&completionNoticeTurns.delete(messageTurnId);- if (empty && !carriesTool && !event.message.error && !reservedForSteering && !isCompletionNoticeReply) {+ if (+ empty && !carriesTool && !event.message.error && !reservedForSteering &&+ !isCompletionNoticeReply && !event.message.providerReplay+ ) {return;}void persistenceOutboxdiff --git a/apps/desktop/test/empty-assistant-persistence.test.mjs b/apps/desktop/test/empty-assistant-persistence.test.mjsindex db08e7e52..b1671e71c 100644--- a/apps/desktop/test/empty-assistant-persistence.test.mjs+++ b/apps/desktop/test/empty-assistant-persistence.test.mjs@@ -129,6 +129,21 @@ test("an empty assistant message that still carries a tool row is persisted", ()assert.equal(f.enqueued.length, 1);});+test("an empty call-only reply with provider replay data is persisted (#1972)", () => {+ // Gemini signs a function call on its own; a rebuilt runtime can only send+ // that signature back if the reply row that carries it is durable.+ const f = fixture();+ f.persistAssistant({+ id: "m3-signed",+ content: "",+ thinking: "",+ status: "complete",+ providerReplay: { version: 1, blocks: [], toolCalls: [{ id: "call-1", signature: "sig" }] },+ });+ assert.equal(f.enqueued.length, 1);+ assert.deepEqual(f.enqueued[0].message.providerReplay.toolCalls, [{ id: "call-1", signature: "sig" }]);+});+test("an empty assistant message with an error payload stays durable", () => {const f = fixture();f.persistAssistant({diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 086229dd8..1cf4862a9 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -3,9 +3,9 @@- Fixed prompt cache misses after a conversation's agent runtime is rebuilt(#1972). Rebuilding happens after a restart or when the thinking level, mode,project rules, or model settings change. Assistant replies now keep the- provider's thinking and reasoning signatures in the transcript, so Claude,- OpenAI Responses, Gemini, and other reasoning models receive the same history- as before the rebuild instead of a rewritten one.+ provider's thinking, reasoning, and Gemini function-call signatures in the+ transcript, so Claude, OpenAI Responses, Gemini, and other reasoning models+ receive the same history as before the rebuild instead of a rewritten one.- Fixed duplicate `/、` when opening slash commands with a Chinese IME in anempty composer. Keep pre-edit text intact and apply the slash alias onlyafter composition commits, preserving recovery from a missing end event.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex fb13ae87f..b9b34e30a 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -317,6 +317,16 @@ live one and keeps the provider prompt cache. If the stored lengths no longeradd up to the row's text, or the reasoning text was cleaned on replay, the rowfalls back to the plain thinking-and-text rebuild.+`meta.providerReplay.toolCalls = [{ id, signature }]` keeps the signature a+provider put on a function call (Gemini `thoughtSignature`), keyed by the tool+call id. The calls are rebuilt from their tool rows, which carry the same id,+and get their signature back; this does not depend on the text lengths. A+call-only reply that carries such signatures is persisted even though it has no+text. pi-ai still drops a signature whose row came from a different provider or+model. A row whose serialized replay data exceeds 64 KiB is stored without it+and uses the plain rebuild, so opaque payloads cannot grow the transcript+without bound.+Compaction details may include one `systemMessageJson` checkpoint. It replaces oldsystem updates in the retained tail and is restored before the summary. Theseoptional metadata fields use the existing JSONL/SQLite index and require nodiff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex dad4655f5..c23e8a78c 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -820,6 +820,12 @@ reasoning item 与 message id、Gemini thought signature、Completions 推理字runtime 从转录重建时按原块和签名还原,使重放请求与在线请求一致,保住 provider 的prompt cache。长度对不上,或推理文本在回放时被清理过,就退回原来的纯文本重建。+`meta.providerReplay.toolCalls = [{ id, signature }]` 按工具调用 id 保存 provider+挂在函数调用上的签名(Gemini `thoughtSignature`)。工具调用从带同一 id 的工具行重建,+并据此补回签名,这一步不依赖文本长度。只有函数调用、但带这类签名的回复即使没有文本+也会持久化。来自不同 provider 或模型的行,pi-ai 仍会丢弃其签名。序列化后的回放数据+超过 64 KiB 的行不保存该字段,改用纯文本重建,避免不透明载荷让转录无限增长。+这两个字段都可以在重新加载后保存下来,这就是恢复会话嵌套的原因就像现场一样(`04-ux/08-component-spec.md` §9.9)。两位消费者阅读了它们:diff --git a/packages/agent-runtime/src/assistant-provider-replay.test.ts b/packages/agent-runtime/src/assistant-provider-replay.test.tsindex a96eee989..b916151b5 100644--- a/packages/agent-runtime/src/assistant-provider-replay.test.ts+++ b/packages/agent-runtime/src/assistant-provider-replay.test.ts@@ -4,7 +4,10 @@ import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";import type { CommandShellOption, UiMessage } from "@pi-desktop/shared";import {+ MAX_PROVIDER_REPLAY_BYTES,captureAssistantProviderReplay,+ providerReplayForBubble,+ providerReplayToolCallSignatures,restoreAssistantProviderReplay,} from "./assistant-provider-replay.js";import { assistantContent } from "./agent-messages.js";@@ -49,6 +52,42 @@ describe("assistant provider replay", () => {expect(captureAssistantProviderReplay("text only")).toBeUndefined();});+ it("links function-call signatures by call id", () => {+ const replay = captureAssistantProviderReplay([+ { type: "toolCall", id: "call-1", name: "Read", arguments: {}, thoughtSignature: "fc-1" },+ { type: "toolCall", id: "call-2", name: "Read", arguments: {} },+ ]);+ expect(replay).toEqual({ version: 1, blocks: [], toolCalls: [{ id: "call-1", signature: "fc-1" }] });+ expect([...providerReplayToolCallSignatures(replay)]).toEqual([["call-1", "fc-1"]]);+ expect(providerReplayToolCallSignatures({ version: 2, toolCalls: [{ id: "a", signature: "b" }] }).size).toBe(0);+ });++ it("drops the replay data of a row above the size ceiling", () => {+ const huge = "x".repeat(MAX_PROVIDER_REPLAY_BYTES);+ expect(+ captureAssistantProviderReplay([{ type: "thinking", thinking: "", thinkingSignature: huge, redacted: true }]),+ ).toBeUndefined();+ expect(+ captureAssistantProviderReplay([{ type: "thinking", thinking: "t", thinkingSignature: "small" }]),+ ).toBeDefined();+ });++ it("keeps only call signatures when the bubble text is not this response's", () => {+ const replay = captureAssistantProviderReplay([+ { type: "thinking", thinking: "t", thinkingSignature: "th" },+ { type: "toolCall", id: "call-1", name: "Read", arguments: {}, thoughtSignature: "fc-1" },+ ]);+ expect(providerReplayForBubble(replay, true)).toBe(replay);+ expect(providerReplayForBubble(replay, false)).toEqual({+ version: 1,+ blocks: [],+ toolCalls: [{ id: "call-1", signature: "fc-1" }],+ });+ expect(+ providerReplayForBubble(captureAssistantProviderReplay([{ type: "text", text: "a", textSignature: "m" }]), false),+ ).toBeUndefined();+ });+it("falls back when the stored lengths no longer match the row", () => {const replay = captureAssistantProviderReplay(signedContent);expect(restoreAssistantProviderReplay(replay, "plan Aplan B", "Hello world!")).toBeUndefined();@@ -239,3 +278,209 @@ describe("live response to rebuilt request", () => {expect(input).toContainEqual(expect.objectContaining({ type: "message", role: "assistant", id: "msg_real_1" }));});});++/**+ * Gemini signs function calls separately from thinking (`thoughtSignature` on+ * the functionCall part). The call is rebuilt from its tool row, so the+ * signature has to come back from the assistant row's replay data.+ */+describe("Gemini function-call signatures across a rebuild", () => {+ const googleProvider: RuntimeProviderConfig = {+ id: "google",+ name: "Google Gemini",+ vendorKey: "google",+ apiStyle: "google_generative_ai",+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",+ modelId: "gemini-3.8-flash",+ apiKey: "AIza-test",+ authKind: "api_key",+ supportsReasoning: true,+ supportedThinkingLevels: ["off", "high"],+ };++ type GooglePart = Record<string, unknown>;+ type GoogleContent = { role: string; parts: GooglePart[] };++ function googleRuntime(history: UiMessage[], onEvent = vi.fn()) {+ return new DesktopAgentRuntime({+ host: {+ call: vi.fn(async () => ({})),+ onNotification: vi.fn(() => () => {}),+ } as never,+ sessionId: "session-g",+ mode: "agent",+ provider: googleProvider,+ thinkingLevel: "high",+ commandShell,+ history,+ onEvent,+ });+ }++ // The Google adapter only accepts the global fetch (#1072).+ async function requestContents(+ runtime: DesktopAgentRuntime,+ messages: unknown[],+ ): Promise<GoogleContent[]> {+ const internals = runtime as unknown as { agent: Agent; model: Model<Api> };+ const bodies: { contents: GoogleContent[] }[] = [];+ vi.stubGlobal("fetch", async (_url: unknown, init?: RequestInit) => {+ bodies.push(JSON.parse(String(init?.body)));+ // A short successful stream: a failed request would be retried.+ const chunk = (body: unknown) => `data: ${JSON.stringify(body)}\n\n`;+ return new Response(+ chunk({ candidates: [{ content: { role: "model", parts: [{ text: "ok" }] }, index: 0 }] }) ++ chunk({+ candidates: [{ content: { role: "model", parts: [] }, finishReason: "STOP", index: 0 }],+ usageMetadata: { promptTokenCount: 3, candidatesTokenCount: 1, totalTokenCount: 4 },+ }),+ { status: 200, headers: { "content-type": "text/event-stream" } },+ );+ });+ try {+ const stream = await internals.agent.streamFunction(+ internals.model,+ { messages: [...messages, { role: "user", content: "next", timestamp: 9 }] } as never,+ { apiKey: "AIza-test" },+ );+ await stream.result();+ } finally {+ vi.unstubAllGlobals();+ }+ expect(bodies).toHaveLength(1);+ return bodies[0].contents;+ }++ /**+ * Runs one live call-making turn, persists what the Host would (the+ * assistant row from message_end, tool rows from tool_start/tool_end, all+ * as JSON), then compares the live and rebuilt requests.+ */+ async function liveAndRebuilt(content: AssistantMessage["content"]) {+ const onEvent = vi.fn();+ const live = googleRuntime([], onEvent);+ const internals = live as unknown as {+ model: Model<Api>;+ handleAgentEvent: (event: unknown) => Promise<void>;+ };+ const handle = internals.handleAgentEvent.bind(live);+ const message = {+ role: "assistant",+ content: [] as AssistantMessage["content"],+ api: internals.model.api,+ provider: internals.model.provider,+ model: internals.model.id,+ usage: {+ input: 1,+ output: 1,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 2,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: "toolUse",+ timestamp: 2,+ };+ const finished = { ...message, content } as AssistantMessage;+ await handle({ type: "message_start", message });+ await handle({ type: "message_end", message: finished });+ const calls = content.filter((block) => block.type === "toolCall");+ const results = calls.map((call, index) => ({+ role: "toolResult",+ toolCallId: call.id,+ toolName: call.name,+ content: [{ type: "text", text: `result ${index + 1}` }],+ details: undefined,+ isError: false,+ timestamp: 3 + index,+ }));+ for (const [index, call] of calls.entries()) {+ await handle({ type: "tool_execution_start", toolCallId: call.id, toolName: call.name, args: call.arguments });+ await handle({+ type: "tool_execution_end",+ toolCallId: call.id,+ toolName: call.name,+ result: results[index].content[0].text,+ isError: false,+ });+ }+ const user = { role: "user" as const, content: "question", timestamp: 1 };+ const liveContents = await requestContents(live, [user, finished, ...results]);+ await live.dispose();++ const events = onEvent.mock.calls.map(+ ([envelope]) => (envelope as { event: Record<string, any> }).event,+ );+ const assistantRow = events.find(+ (event) => event.type === "message_end" && event.message?.role === "assistant",+ )?.message as UiMessage;+ // Host-built tool rows (packages/host-runtime turn-events tool_end).+ const toolRows: UiMessage[] = calls.map((call, index) => {+ const end = events.find((event) => event.type === "tool_end" && event.toolCallId === call.id);+ return {+ id: call.id,+ role: "tool",+ content: "",+ createdAt: `2026-01-01T00:00:0${3 + index}.000Z`,+ toolCallId: call.id,+ toolName: call.name,+ toolArgs: call.arguments,+ toolResult: end?.result,+ toolStatus: "success",+ };+ });+ const history = JSON.parse(JSON.stringify([+ { id: "u1", role: "user", content: "question", createdAt: "2026-01-01T00:00:01.000Z" },+ { ...assistantRow, createdAt: "2026-01-01T00:00:02.000Z" },+ ...toolRows,+ ])) as UiMessage[];+ const rebuilt = googleRuntime(history);+ const rebuiltInternals = rebuilt as unknown as { fullEntries: { message: unknown }[] };+ const rebuiltContents = await requestContents(+ rebuilt,+ rebuiltInternals.fullEntries.map((entry) => entry.message),+ );+ await rebuilt.dispose();+ return { liveContents, rebuiltContents, assistantRow };+ }++ const modelParts = (contents: GoogleContent[]) =>+ contents.find((entry) => entry.role === "model")?.parts ?? [];+ const responseParts = (contents: GoogleContent[]) =>+ contents+ .filter((entry) => entry.role === "user")+ .flatMap((entry) => entry.parts)+ .filter((part) => "functionResponse" in part)+ .map((part) => {+ const response = part.functionResponse as { name: string; id?: string };+ return { name: response.name, id: response.id };+ });++ it("restores a signature carried only by the function call", async () => {+ const { liveContents, rebuiltContents, assistantRow } = await liveAndRebuilt([+ { type: "toolCall", id: "call-1", name: "Read", arguments: { path: "a.ts" }, thoughtSignature: "ZmMtc2lnLTE=" },+ { type: "toolCall", id: "call-2", name: "Grep", arguments: { pattern: "x" } },+ ]);+ expect(assistantRow.providerReplay?.toolCalls).toEqual([{ id: "call-1", signature: "ZmMtc2lnLTE=" }]);+ const parts = modelParts(rebuiltContents);+ expect(parts.map((part) => (part.functionCall as { name: string }).name)).toEqual(["Read", "Grep"]);+ expect(parts[0].thoughtSignature).toBe("ZmMtc2lnLTE=");+ expect(parts[1].thoughtSignature).toBeUndefined();+ expect(parts).toEqual(modelParts(liveContents));+ expect(responseParts(rebuiltContents)).toEqual(responseParts(liveContents));+ expect(responseParts(rebuiltContents).map((part) => part.name)).toEqual(["Read", "Grep"]);+ });++ it("restores thinking and function-call signatures together", async () => {+ const { liveContents, rebuiltContents } = await liveAndRebuilt([+ { type: "thinking", thinking: "look first", thinkingSignature: "dGgtc2ln" },+ { type: "toolCall", id: "call-1", name: "Read", arguments: { path: "a.ts" }, thoughtSignature: "ZmMtc2lnLTE=" },+ { type: "toolCall", id: "call-2", name: "Grep", arguments: { pattern: "x" }, thoughtSignature: "ZmMtc2lnLTI=" },+ ]);+ const parts = modelParts(rebuiltContents);+ expect(parts[0]).toMatchObject({ thought: true, thoughtSignature: "dGgtc2ln" });+ expect(parts.slice(1).map((part) => part.thoughtSignature)).toEqual(["ZmMtc2lnLTE=", "ZmMtc2lnLTI="]);+ expect(parts).toEqual(modelParts(liveContents));+ expect(responseParts(rebuiltContents)).toEqual(responseParts(liveContents));+ });+});diff --git a/packages/agent-runtime/src/assistant-provider-replay.ts b/packages/agent-runtime/src/assistant-provider-replay.tsindex a02cc33f1..cbaaac666 100644--- a/packages/agent-runtime/src/assistant-provider-replay.ts+++ b/packages/agent-runtime/src/assistant-provider-replay.ts@@ -18,8 +18,17 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";import type {AssistantProviderReplay,AssistantProviderReplayBlock,+ AssistantProviderReplayToolCall,} from "@pi-desktop/shared";+/**+ * Per-row ceiling for the serialized replay data. Signatures are opaque and+ * redacted or encrypted reasoning can be kilobytes per block; a row above the+ * ceiling is stored without replay data and falls back to the plain rebuild+ * instead of growing the transcript without bound.+ */+export const MAX_PROVIDER_REPLAY_BYTES = 64 * 1024;+type ReplayContent = Extract<AssistantMessage["content"][number],{ type: "thinking" } | { type: "text" }@@ -39,6 +48,7 @@ export function captureAssistantProviderReplay(): AssistantProviderReplay | undefined {if (!Array.isArray(content)) return undefined;const blocks: AssistantProviderReplayBlock[] = [];+ const toolCalls: AssistantProviderReplayToolCall[] = [];let carriesReplay = false;for (const part of content) {if (!part || typeof part !== "object") continue;@@ -48,6 +58,8 @@ export function captureAssistantProviderReplay(thinking?: unknown;thinkingSignature?: unknown;textSignature?: unknown;+ thoughtSignature?: unknown;+ id?: unknown;redacted?: unknown;};if (block.type === "thinking") {@@ -66,6 +78,15 @@ export function captureAssistantProviderReplay(...(signature ? { signature } : {}),...(redacted ? { redacted: true as const } : {}),});+ } else if (block.type === "toolCall") {+ // Gemini signs function calls separately from thinking and text. The+ // call is rebuilt from its tool row, so only the id link is kept.+ const id = nonEmpty(block.id);+ const signature = nonEmpty(block.thoughtSignature);+ if (id && signature) {+ carriesReplay = true;+ toolCalls.push({ id, signature });+ }} else if (block.type === "text" && typeof block.text === "string") {const signature = nonEmpty(block.textSignature);if (signature) carriesReplay = true;@@ -76,7 +97,15 @@ export function captureAssistantProviderReplay(});}}- return carriesReplay ? { version: 1, blocks } : undefined;+ if (!carriesReplay) return undefined;+ const replay: AssistantProviderReplay = {+ version: 1,+ blocks,+ ...(toolCalls.length > 0 ? { toolCalls } : {}),+ };+ return Buffer.byteLength(JSON.stringify(replay), "utf8") > MAX_PROVIDER_REPLAY_BYTES+ ? undefined+ : replay;}function validBlocks(replay: unknown): AssistantProviderReplayBlock[] | undefined {@@ -99,6 +128,25 @@ function validBlocks(replay: unknown): AssistantProviderReplayBlock[] | undefinereturn blocks as AssistantProviderReplayBlock[];}+/**+ * Signatures of the row's function calls by call id. Independent of the+ * thinking/text lengths, so they survive a row whose text no longer matches.+ */+export function providerReplayToolCallSignatures(replay: unknown): Map<string, string> {+ const signatures = new Map<string, string>();+ if (!replay || typeof replay !== "object") return signatures;+ const { version, toolCalls } = replay as { version?: unknown; toolCalls?: unknown };+ if (version !== 1 || !Array.isArray(toolCalls)) return signatures;+ for (const entry of toolCalls) {+ if (!entry || typeof entry !== "object") continue;+ const { id, signature } = entry as { id?: unknown; signature?: unknown };+ const callId = nonEmpty(id);+ const value = nonEmpty(signature);+ if (callId && value) signatures.set(callId, value);+ }+ return signatures;+}+/*** Rebuild the thinking/text blocks of a persisted assistant row with their* original boundaries and signatures. Returns undefined when the stored@@ -148,3 +196,18 @@ export function restoreAssistantProviderReplay(}return restored;}++/**+ * Replay data for a finished bubble. When the bubble's text is not this+ * response's own (it kept text from an earlier recovery attempt), the block+ * boundaries no longer apply; only the call-id-linked signatures remain.+ */+export function providerReplayForBubble(+ replay: AssistantProviderReplay | undefined,+ textMatchesResponse: boolean,+): AssistantProviderReplay | undefined {+ if (!replay || textMatchesResponse) return replay;+ return replay.toolCalls?.length+ ? { version: 1, blocks: [], toolCalls: replay.toolCalls }+ : undefined;+}diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 384ebdd4a..de99a6a3c 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -137,6 +137,8 @@ import { classifyAgentError } from "./agent-errors.js";import {captureAssistantProviderReplay,restoreAssistantProviderReplay,+ providerReplayForBubble,+ providerReplayToolCallSignatures,} from "./assistant-provider-replay.js";import {assistantContent,@@ -3142,6 +3144,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// (the nearest one above), keeping each call adjacent to its result as// the provider APIs require.let toolCarrier: AssistantMessage | undefined;+ // Function-call signatures of the carrier's row, restored by call id.+ let carrierToolSignatures = new Map<string, string>();for (const m of orderSystemRows(history)) {// Subagent rows belong to the transcript and to review, never to the// parent's model context (ADR 0062): the parent only ever saw the `Task`@@ -3231,6 +3235,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the};append(m.id, assistant);toolCarrier = assistant;+ carrierToolSignatures = providerReplayToolCallSignatures(m.providerReplay);} else if (m.role === "tool") {if (!m.toolCallId || !m.toolName) continue;if (!toolCarrier) {@@ -3247,12 +3252,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetimestamp,};append(`${m.id}:carrier`, toolCarrier);+ carrierToolSignatures = new Map();}+ const thoughtSignature = carrierToolSignatures.get(m.toolCallId);toolCarrier.content.push({type: "toolCall",id: m.toolCallId,name: m.toolName,arguments: toJsonObject(m.toolArgs),+ ...(thoughtSignature ? { thoughtSignature } : {}),});toolCarrier.stopReason = "toolUse";append(m.id, toolResultFromUi(m, timestamp));@@ -8708,11 +8716,14 @@ Do not invent objections or turn speculative risks into blockers. Stop when the...(hostedSearch ? { hostedSearch } : {}),// Signatures only describe this response's own blocks. A bubble// that kept text from an earlier recovery attempt no longer lines- // up with them, so it is persisted without replay data.- providerReplay:- !failed && nextText === content.text && nextThinking === content.thinking- ? captureAssistantProviderReplay((event.message as any).content)- : undefined,+ // up with them, so it keeps only the function-call signatures,+ // which are linked by call id rather than by text position.+ providerReplay: failed+ ? undefined+ : providerReplayForBubble(+ captureAssistantProviderReplay((event.message as any).content),+ nextText === content.text && nextThinking === content.thinking,+ ),};if (!this.currentAssistant.providerReplay) delete this.currentAssistant.providerReplay;this.emit({ type: "message_end", message: this.currentAssistant });diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex f9cd95d90..66967c526 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -184,16 +184,29 @@ export type UiMessage = {* `length` is the UTF-16 length of the block's text; the texts themselves are* already stored as `thinking` and `content` (concatenated), so only the* boundaries and signatures are kept here.+ *+ * `toolCalls` keeps the signature a provider attached to a function call+ * (Gemini's `thoughtSignature`), keyed by call id. The calls themselves are+ * rebuilt from their tool rows, which carry the same id.*/export type AssistantProviderReplay = {version: 1;blocks: AssistantProviderReplayBlock[];+ toolCalls?: AssistantProviderReplayToolCall[];};+/**+ * A text block's `signature` is pi-ai's `textSignature`: the Responses message+ * id or a Gemini thought signature. A thinking block's is the thinking+ * signature, redacted payload, encrypted reasoning item, or Completions+ * reasoning field name.+ */export type AssistantProviderReplayBlock =| { type: "thinking"; length: number; signature?: string; redacted?: true }| { type: "text"; length: number; signature?: string };+export type AssistantProviderReplayToolCall = { id: string; signature: string };+/*** Normalized provider-hosted web search activity for one assistant message.* One message can run several search rounds server-side; each round is one