Skip to content

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

fix(agent-runtime): keep unreplayable search history usable

vastsa63846b50d6d7
diff --git a/docs/project/hosted-search-contract-verification.md b/docs/project/hosted-search-contract-verification.md
index 089d5deb3..98e11ce40 100644
--- a/docs/project/hosted-search-contract-verification.md
+++ b/docs/project/hosted-search-contract-verification.md
@@ -107,9 +107,17 @@ Final evidence directory: `$PI_SCRATCH_DIR/hosted-search-e2e-CS9uZW`. The bundle
| `search-task-delegation` | PASS; real Task/TaskWait and parent continuation | 4 |
| `search-persist-restore` | PASS; disk JSON boundary and a new sidecar process | 2 |
| `invalid-search-container` | PASS; safe local validation error, no persistence call/runtime leak | 0 |
-| `invalid-search-phase` | PASS; explicit rejection, no persistence call/runtime leak | 0 |
+| `invalid-search-phase` | PASS; the turn continued without the stored replay and the unreplayable block never reached the provider (behavior changed after this run — see the note below) | 1 |
Each invalid-history case subsequently completes a clean session in the same process using a separate loopback fixture provider (one request). Those recovery requests are recorded separately and are not hidden in the malformed-history zero-request count. The changed-prefix artifact verifies changed request instructions; direct usage-anchor invalidation is asserted by the companion estimator/system tests rather than inferred solely from the RPC boundary.
+Behavior changed after this qualification: a stored record this app itself writes
+when a gateway drops ids (a display-only block with no replay id) used to reject
+the turn with a local context-validation error. It now degrades to "no replay"
+for that message, because rejecting it failed every later turn of that
+conversation. `invalid-search-container` still rejects: a container that is not a
+block list is a corrupt record, not an old readable one. The table above records
+the pre-fix run; `scripts/e2e/hosted-search-scenarios.mjs` holds the current
+expectations.
## Independent review and disposition
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index fe76a1452..12f7e73bd 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -1,5 +1,9 @@
# Unreleased changes
+- A stored hosted web-search record that cannot be replayed no longer fails every
+ later request in that conversation: the message continues without search replay,
+ so histories written before the contract change stay usable.
+
- Hosted web search now has a complete replay and estimation contract, including
tool/Task continuation and restart recovery. Context rebuilding preserves
system-prefix semantics, and structured local preparation failures no longer
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 918ec704d..1a244fb3e 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -408,8 +408,15 @@ retain the existing network/retry and cancellation behavior.
Restored-history validation may fail before a runtime stream exists. In that case
the existing RPC error `data` carries `errorCode`, `retriable: false`, and safe
-`details` (`origin`, `phase`, optional cause type). No provider request is made;
-the sidecar stays available and the stored record is not rewritten or skipped.
+`details` (`origin`, `phase`, optional cause type). No provider request is made,
+the sidecar stays available, and a stored record is never rewritten. A container
+that is not a stored block list still fails this way.
+
+A single stored block that cannot be replayed is a different case: this app itself
+stores display-only blocks when a gateway drops ids, so the whole stored replay for
+that message degrades to "no replay" instead of failing every later turn. The turn
+continues, display rounds are unchanged, and the diagnostic records the block count
+and phases without copying search content, results or credentials.
## 5. UI handling guidelines
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index efc7922ce..95fd453dd 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -265,7 +265,9 @@ Catalog and custom model entry must support common capability classes:
- Search content and progress events are declared adapter types, not disguised
client tool calls. A search result or Responses search item does not require
- `name` or `arguments`. Existing replay records remain compatible.
+ `name` or `arguments`. Existing replay records remain compatible: a stored
+ record this app wrote without replay ids degrades to "no replay" for that
+ message instead of failing the turn, so pre-upgrade history stays usable.
- Replay and token estimation share the search-phase interpretation. Valid
usage covers its prefix once; zero or invalidated usage triggers a complete
estimate which includes search replay data. Display rounds and streaming
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index b69c15a2f..0db2dba8c 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -451,4 +451,8 @@ transcript 保留稳定错误码、传输 errno 和原始 details,但使用本
历史恢复校验可能在运行时流创建前失败。此时使用既有 RPC 错误 `data`,携带
`errorCode`、`retriable: false` 及安全的 `details`(来源、阶段、可选原因类型)。
-不得发出模型请求;sidecar 保持可用,不改写或跳过损坏历史。
+不得发出模型请求,sidecar 保持可用,也不改写存储记录;容器不是存储块列表时仍按此失败。
+
+单个存储块无法回放属于另一种情况:网关丢弃 id 时本应用本身就会存下仅供展示的块,
+因此该消息的整条 replay 降级为“没有 replay”,而不是让之后每一轮请求都失败。
+回合继续执行,展示轮次不变;诊断只记录块数与阶段,不复制搜索内容、结果或凭据。
diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
index 145f156b1..c36f5413e 100644
--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
@@ -651,7 +651,9 @@ OpenAI Responses 适配器必须把 `response.completed`(以及
## 托管搜索消息与预算契约
- 搜索内容和进度事件必须拥有正式适配器类型,不能伪装成客户端工具调用。
- 搜索结果和 Responses 搜索项不要求 `name` 或 `arguments`;既有回放记录保持兼容。
+ 搜索结果和 Responses 搜索项不要求 `name` 或 `arguments`;既有回放记录保持兼容:
+ 本应用写出的、缺少回放 id 的记录为该消息降级为“没有 replay”,而不是让回合失败,
+ 升级前的历史因此仍可用。
- 回放与 token 估算共享搜索阶段的解释规则。有效 usage 只覆盖其前缀一次;
usage 为零或失效时,全量估算必须包含搜索回放数据,不重复计算展示轮次和流式临时字段。
估算不是服务端计费保证。
diff --git a/packages/agent-runtime/src/hosted-search-replay.test.ts b/packages/agent-runtime/src/hosted-search-replay.test.ts
index aaad90233..d2fa658bc 100644
--- a/packages/agent-runtime/src/hosted-search-replay.test.ts
+++ b/packages/agent-runtime/src/hosted-search-replay.test.ts
@@ -1,11 +1,22 @@
-import { describe, expect, it } from "vitest";
-import type { HostedSearch } from "@pi-desktop/shared";
+import { describe, expect, it, vi } from "vitest";
+import { hostedSearchFromMessage, type HostedSearch } from "@pi-desktop/shared";
import { restoreHostedSearchReplay } from "./hosted-search-replay.js";
function stored(replay: HostedSearch["replay"]): HostedSearch {
return { status: "completed", rounds: [], replay };
}
+/** 捕获诊断输出:降级必须可观测,而不是静默丢弃。 */
+function withCapturedWarnings<T>(run: () => T): { result: T; warnings: unknown[] } {
+ const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const result = run();
+ return { result, warnings: spy.mock.calls };
+ } finally {
+ spy.mockRestore();
+ }
+}
+
describe("stored hosted-search replay boundary", () => {
it("keeps display-only old records readable without manufacturing replay", () => {
expect(restoreHostedSearchReplay(undefined)).toEqual([]);
@@ -44,9 +55,23 @@ describe("stored hosted-search replay boundary", () => {
);
});
- it("reports a structured local error rather than dropping a corrupt replay phase", () => {
- expect(() => restoreHostedSearchReplay(stored([
+ it("drops the whole replay rather than failing a turn on an unreplayable block", () => {
+ const { result, warnings } = withCapturedWarnings(() => restoreHostedSearchReplay(stored([
+ { type: "hostedSearch", phase: "server_tool_use", blockId: "srv_fixture", name: "web_search", input: { query: "fixture" } },
{ type: "hostedSearch", phase: "unsupported", blockId: "fixture" },
- ]))).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" }));
+ ])));
+ // 整条丢弃:留下配对的另一半会制造适配器无法接受的孤立块。
+ expect(result).toEqual([]);
+ expect(warnings).toHaveLength(1);
+ });
+
+ it("reads a stored record the persistence layer writes when a gateway drops ids", () => {
+ const search = hostedSearchFromMessage({
+ content: [{ type: "hostedSearch", phase: "web_search_call", status: "completed" }],
+ });
+ expect(search?.replay).toHaveLength(1);
+ const { result, warnings } = withCapturedWarnings(() => restoreHostedSearchReplay(search));
+ expect(result).toEqual([]);
+ expect(warnings).toHaveLength(1);
});
});
diff --git a/packages/agent-runtime/src/hosted-search-replay.ts b/packages/agent-runtime/src/hosted-search-replay.ts
index 924c68c0a..cb94cbbb9 100644
--- a/packages/agent-runtime/src/hosted-search-replay.ts
+++ b/packages/agent-runtime/src/hosted-search-replay.ts
@@ -5,13 +5,46 @@ import type { HostedSearch } from "@pi-desktop/shared";
/**
* 持久化类型保持向后兼容;只在进入模型上下文的边界收敛为正式搜索类型。
- * 旧记录没有 replay 时仍可展示。有 replay 但结构损坏时必须给出本地错误,
- * 不能靠类型断言或静默过滤丢掉 grounding 数据后继续发请求。
+ *
+ * 旧记录没有 replay 时仍可展示。记录带 replay 时分两种情况:容器不是数组
+ * 属于损坏记录,仍按本地错误失败;单个块无法回放则整条 replay 降级为空,
+ * 与该消息"没有 replay"的旧记录一致。
+ *
+ * 持久化层明确允许缺少 blockId 的块——网关丢弃 id 时,展示路径用匿名轮次
+ * 兜底(`native-web-search.ts`)。这类记录升级前可读,不能在升级后让会话的
+ * 每一轮请求都失败:请求级失败无法通过重启或重新打开会话恢复,而搜索回放
+ * 只是该消息上下文的一部分。降级保持可观测,且不复制搜索内容或凭据。
*/
export function restoreHostedSearchReplay(
search: HostedSearch | undefined,
): HostedSearchContent[] {
if (search?.replay === undefined) return [];
if (!Array.isArray(search.replay)) throw new LocalRequestError("context-validation");
- return search.replay.map((block) => normalizeHostedSearchContent(block));
+ try {
+ return search.replay.map((block) => normalizeHostedSearchContent(block));
+ } catch (error) {
+ reportUnreplayableSearchReplay(search.replay, error);
+ return [];
+ }
+}
+
+/**
+ * 只记录块数与阶段:足够定位数据形状,又不把搜索结果或凭据写进日志。
+ */
+function reportUnreplayableSearchReplay(
+ replay: readonly unknown[],
+ error: unknown,
+): void {
+ const phases = [
+ ...new Set(
+ replay
+ .map((block) => (block as { phase?: unknown } | null)?.phase)
+ .filter((phase): phase is string => typeof phase === "string"),
+ ),
+ ];
+ console.warn(
+ `[hosted-search] dropping an unreplayable stored search record ` +
+ `(${replay.length} block(s), phases: ${phases.join(", ") || "none"})`,
+ error,
+ );
}
diff --git a/scripts/e2e/hosted-search-scenarios.mjs b/scripts/e2e/hosted-search-scenarios.mjs
index 323a038c0..4d827fea6 100644
--- a/scripts/e2e/hosted-search-scenarios.mjs
+++ b/scripts/e2e/hosted-search-scenarios.mjs
@@ -191,64 +191,88 @@ export async function runScenarios(bundle, root, timeoutMs, report) {
assert.equal(second.hostCalls.filter((call) => call.method === "session.get").length, 1);
assert.equal(provider.requests.length, 2);
});
- for (const replay of [{ invalid: true }, [{ type: "hostedSearch", phase: "unknown", blockId: "private-fixture-value" }]]) {
- await run(Array.isArray(replay) ? "invalid-search-phase" : "invalid-search-container", () => {
- assert.fail("invalid restored history must never reach the provider");
- }, async ({ provider, start, dir }) => {
- const history = [{
- id: "invalid-history", role: "assistant", content: "stored result", status: "complete",
- createdAt: "2026-09-20T00:00:00.000Z",
- hostedSearch: { status: "completed", rounds: [], replay },
- }];
- // Serve the malformed row to the failing session only: the recovery prompt
- // below opens a clean session that must still be able to run.
- const fixture = fixtureHost({ history: [] });
- const host = (method, params) => method === "session.get" && params.id === "invalid-history"
- ? { session: { id: params.id, messages: history } }
- : fixture(method, params);
- const sidecar = await start("runtime", host);
- const healthBefore = await sidecar.call("sidecar.health");
- assert.equal(healthBefore.runtimes, 0, "a fresh fixture process must not own a live runtime");
- await assert.rejects(sidecar.call("agent.prompt", {
- ...parameters(provider.baseUrl, dir, "invalid-history"), content: "Continue the restored history.",
- }), (error) => {
- const rpc = JSON.parse(error.message);
- assert.equal(rpc.code, -32000);
- assert.equal(rpc.data.errorCode, "INTERNAL");
- assert.equal(rpc.data.retriable, false);
- assert.deepEqual(rpc.data.details, { origin: "local", phase: "context-validation" });
- assert.doesNotMatch(error.message, /private-fixture-value/);
- return true;
- });
- assert.equal(provider.requests.length, 0);
- // The child only ever receives `history` as an RPC JSON copy, so
- // re-serialising the harness-side array proves nothing about the child's
- // memory. What this harness can observe is the Host surface: a rejected
- // restore may only read the session through the runtime constructor's
- // session.get, and may not call any other Host method. In-memory
- // immutability of the restored copy is covered by the source replay
- // tests, not here.
- const restoreCalls = sidecar.hostCalls.slice();
- assert.deepEqual(restoreCalls.filter((call) => call.method !== "session.get"), [],
- "a rejected restore must not issue persistence-mutating Host RPCs");
- assert.equal(restoreCalls.filter((call) => call.method === "session.get").length, 1,
- "restore must read the session exactly once before rejecting");
- const healthAfter = await sidecar.call("sidecar.health");
- assert.equal(healthAfter.ok, true, "invalid history must not terminate the process");
- assert.equal(healthAfter.runtimes, healthBefore.runtimes,
- "a rejected restore must not register or leak a runtime");
- // Same child, clean session: a rejected restore must not wedge recovery.
- const cleanDir = join(dir, "clean-session");
- await mkdir(cleanDir, { recursive: true });
- const clean = await startProvider(cleanDir, () => ({ text: "CLEAN_SESSION_OK" }));
- try {
- await sidecar.prompt(parameters(clean.baseUrl, dir, "clean-after-invalid"), "CLEAN_SESSION_PROMPT");
- assertText(sidecar, "CLEAN_SESSION_OK");
- assert.equal(clean.requests.length, 1, "the recovery session must make exactly one provider request");
- } finally {
- await clean.close();
- }
+ await run("invalid-search-container", () => {
+ assert.fail("a corrupt replay container must never reach the provider");
+ }, async ({ provider, start, dir }) => {
+ const history = [{
+ id: "invalid-history", role: "assistant", content: "stored result", status: "complete",
+ createdAt: "2026-09-20T00:00:00.000Z",
+ hostedSearch: { status: "completed", rounds: [], replay: { invalid: true } },
+ }];
+ // Serve the malformed row to the failing session only: the recovery prompt
+ // below opens a clean session that must still be able to run.
+ const fixture = fixtureHost({ history: [] });
+ const host = (method, params) => method === "session.get" && params.id === "invalid-history"
+ ? { session: { id: params.id, messages: history } }
+ : fixture(method, params);
+ const sidecar = await start("runtime", host);
+ const healthBefore = await sidecar.call("sidecar.health");
+ assert.equal(healthBefore.runtimes, 0, "a fresh fixture process must not own a live runtime");
+ await assert.rejects(sidecar.call("agent.prompt", {
+ ...parameters(provider.baseUrl, dir, "invalid-history"), content: "Continue the restored history.",
+ }), (error) => {
+ const rpc = JSON.parse(error.message);
+ assert.equal(rpc.code, -32000);
+ assert.equal(rpc.data.errorCode, "INTERNAL");
+ assert.equal(rpc.data.retriable, false);
+ assert.deepEqual(rpc.data.details, { origin: "local", phase: "context-validation" });
+ return true;
});
- }
+ assert.equal(provider.requests.length, 0);
+ // The child only ever receives `history` as an RPC JSON copy, so
+ // re-serialising the harness-side array proves nothing about the child's
+ // memory. What this harness can observe is the Host surface: a rejected
+ // restore may only read the session through the runtime constructor's
+ // session.get, and may not call any other Host method. In-memory
+ // immutability of the restored copy is covered by the source replay
+ // tests, not here.
+ const restoreCalls = sidecar.hostCalls.slice();
+ assert.deepEqual(restoreCalls.filter((call) => call.method !== "session.get"), [],
+ "a rejected restore must not issue persistence-mutating Host RPCs");
+ assert.equal(restoreCalls.filter((call) => call.method === "session.get").length, 1,
+ "restore must read the session exactly once before rejecting");
+ const healthAfter = await sidecar.call("sidecar.health");
+ assert.equal(healthAfter.ok, true, "invalid history must not terminate the process");
+ assert.equal(healthAfter.runtimes, healthBefore.runtimes,
+ "a rejected restore must not register or leak a runtime");
+ // Same child, clean session: a rejected restore must not wedge recovery.
+ const cleanDir = join(dir, "clean-session");
+ await mkdir(cleanDir, { recursive: true });
+ const clean = await startProvider(cleanDir, () => ({ text: "CLEAN_SESSION_OK" }));
+ try {
+ await sidecar.prompt(parameters(clean.baseUrl, dir, "clean-after-invalid"), "CLEAN_SESSION_PROMPT");
+ assertText(sidecar, "CLEAN_SESSION_OK");
+ assert.equal(clean.requests.length, 1, "the recovery session must make exactly one provider request");
+ } finally {
+ await clean.close();
+ }
+ });
+
+ // A single stored block this app itself writes when a gateway drops ids is not
+ // a corrupt container: the message must continue without search replay rather
+ // than fail every later turn. The unreplayable block never reaches the provider.
+ await run("invalid-search-phase", (body) => {
+ assert.doesNotMatch(JSON.stringify(body), /private-fixture-value/,
+ "an unreplayable stored block must not be sent to the provider");
+ return { text: "DEGRADED_SEARCH_CONTINUED" };
+ }, async ({ provider, start, dir }) => {
+ const history = [{
+ id: "invalid-history", role: "assistant", content: "stored result", status: "complete",
+ createdAt: "2026-09-20T00:00:00.000Z",
+ hostedSearch: { status: "completed", rounds: [], replay: [
+ { type: "hostedSearch", phase: "unknown", blockId: "private-fixture-value" },
+ ] },
+ }];
+ const fixture = fixtureHost({ history: [] });
+ const host = (method, params) => method === "session.get" && params.id === "invalid-history"
+ ? { session: { id: params.id, messages: history } }
+ : fixture(method, params);
+ const sidecar = await start("runtime", host);
+ await sidecar.prompt(parameters(provider.baseUrl, dir, "invalid-history"), "Continue the restored history.");
+ assertText(sidecar, "DEGRADED_SEARCH_CONTINUED");
+ assert.equal(provider.requests.length, 1, "the turn must continue without the stored search replay");
+ const health = await sidecar.call("sidecar.health");
+ assert.equal(health.ok, true, "a degraded stored record must not terminate the process");
+ });
return results;
}