Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
Merge branch 'main' into fix/duplicate-tool-output
vastsad90a326bd6ad
diff --cc docs/spec/03-runtime/02-agent-runtime.mdindex b1570b8b0,6fed6f68b..9af2c046b--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@@ -698,27 -740,6 +740,27 @@@ criterion-by-criterion report of what w(D608). Anthropic-family endpoints, including DeepSeek's, reject the wholeturn with `tool_use ids must be unique` (issue #718), which leaves the sessionunable to continue.+- The guard compares the wire-visible call id — the part before the `|` that+ separates the Responses item id — and drops an assistant message whole once+ every tool call in it was already claimed, because keeping its residual text+ would leave a message sitting between a call and the result answering it. A+ message that replays a claimed call while carrying a new one keeps its new+ call in place; no writer produces that partial replay, and the guard does not- reorder messages to close the gap it leaves (D613).++ reorder messages to close the gap it leaves (D619).+- The agent loop owns its context array. `prepareNextTurn` hands pi a copy of+ the live state — for a delegate turn boundary too — exactly as pi's own+ `createContextSnapshot()` does for `prompt()` and `continue()`: pi's loop+ appends each streamed assistant message and each tool result to the array it+ was given, while its `message_end` listener appends the same message to+ `state.messages`, so handing over the live array stored every message of a+ run's later iterations twice. The next turn's first request was built from+ that array, and the duplicate of an assistant message carrying text plus a+ tool call survived as a text-only clone between the call and its result —+ pi-ai then closed the still-pending call with a synthesized output next to the+ real one, and the endpoint rejected the turn with+ `Duplicate tool output for call_id`. In a delegate the same doubling doubled+ the estimate at the following boundary and left the trailing row a fallback- carries onto a model it cannot resume from (D613).++ carries onto a model it cannot resume from (D619).- Restored checkpoints clear provider usage from retained assistant messagesfor budgeting. That usage measured the pre-compacted request and must notmake the summary + tail appear as large as the discarded context.diff --cc docs/spec/06-delivery/04-e2e-test-plan.mdindex 523b0f9e8,9d95e4860..b857f4e96--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@@ -14409,32 -14426,6 +14429,32 @@@ the latest destination. These assertion- **Status:** Unit-covered; no end-to-end driver issues a real provider requestagainst a duplicated transcript.+### E2E-RUNTIME-loop-context-ownership++- **Preconditions:** A deterministic provider fixture that answers the first two+ rounds with one tool call each and stops the turn after the second round the+ way a user Stop does. No real provider credentials.+- **Steps:** Send one prompt so the runtime runs both tool rounds and ends the+ turn on a tool round. Send a second prompt. Read the state the runtime kept and+ the outgoing request the fixture received.+- **Expected:** The kept state holds each streamed assistant message and each tool+ result exactly once; no result is separated from the call it answers; the+ fixture's request carries exactly one result per call. No duplicate-drop line is+ logged, because the request guard had nothing to drop.+- **Specs:** `03-runtime/02-agent-runtime.md` §5c,- `08-meta/decisions-log.md` D613.++ `08-meta/decisions-log.md` D619.+- **Acceptance:** C (conversation and stream), Quality.+- **Milestone:** Post-MVP regression coverage.+- **Automation:** `packages/agent-runtime/src/runtime.test.ts` (loop context+ ownership) drives the real pi loop through `runtime.prompt()` and reads the+ view `convertToLlm` handed the provider; `subagent-loop-context.test.ts` covers+ the delegate's turn boundary. The adapter's own output is out of reach of both,+ so `tool-call-dedupe.test.ts` (request wire contract) drives pi-ai's message+ transform directly to pin the two outputs one call id receives when a request+ separates a call from its result.+- **Status:** Unit-covered; no end-to-end driver issues a real provider request+ from a context the loop appended to.+### E2E-MCP-HTTP-ACK — HTTP acknowledgement and authorization status- **Preconditions**: A local mock Streamable HTTP server returns JSON fordiff --cc docs/spec/08-meta/decisions-log.mdindex 458adc5e3,72cdb22e8..1b11b61df--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@@ -6596,37 -6610,138 +6610,172 @@@ that was sitting at the bottom — incl`apps/desktop/test/image-generation-default.test.mjs`, with`provider-model-config.test.mjs` asserting the add branch consults them.- ## 2026-09-22 — The loop owns its context array (D613)++## 2026-09-22 — The loop owns its context array (D619)++- A turn whose later iterations ran tools left `state.messages` holding two copies+ of every message those iterations appended, and the next turn's first request+ was assembled from that array. The duplicate of an assistant message that+ carried text plus a tool call survived the request guard (D608) as a text-only+ clone sitting between the call and the result answering it; pi-ai then closed+ the still-pending call with a synthesized "No result provided" output next to+ the real one, so one call id carried two outputs and the endpoint rejected the+ whole turn with `Duplicate tool output for call_id` (HTTP 400, not retriable).+ The array is reused, so every following turn failed the same way and `继续`+ could not recover the session.+- pi-ai's loop appends each streamed assistant message and each tool result to+ the context it was handed, while its own `message_end` listener appends the+ same message object to `state.messages`. `rebuiltAgentContext()` returned that+ live array, so both appends landed in one array; it now returns a copy, exactly+ like pi's own `createContextSnapshot()` does for `prompt()` and `continue()`.+ The delegate's turn boundary handed over the same live array+ (`subagent.ts` `prepareNextTurn`) and now copies too. The loop's view and+ `state.messages` carry the same messages in the same order at each message+ boundary, they are simply no longer the same array — which is what keeps the+ duplicates out of the next request.+- The request guard at `convertToLlm` (D608) now matches what the provider+ validates: call and result ids are compared by their wire-visible part, a+ result whose item half disagrees with its call is paired to the call's id, and+ an assistant message whose tool calls were all already claimed is dropped whole+ instead of being kept as the clone that separates a call from its result. The+ drop log line also states how many messages were removed. A message that+ replays one claimed call while carrying a new one is left in place with its new+ call, the only id sharing the guard accepts; no writer reaches that shape.+- No provider transport, host protocol, version, storage migration, transcript+ rewrite, or compaction/retention/budget rule changes.+ `03-runtime/02-agent-runtime.md` §5c and+ E2E-RUNTIME-loop-context-ownership record the contract and its coverage.+ ## 2026-09-21 — Bound Desktop trusted-extension lifecycle waits++ - Apply the existing 30-second handler budget to notification, startup and+ shutdown handlers as well as result handlers; module loading and factory+ initialization each use the same budget. This changes previously unbounded+ waits, including event handlers waiting for a UI answer.+ - Abort retires current waits; disposal rejects new dispatches and runs shutdown+ once. Late settlements cannot supply results to the retired dispatch. Existing+ fail-open error handling, result folding, plugin ownership and permissions+ remain unchanged. In-process code is not forcibly terminated.+ - Deferred events remain registrable and now appear in existing diagnostics.+ See `07-plugins/16-trusted-extensions.md` §6 and+ `E2E-HOOKS-cancel-and-dispose`.+ ## 2026-09-22 — An unreadable command source refuses a slash submission (D613, issue #795)++ - Composer send-time resolution read the merged command list and swallowed a+ failure as `null`, which the submit path could not tell apart from "no such+ command". `/compact` typed while that IPC read failed was therefore sent to the+ model as literal prompt text, and the model acted on it as an instruction.+ - Resolution now answers with three outcomes instead of one nullable value:+ resolved (builtin/plugin/extension dispatch), unknown (templates, aliases, and+ id-less entries continue as prompt text), and unavailable. Unavailable refuses+ the submission, keeps the draft, and shows+ `chat.slashCommandSourceUnavailable`. The failed read leaves the TTL cache+ cold, so the next submit retries it; a warm cache still resolves through a+ source blip.+ - The refusal is fail-closed on purpose: only the command source can say whether+ `/name` is a control command, so while it cannot be read a `name` that looks+ like plain text is refused rather than guessed. Templates and genuinely unknown+ aliases keep the old prompt path. Pinned by+ `apps/desktop/test/slash-command-source.test.mjs` and+ `03-runtime/01-ipc-protocol.md` §13c.++ ## 2026-09-22 — A manual compaction has its own transport deadline and a durable verdict (D614, issue #795)++ - `agent.compact` is a blocking RPC that spends a whole model summary request+ inside the sidecar: pi serializes the conversation, streams the summary, and+ retries a transient failure. It ran under the flat 130s transport default, so a+ ~158s compaction on an 888KB context ended as `sidecar RPC timeout` while the+ sidecar kept working and persisted the checkpoint — the user was told the+ compaction failed, and the next turn proved it had succeeded.+ - The deadline is now derived from the ceilings the sidecar actually enforces:+ one stream watchdog (180s) per attempt, `1 + 3` attempts, the 2s/4s/8s retry+ backoff, and transport slack — `AGENT_COMPACT_RPC_TIMEOUT_MS`, deliberately+ per-method rather than a wider global default.+ - Either host path (Electron `agentCompact` IPC and `RuntimeService.compact`)+ also stops treating a transport timeout as the sidecar's verdict: it re-reads+ the durable `session.compaction` record and reports success when a new+ checkpoint landed, logs the mismatch, and rethrows the timeout otherwise. A+ verdict the sidecar reported itself is never reconciled. Pinned by+ `packages/host-runtime/src/runtime-service.test.ts`,+ `packages/shared/src/protocol.test.ts`,+ `apps/desktop/test/plugin-timeout-budgets.test.mjs`, and+ `03-runtime/01-ipc-protocol.md` §5.4.++ ## 2026-09-22 — An empty transcript read is retried and never cached (D615, issue #795)++ - The renderer treated every durable `session.get` window as the truth, and+ cached it. A window that came back empty for a session with thousands of+ messages — the host answers such a read from a transcript file it may be+ rewriting — was stored as an empty snapshot, hover prefetch re-served it, and+ the pane stayed blank until the app restarted. Nothing distinguished a failed+ or stale read from an empty conversation, and no path retried one.+ - A read is now judged against the session's own count: zero messages for a+ session the sidebar counts as having history triggers one more read, then keeps+ the snapshot the user already has, and otherwise reports+ `chat.sessionTranscriptEmpty`. The empty page is never written to the+ transcript cache, so a hover prefetch cannot poison every later open.+ - This is a defense, not the host-side root cause: the transcript rewrite is the+ reporter's 0.15.1 storage layout, and the read side still answers "session+ exists, no messages" instead of reporting an unreadable transcript. See+ `04-ux/09-interaction-patterns.md` §Session isolation across tabs.++ ## 2026-09-22 — A renderer that never reaches its first state gets a bounded surface and a quit channel (D616)++ - The renderer's startup had no timeout of its own: `bootstrap()` either+ publishes the initial state or nothing, so one read that never settled left the+ window on the boot surface with no menu, no data, and nothing to act on except+ force-quitting the process (issue #831). The renderer now watches its own wait.+ `STARTUP_SLOW_HINT_MS` (30s) adds logs, diagnostics, and quit to the boot+ surface without calling the boot a failure; `STARTUP_STALLED_MS` (180s) turns it+ into the recovery surface, which also offers a retry that re-runs `bootstrap()`.+ - Both bounds sit above the main↔host RPC ceiling (`DEFAULT_RPC_TIMEOUT_MS`,+ 130s), so a slow but successful boot is never read as a failure, and the+ watchdog never cancels the startup it watches: a boot that finishes replaces the+ surface with the shell. The recovery surface replaces the splash (exactly one+ boot surface is mounted), and the renderer-drawn window controls stay above it,+ so a frameless Windows/Linux window can always be closed.+ - The renderer gains the quit channel `pi-desktop/app/quit` (`api.quitApp()`),+ whose handler calls `app.quit()` exactly like the Quit menu item, so the ordered+ shutdown, the confirmation dialog, and the close behavior stay the ones the app+ already has. See `03-runtime/07-process-model.md` §3 and E2E-076.++ ## 2026-09-22 — A failed compaction keeps the recent window (D617, issue #827)++ - An automatic compaction whose summary request failed installed a+ retained-tail checkpoint that carried at most the latest user message, and a+ rebuild narrowed a stored checkpoint's tail the same way. A long turn+ therefore reached the next model request as one user sentence: the reported+ session lost roughly 168 messages (3 user / 34 assistant / 131 tool) between+ two checkpoints while the transcript on disk and the UI row stayed intact.+ - The fallback now retains the real recent window — the newest contiguous+ messages of the compacted range, every role, bounded by the keep-recent+ target and by what the carried summary and the recovery notice leave — and+ marks it with `details.retainedTailShape`, so a rebuild replays it. A+ checkpoint without the marker (every successful checkpoint, and every record+ written before it existed) still normalizes to the latest user message. An+ `active_turn` fallback also keeps the active task's user message when the+ window cannot hold it, the fallback drops the assistant messages pi drops+ anyway and any tool result whose call is not in the window, and+ `details.failureReason` records `no_new_history` / `summary_budget` /+ `summary_provider` / `checkpoint_oversized` instead of provider error text.+ - A summary prompt that is still too large after the single reduced pass is no+ longer skipped: the range is split into contiguous chunks that each fit, at+ most 16 requests, each carrying the previous chunk's summary, and the+ checkpoint reports the summed usage of the requests that produced it. Only an+ empty range, or one past that request bound, still falls back on budget+ grounds. See ADR 0302, `03-runtime/02-agent-runtime.md`, ADR 0049, ADR 0282.++ ## 2026-09-22 — pi's file-op collector is fed the names it reads (D618, issue #827)++ - A checkpoint's `readFiles` / `modifiedFiles`, and the `<read-files>` section a+ summary appends, come from pi's own `extractFileOpsFromMessage`, which switches+ on the lowercase names `read` / `write` / `edit` — the names pi's tools carry.+ PI-Desktop registers `Read` / `Write` / `Edit`, so the collector matched+ nothing and every checkpoint reported an empty file list; issue #827 turned+ this up while reading a compaction report.+ - The conversion stays on our side of the boundary. `withPiFileOpToolNames`+ copies the entries handed to pi's `prepareCompaction` with exactly those three+ names respelled; no stored byte changes — a transcript, a checkpoint and a+ rebuilt context keep our names — and the input array comes back untouched when+ no such call is present, so the common path allocates nothing.+ - Only those three are converted. pi's collector reads nothing else, so `Grep`,+ `Glob`, `Bash`, plugin and MCP names keep the spelling we register, and the+ summarized text changes only where pi consumes the name.diff --cc docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex f35d4178f,37f5c964e..b8dc4f20a--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@@ -540,15 -571,6 +571,15 @@@ Goal 批准所承诺的内容与 Plan �对每个 `toolCall` id 只保留第一次出现,丢弃其后重复的调用或结果,使提供商校验的「一调用一结果」配对保持完整;没有重复的请求原样返回。一旦发生丢弃,会在 `agent` 日志通道上报告一次,带上会话与 id(D608)。Anthropic 系端点(含 DeepSeek)会以 `tool_use ids must be unique` 拒绝整个回合(issue #718),使该会话无法继续。+- 守卫按“上线的 id”比较调用与结果,即 Responses item id 之前、以 `|` 分隔的那一段;当一条辅助消息里的工具调用全部已被更早的消息占有时,+ 整条消息被丢弃,因为保留它剩下的文本会把一条消息塞进调用与回答它的结果之间。若一条消息在复写已占用调用的同时还带一个新调用,则保留该- 消息及其新调用;目前没有写入方会产生这种部分复写,守卫也不会重排消息来填补它留下的空隙(D613)。++ 消息及其新调用;目前没有写入方会产生这种部分复写,守卫也不会重排消息来填补它留下的空隙(D619)。+- 智能体循环拥有自己的上下文数组。`prepareNextTurn` 交给 pi 的是实时状态的副本(委托侧的回合边界同样如此),与 pi 自己的+ `createContextSnapshot()` 在 `prompt()`/`continue()` 里的做法一致:pi 的循环会把每个流式辅助消息与每个工具结果 push 进它拿到的+ 数组,而它的 `message_end` 监听器又把同一消息 push 回 `state.messages`,因此交出活数组会把一个回合中较晚迭代的每条消息都存两份。+ 下一回合的首个请求正是用该数组组装的,其中“带文本与工具调用的辅助消息”的重复项会残留为只剩文本的克隆,卡在调用与结果之间——pi-ai+ 随后会为这个仍处于待配对的调用合成一条输出,与真实结果并列,端点以 `Duplicate tool output for call_id` 拒绝整个回合。在委托运行时,- 同样的重复还会让下一个边界的估算翻倍,并让备用模型拿到的末行无法被 `continue()` 续跑(D613)。++ 同样的重复还会让下一个边界的估算翻倍,并让备用模型拿到的末行无法被 `continue()` 续跑(D619)。- 视觉运行时只从会话绑定的附件、scratch 与项目根目录中水合持久化的图片引用。处于 10 MB 内联安全上限之内的图片会成为临时的 pi-ai 图片块;超限或不可用的图片则退化为安全的 `@path` 回退。超限历史的水合会直接复制文件,不会先把内容diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 4158ee14b,a52de6b78..a78e423c6--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@@ -8466,23 -8475,8 +8477,23 @@@ the latest destination. These assertion**里程碑:** Post-MVP 回归覆盖。- **自动化:** `packages/agent-runtime/src/runtime.test.ts` 用真实的运行时覆盖两半:重复历史(丢弃 + 一行日志)与唯一历史(同一对象、无日志)。+- **状态:** 单元测试覆盖;没有端到端驱动对重复转录发出真实提供商请求。+### E2E-RUNTIME-loop-context-ownership++- **先决条件:** 一个确定性提供商夹具:前两轮各回一次工具调用,并在第二轮之后像用户 Stop 那样结束回合;不使用真实凭据。+- **步骤:** 发一条提示,让运行时跑完两轮工具调用并在工具轮上结束回合;再发第二条提示。读取运行时保留的状态与夹具收到的出站请求。+- **预期:** 保留的状态里每个流式辅助消息与每个工具结果都只有一份;没有结果与它回答的调用被隔开;夹具收到的请求对每次调用只带一个结果。+ 不产生去重日志行,因为请求守卫没有任何东西需要丢弃。- - **规格:** 03-runtime/02-agent-runtime §5c、08-meta/decisions-log D613。**验收:** C(对话与流)、品质。++- **规格:** 03-runtime/02-agent-runtime §5c、08-meta/decisions-log D619。**验收:** C(对话与流)、品质。+ **里程碑:** Post-MVP 回归覆盖。+- **自动化:** `packages/agent-runtime/src/runtime.test.ts`(loop context ownership)通过 `runtime.prompt()` 驱动真实 pi 循环,+ 并读取 `convertToLlm` 交给提供商的视图;`subagent-loop-context.test.ts` 覆盖委托侧的回合边界。两者都到不了适配器自身的输出,+ 因此由 `tool-call-dedupe.test.ts`(request wire contract)直接驱动 pi-ai 的消息变换,固定「请求把调用与结果隔开时同一个 call id+ 会拿到两条输出」这一机制。+- **状态:** 单元测试覆盖;没有端到端驱动从「循环追加过的上下文」构建新回合的请求。+### E2E-MCP-HTTP-ACK — HTTP acknowledgement and authorization status- **Preconditions**: A local mock Streamable HTTP server returns JSON fordiff --cc docs/zh-CN/spec/08-meta/decisions-log.mdindex d6f0c59c5,b0eb74014..505042f49--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@@ -4678,21 -4689,99 +4689,117 @@@ that amendment are retired by ADR 0268`apps/desktop/test/image-generation-default.test.mjs` 固定,`provider-model-config.test.mjs` 断言新增分支会走这两个判断。- ## 2026-09-22 — 循环拥有自己的上下文数组(D613)++## 2026-09-22 — 循环拥有自己的上下文数组(D619)++- 当某个回合的较晚迭代跑了工具后,`state.messages` 会把那些迭代追加的每条消息存两份,而下一回合的首个请求正是用该数组组装的。+ 其中“带文本与工具调用的辅助消息”的重复项在请求守卫(D608)之后残留为只剩文本的克隆,卡在调用与回答它的结果之间;pi-ai 随后会为+ 这个仍处于待配对的调用合成一条 “No result provided” 输出,与真实结果并列,于是同一个 call id 带上了两条输出,端点以+ `Duplicate tool output for call_id`(HTTP 400,不可重试)拒绝整个回合。该数组会被复用,因此其后每个回合都以同样方式失败,+ `继续` 也无法让会话恢复。+- pi-ai 的循环会把每个流式辅助消息与每个工具结果 push 进它拿到的上下文,而它自己的 `message_end` 监听器又把同一个消息对象 push 回+ `state.messages`。`rebuiltAgentContext()` 返回的正是这个活数组,两次 push 因此落在同一个数组里;现在它返回副本,与 pi 自己的+ `createContextSnapshot()` 在 `prompt()` 与 `continue()` 里的做法一致。委托侧的回合边界此前交出的也是同一个活数组+ (`subagent.ts` 的 `prepareNextTurn`),现已同样改为副本。每个消息边界处循环视图与 `state.messages` 携带同样的消息、同样的顺序,+ 只是不再是同一个数组——这正是把重复项挡在下一回合请求之外的原因。+- `convertToLlm` 处的请求守卫(D608)改为与提供商实际校验的对象一致:调用与结果的 id 按“上线可见”的那一段比较;当结果与调用在 item+ 段上不一致时,结果改挂到调用的 id 上;当一条辅助消息里的工具调用全部已被占用时,整条消息被丢弃,而不再保留那个把调用与结果隔开的克隆。+ 丢弃日志同时给出被移除的消息条数。若一条消息在复写某个已占用调用的同时还带一个新调用,则保留该消息及其新调用——这是守卫接受的唯一一种+ id 复用;目前没有写入方会产生这种部分复写。+- 不涉及提供商传输、宿主协议、版本、存储迁移、转录重写,也不改变压缩/保留/预算规则。+ `03-runtime/02-agent-runtime.md` §5c 与 E2E-RUNTIME-loop-context-ownership 记录了该契约与覆盖情况。+ ## 2026-09-21 — 限制 Desktop 可信扩展生命周期等待++ - 现有 30 秒处理器预算扩展到通知、启动和关闭事件;模块加载、工厂初始化分别使用+ 同一预算。此前无界的等待变为有界,事件内等待 UI 回答也受此限制。+ - 中止使当前等待失效;销毁拒绝新派发且只执行一次关闭。迟到完成不能向旧派发提供+ 结果。既有失败继续、结果归并、插件归属和权限不变,不强制终止进程内代码。+ - 未接通事件仍可注册,并在现有诊断中显示。参见+ `07-plugins/16-trusted-extensions.md` §6 与 `E2E-HOOKS-cancel-and-dispose`。+ ## 2026-09-22 —— 指令源不可读时拒绝斜杠提交(D613,issue #795)++ - Composer 在发送时读取合并后的指令列表,并把失败吞成 `null`,而提交路径无法把它与+ “没有这个指令”区分开。于是在该 IPC 读取失败时输入的 `/compact` 会作为字面提示词发给+ 模型,模型据此把它当成指令执行。+ - 解析现在返回三种结果,而不再是一个可空值:已解析(内置 / 插件 / 扩展分发)、未知+ (模板、别名与无 id 条目继续走提示词路径)、不可用。不可用时拒绝提交、保留草稿并显示+ `chat.slashCommandSourceUnavailable`。失败的读取不写 TTL 缓存,因此下一次发送会重试;+ 缓存仍热时,一次数据源抖动不会影响解析。+ - 拒绝是刻意 fail-closed:只有指令源能判断 `/name` 是否为控制指令,因此读不到时,看起来像+ 普通文本的名称也会被拒绝,而不是靠猜测。模板与确实未知的别名保持原有提示词路径。由+ `apps/desktop/test/slash-command-source.test.mjs` 与+ `03-runtime/01-ipc-protocol.md` §13c 固定。++ ## 2026-09-22 —— 手动压缩有自己的传输超时与持久化判定(D614,issue #795)++ - `agent.compact` 是阻塞式 RPC,会在 sidecar 内消耗一次完整的模型摘要请求:pi 序列化会话、+ 流式生成摘要,并重试瞬时失败。它此前沿用扁平的 130 秒传输默认值,因此 888KB 上下文约+ 158 秒的压缩以 `sidecar RPC timeout` 结束,而 sidecar 仍在继续工作并落盘了检查点——用户+ 被告知压缩失败,而下一个回合证明它其实成功了。+ - 超时现在由 sidecar 真正执行的预算推导:每次尝试的流空转看门狗(180 秒)、`1 + 3` 次+ 尝试、2/4/8 秒重试退避,以及传输余量 —— 即 `AGENT_COMPACT_RPC_TIMEOUT_MS`,刻意按方法+ 区分,而不是放宽全局默认值。+ - 两条宿主路径(Electron 的 `agentCompact` IPC 与 `RuntimeService.compact`)也不再把手动+ 压缩的传输超时当作 sidecar 的判定:它们会重新读取持久化的 `session.compaction` 记录,+ 发现新检查点已落盘就报告成功、记录该不一致,否则原样抛出超时。sidecar 自己报告的判定+ 绝不会被这样改写。由 `packages/host-runtime/src/runtime-service.test.ts`、+ `packages/shared/src/protocol.test.ts`、+ `apps/desktop/test/plugin-timeout-budgets.test.mjs` 与+ `03-runtime/01-ipc-protocol.md` §5.4 固定。++ ## 2026-09-22 —— 空记录读取会重试,且绝不入缓存(D615,issue #795)++ - 渲染层把每一次持久化 `session.get` 窗口都当真,并写入缓存。当宿主正在重写记录文件时,+ 对拥有数千条消息的会话返回的空窗口被当成“空快照”存下,侧边栏悬停预取又反复送出它,+ 于是面板一直空白,只有重启应用才能恢复。此前没有任何逻辑区分“读取失败或读到陈旧数据”+ 与“真的空会话”,也没有任何路径重试。+ - 现在的判断依据是会话自己的计数:若侧边栏计为有历史的会话返回零条消息,就再读一次,+ 随后保留用户已有的快照,否则显示 `chat.sessionTranscriptEmpty`。这类空页绝不会写入记录+ 缓存,因此悬停预取不会污染之后每次打开。+ - 这是防御措施,而不是宿主侧根因:记录重写是报告者 0.15.1 的存储布局,而读取侧仍然返回+ “会话存在但没有消息”,而不是报告记录不可读。见 `04-ux/09-interaction-patterns.md`+ §跨选项卡的会话隔离。++ ## 2026-09-22 —— 从未拿到初始状态的渲染器有了有界表面与退出通道(D616)++ - 渲染器的启动过程本身没有超时:`bootstrap()` 要么发布初始状态,要么什么都不发布,+ 因此一次始终没有落地的读取会让窗口一直停在启动表面上——没有菜单、没有数据,除了+ 强杀进程无事可做(issue #831)。渲染器现在自己监视这段等待:+ `STARTUP_SLOW_HINT_MS`(30 秒)在不判定启动失败的前提下为启动表面加上日志、诊断与+ 退出,`STARTUP_STALLED_MS`(180 秒)把它变成恢复表面,后者还提供重跑+ `bootstrap()` 的重试。+ - 两个界限都高于 main↔host 的 RPC 上限(`DEFAULT_RPC_TIMEOUT_MS`,130 秒),因此慢+ 但成功的启动不会被读成失败;看门狗从不取消它所监视的启动,成功完成的启动会用 shell+ 替换该表面。恢复表面替换启动画面(同一时刻只挂载一个启动表面),渲染器绘制的窗口+ 控制按钮保持在其之上,因此无边框的 Windows/Linux 窗口始终可以关闭。+ - 渲染器新增退出通道 `pi-desktop/app/quit`(`api.quitApp()`),其处理函数与“退出”+ 菜单项一样调用 `app.quit()`,因此有序关停、确认对话框和关闭行为都仍是应用已有的+ 那一套。参见 `03-runtime/07-process-model.md` §3 与 E2E-076。++ ## 2026-09-22 —— 摘要失败的压缩保留真实近期窗口(D617,issue #827)++ - 自动压缩的摘要请求失败时安装的保留尾部检查点最多只带一条最新用户消息,重建存储的+ 检查点也会以同样方式收窄尾部。于是在一条长回合里,下一次模型请求只剩一句用户话:+ 报告中的会话在两次检查点之间丢掉约 168 条消息(3 条用户 / 34 条助手 / 131 条工具),+ 而磁盘上的转录本与界面行看起来完好。+ - 回退现在保留真实的近期窗口——压缩范围内最新的连续消息,包含所有角色,上限为+ keep-recent 目标,以及携带摘要与恢复提示之后安全预算剩余的空间——并用+ `details.retainedTailShape` 标记,使重建时回放整窗。没有该标记的检查点(每个成功+ 检查点,以及标记出现之前写入的记录)仍归一化为只保留最新的用户消息。`active_turn`+ 回退还会在窗口装不下时保留当前任务的用户消息;回退会丢弃 pi 本来就会丢的助手消息,+ 以及调用不在窗口内的工具结果;`details.failureReason` 记录 `no_new_history` /+ `summary_budget` / `summary_provider` / `checkpoint_oversized`,而不是提供商错误文本。+ - 单次缩减后仍过大的摘要提示不再被跳过:范围会被切成每片都能放下的连续分片,最多 16 次+ 请求,每次携带上一片的摘要,检查点报告这些请求的用量总和。只有空范围或超过该请求上限+ 的范围才因预算原因回退。见 ADR 0302、`03-runtime/02-agent-runtime.md`、ADR 0049、ADR 0282。++ ## 2026-09-22 —— 交给 pi 的文件操作收集器使用它认识的拼写(D618,issue #827)++ - 检查点的 `readFiles` / `modifiedFiles` 以及摘要追加的 `<read-files>` 段来自 pi 自己的+ `extractFileOpsFromMessage`,它只匹配小写名字 `read` / `write` / `edit`——即 pi 自己+ 工具的名字。PI-Desktop 注册的是 `Read` / `Write` / `Edit`,因此该收集器什么都匹配不到,+ 每个检查点都报出空文件清单;issue #827 在排查压缩报告时发现了这一点。+ - 转换只发生在边界这一侧:`withPiFileOpToolNames` 把交给 pi `prepareCompaction` 的条目+ 复制一份,并改写这三个名字的拼写。存储字节不变——transcript、检查点与重建后的上下文都+ 保留我们的拼写——而且当历史里没有这类调用时原样返回入参数组,常见路径不产生任何分配。+ - 只转换这三个名字。pi 的收集器不读其它名字,因此 `Grep`、`Glob`、`Bash`、插件与 MCP 名字+ 保持我们注册的拼写,被摘要的文本只在 pi 真正消费该名字的地方发生变化。diff --cc packages/agent-runtime/src/runtime.test.tsindex ddd57a78b,91ab2ca8d..74e29c975--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@@ -8884,198 -9011,313 +9013,506 @@@ describe("context estimate calibration"});});- describe("DesktopAgentRuntime loop context ownership (D613)", () => {++describe("DesktopAgentRuntime loop context ownership (D619)", () => {+ /**+ * Rounds 1 and 2 answer with a tool call and round 3 closes the turn; with+ * `stopAfterFirstRound` the run ends on the tool round instead, the way a+ * user Stop does. Every round records the request view the provider saw.+ */+ function scriptCallRounds(+ runtime: DesktopAgentRuntime,+ requests: AgentMessage[][],+ options: { stopAfterRound?: number } = {},+ ): void {+ let round = 0;+ (runtime as any).models = {+ streamSimple: (_model: unknown, context: { messages: AgentMessage[] }) => {+ round += 1;+ const current = round;+ requests.push([...context.messages]);+ if (current === options.stopAfterRound) {+ runtime.requestGracefulStop();+ }+ const withCall = current <= 2;+ const message = assistantMessage({+ content: withCall+ ? [+ { type: "text", text: `round ${current}` },+ {+ type: "toolCall",+ id: `call-${current}`,+ name: "plugin_demo_probe",+ arguments: {},+ },+ ]+ : [{ type: "text", text: `round ${current}` }],+ stopReason: withCall ? "toolUse" : "stop",+ }) as unknown as AssistantMessage;+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "start", partial: message });+ stream.push({+ type: "done",+ reason: withCall ? "toolUse" : "stop",+ message,+ });+ stream.end(message);+ });+ return stream;+ },+ };+ }++ function probeRuntime(+ requests: AgentMessage[][],+ options: { stopAfterRound?: number } = {},+ ): DesktopAgentRuntime {+ const runtime = createRuntime({+ host: {+ call: vi.fn(async (method: string) =>+ method === "tools.execute"+ ? {+ ok: true,+ content: {+ content: [{ type: "text", text: "probe ok" }],+ details: {},+ },+ }+ : undefined,+ ),+ } as never,+ pluginTools: [+ { name: "plugin_demo_probe", description: "probe", parameters: {} },+ ],+ });+ scriptCallRounds(runtime, requests, options);+ return runtime;+ }++ function textBlocks(messages: AgentMessage[]): string[] {+ return messages.flatMap((message) =>+ message.role === "assistant"+ ? ((message as { content: unknown[] }).content ?? [])+ .filter(+ (block): block is { type: string; text: string } =>+ typeof block === "object" &&+ block !== null &&+ (block as { type?: string }).type === "text",+ )+ .map((block) => block.text)+ : [],+ );+ }++ function toolCallIds(messages: AgentMessage[]): string[] {+ return messages.flatMap((message) =>+ message.role === "assistant"+ ? ((message as { content: unknown[] }).content ?? [])+ .filter(+ (block): block is { type: string; id: string } =>+ typeof block === "object" &&+ block !== null &&+ (block as { type?: string }).type === "toolCall",+ )+ .map((block) => block.id)+ : [],+ );+ }++ function resultIds(messages: AgentMessage[]): string[] {+ return messages+ .filter((message) => message.role === "toolResult")+ .map((message) => (message as { toolCallId?: string }).toolCallId ?? "");+ }++ /** Every result has to sit directly behind the assistant that carries its call. */+ function expectResultsFollowTheirCalls(messages: AgentMessage[]): void {+ for (let index = 0; index < messages.length; index += 1) {+ const message = messages[index] as { role?: string; toolCallId?: string };+ if (message.role !== "toolResult") continue;+ let previous = index - 1;+ while (+ previous >= 0 &&+ (messages[previous] as { role?: string }).role === "system"+ ) {+ previous -= 1;+ }+ const carrier = messages[previous] as { role?: string; content?: unknown[] };+ expect(carrier?.role).toBe("assistant");+ expect(+ (carrier?.content ?? []).some(+ (block) =>+ typeof block === "object" &&+ block !== null &&+ (block as { type?: string }).type === "toolCall" &&+ (block as { id?: string }).id === message.toolCallId,+ ),+ ).toBe(true);+ }+ }++ it("stores one copy of every message the loop appends", async () => {+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ const requests: AgentMessage[][] = [];+ const runtime = probeRuntime(requests);++ await runtime.prompt("first task", "user-1", "turn-1");++ // The loop appends the streamed assistant message and the tool results to+ // the context it was handed; pi's `message_end` listener appends the same+ // object to the state. Sharing one array stored every message of the- // later rounds twice (D613).++ // later rounds twice (D619).+ const state = (runtime as any).agent.state.messages as AgentMessage[];+ expect(textBlocks(state)).toEqual(["round 1", "round 2", "round 3"]);+ expect(toolCallIds(state)).toEqual(["call-1", "call-2"]);+ expect(resultIds(state)).toEqual(["call-1", "call-2"]);+ // Nothing was duplicated, so the request guard had nothing to report.+ const log = stderr.mock.calls.map(([chunk]) => String(chunk)).join("");+ expect(log).not.toContain("duplicate tool call");++ await runtime.dispose();+ } finally {+ stderr.mockRestore();+ }+ });++ it("opens the next turn from a stopped tool round without guard repairs", async () => {+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ const requests: AgentMessage[][] = [];+ const runtime = probeRuntime(requests, { stopAfterRound: 2 });++ // A Stop ends the run on the second tool round, so those messages are the+ // ones the next turn's first request is built from — the request that- // production rejected with `Duplicate tool output for call_id` (D613).++ // production rejected with `Duplicate tool output for call_id` (D619).+ await runtime.prompt("first task", "user-1", "turn-1");++ requests.length = 0;+ await runtime.prompt("second task", "user-2", "turn-2");++ // `streamSimple` sees the view `convertToLlm` produced, so this is the+ // request the guard let through unrepaired, not the adapter's output: the+ // second output pi-ai synthesizes for an unanswered call is pinned+ // directly in `tool-call-dedupe.test.ts` (request wire contract).+ const wire = requests[0]!;+ expect(toolCallIds(wire)).toEqual(["call-1", "call-2"]);+ expect(resultIds(wire)).toEqual(["call-1", "call-2"]);+ expectResultsFollowTheirCalls(wire);+ const log = stderr.mock.calls.map(([chunk]) => String(chunk)).join("");+ expect(log).not.toContain("duplicate tool call");++ await runtime.dispose();+ } finally {+ stderr.mockRestore();+ }+ describe("compaction fallback retention (#827)", () => {+ function messageEntry(+ id: string,+ parentId: string | null,+ message: unknown,+ seq: number,+ ) {+ return {+ type: "message" as const,+ id,+ seq,+ parentId,+ timestamp: Date.parse("2026-09-21T18:00:00Z") + seq * 1_000,+ message,+ };+ }++ function userNote(text: string, timestamp: number) {+ return { role: "user", content: [{ type: "text", text }], timestamp };+ }++ function assistantNote(text: string, timestamp: number) {+ return { ...assistantMessage({ content: [{ type: "text", text }] }), timestamp };+ }++ /**+ * `toolName` is what pi's file-operation extraction matches on, and it knows+ * the lowercase names: a chunk test that asserts the file list has to use one.+ */+ function toolStep(ids: string[], timestamp: number, toolName = "Read") {+ return {+ ...assistantMessage({+ content: ids.map((id, index) => ({+ type: "toolCall" as const,+ id,+ name: toolName,+ arguments: { path: `large-${index}.txt` },+ })),+ stopReason: "toolUse",+ }),+ timestamp,+ };+ }++ function toolOutput(toolCallId: string, text: string, timestamp: number) {+ return {+ role: "toolResult" as const,+ toolCallId,+ toolName: "Read",+ content: [{ type: "text" as const, text }],+ isError: false,+ timestamp,+ };+ }++ function appendedCheckpoint(host: { call: ReturnType<typeof vi.fn> }) {+ const call = host.call.mock.calls.find(+ ([method]) => method === "session.appendCompaction",+ );+ return (call?.[1] as any)?.compaction;+ }++ function failingSummary(runtime: DesktopAgentRuntime) {+ return vi.spyOn(runtime as any, "generateCompaction").mockResolvedValue({+ ok: false,+ error: {+ code: "summarization_failed",+ message: "provider terminated the summary request",+ },+ });+ }++ function replayedMessages(runtime: DesktopAgentRuntime) {+ return (runtime as any).agent.state.messages.filter(+ (message: any) => message.role !== "system",+ );+ }++ it("keeps the real recent window when an automatic summary fails", async () => {+ const host = { call: vi.fn().mockResolvedValue(undefined) };+ const runtime = createRuntime({ host });+ (runtime as any).fullEntries = [+ messageEntry("user-1", null, userNote("start the migration", 1), 0),+ messageEntry("assistant-1", "user-1", assistantNote("I mapped the schema.", 2), 1),+ messageEntry("assistant-2", "assistant-1", toolStep(["tool-1"], 3), 2),+ messageEntry(+ "tool-1",+ "assistant-2",+ toolOutput("tool-1", "CREATE TABLE projects (id TEXT)", 4),+ 3,+ ),+ messageEntry("user-2", "tool-1", userNote("now rename the column", 5), 4),+ ];+ failingSummary(runtime);++ await expect(+ (runtime as any).runCompaction("threshold", false, "active_turn"),+ ).resolves.toBe(true);++ const checkpoint = appendedCheckpoint(host);+ expect(checkpoint.details).toMatchObject({+ fallback: "retained_tail",+ failureCode: "CONTEXT_COMPACTION_FAILED",+ failureReason: "summary_provider",+ retainedTailMode: "active_turn",+ retainedTailShape: "recent_window",+ retainedTailCount: 5,+ });+ // The whole window survives, not the one latest user line: the earlier+ // decision, the tool output, and the in-flight request all outlive the+ // failed summary.+ expect(checkpoint.retainedTail.map((message: any) => message.role)).toEqual([+ "user",+ "assistant",+ "assistant",+ "toolResult",+ "user",+ ]);+ expect(checkpoint.summary).toContain(COMPACTION_FALLBACK_MARKER);+ // A failed summary must not tell the model that one leftover user line is+ // the source of truth for the whole continuation.+ expect(checkpoint.summary).not.toContain("source of truth");++ const replayed = replayedMessages(runtime);+ expect(replayed.map((message: any) => message.role)).toEqual([+ "compactionSummary",+ "user",+ "assistant",+ "assistant",+ "toolResult",+ "user",+ ]);+ expect(+ replayed+ .filter((message: any) => message.role === "toolResult")+ .map((message: any) => message.content[0].text),+ ).toEqual(["CREATE TABLE projects (id TEXT)"]);+ await runtime.dispose();+ });++ it("restores the same window for a completed turn without inventing a request", async () => {+ const host = { call: vi.fn().mockResolvedValue(undefined) };+ const runtime = createRuntime({ host });+ (runtime as any).fullEntries = [+ messageEntry("user-1", null, userNote("start the migration", 1), 0),+ messageEntry("assistant-1", "user-1", assistantNote("I mapped the schema.", 2), 1),+ messageEntry("assistant-2", "assistant-1", toolStep(["tool-1"], 3), 2),+ messageEntry(+ "tool-1",+ "assistant-2",+ toolOutput("tool-1", "CREATE TABLE projects (id TEXT)", 4),+ 3,+ ),+ messageEntry(+ "assistant-3",+ "tool-1",+ assistantNote("The migration is complete: 3 files changed.", 5),+ 4,+ ),+ ];+ failingSummary(runtime);++ await expect((runtime as any).runCompaction("threshold", false)).resolves.toBe(+ true,+ );++ const checkpoint = appendedCheckpoint(host);+ const replayed = replayedMessages(runtime);+ expect(replayed.map((message: any) => message.role)).toEqual([+ "compactionSummary",+ "user",+ "assistant",+ "assistant",+ "toolResult",+ "assistant",+ ]);+ // The window ends on the finished assistant message, so nothing in it reads+ // as a request the next task still has to answer (#563, #224).+ expect(replayed.at(-1).role).toBe("assistant");+ await runtime.dispose();+ });++ it("summarizes a range no single prompt can carry instead of skipping it", async () => {+ const constrained: RuntimeProviderConfig = {+ ...provider,+ modelConfig: {+ ...provider.modelConfig!,+ contextWindow: 32_000,+ maxTokens: 4_096,+ },+ };+ const runtime = createRuntime({ provider: constrained });+ const resultCount = 600;+ (runtime as any).fullEntries = [+ messageEntry(+ "old-user",+ null,+ { role: "user", content: "inspect the repository", timestamp: 1 },+ 0,+ ),+ messageEntry(+ "carrier",+ "old-user",+ toolStep(+ Array.from({ length: resultCount }, (_, index) => `tool-${index}`),+ 2,+ "read",+ ),+ 1,+ ),+ ...Array.from({ length: resultCount }, (_, index) =>+ messageEntry(+ `tool-${index}`,+ index === 0 ? "carrier" : `tool-${index - 1}`,+ toolOutput(`tool-${index}`, "r".repeat(2_000), 3),+ index + 2,+ ),+ ),+ ];+ const generate = vi+ .spyOn(runtime as any, "generateCompaction")+ .mockImplementation(async () => ({+ ok: true,+ value: {+ summary: `part ${generate.mock.calls.length}`,+ tokensBefore: 80_000,+ usage: {+ input: 10,+ output: 5,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 15,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ details: { readFiles: ["large-0.txt"], modifiedFiles: [] },+ },+ }));++ const build = await (runtime as any).buildCheckpoint(+ new AbortController().signal,+ "active_turn",+ );++ expect(build.ok).toBe(true);+ const calls = generate.mock.calls.map(([preparation]: any[]) => preparation);+ expect(calls.length).toBeGreaterThan(1);+ expect(calls.length).toBeLessThanOrEqual(16);+ // Every request after the first carries its predecessor's summary, so the+ // chain converges on one summary for the whole range.+ expect(calls[0].previousSummary).toBeUndefined();+ for (let index = 1; index < calls.length; index += 1) {+ expect(calls[index].previousSummary).toBe(`part ${index}`);+ }+ // Coverage: the chunks are contiguous and together carry every message, so+ // nothing leaves the context without the summary covering it.+ const summarized = calls.flatMap(+ (preparation: any) => preparation.messagesToSummarize,+ );+ expect(summarized).toHaveLength(resultCount + 2);+ expect(summarized[0].content).toBe("inspect the repository");+ expect(+ summarized.filter((message: any) => message.role === "toolResult"),+ ).toHaveLength(resultCount);+ // The range's file operations ride on the last request only, so pi appends+ // the file list to the installed summary exactly once.+ expect(calls[0].fileOps.read.size).toBe(0);+ expect(calls.at(-1)!.fileOps).toBe((build as any).preparation.fileOps);+ // One checkpoint, not a fallback: the model still summarized the range.+ const checkpoint = (build as any).checkpoint;+ expect(checkpoint.summary).toBe(`part ${calls.length}`);+ expect(checkpoint.usage).toMatchObject({ totalTokens: 15 * calls.length });+ expect(checkpoint.details).toMatchObject({+ strategy: "summary",+ retainedTailMode: "active_turn",+ readFiles: ["large-0.txt"],+ });+ expect(checkpoint.details.fallback).toBeUndefined();+ await runtime.dispose();+ });++ it("records why a fallback had to run", async () => {+ const host = { call: vi.fn().mockResolvedValue(undefined) };+ const runtime = createRuntime({ host });+ (runtime as any).fullEntries = [+ messageEntry("user-1", null, userNote("continue the migration", 1), 0),+ ];++ await expect(+ (runtime as any).recoverCompactionFailure(+ (runtime as any).entriesWithCompaction(),+ (runtime as any).contextBudget(+ (runtime as any).liveSessionContext().messages,+ ),+ "threshold",+ false,+ undefined,+ "Compaction summary input exceeds the safe model budget",+ "active_turn",+ "summary_budget",+ ),+ ).resolves.toBe(true);++ expect(appendedCheckpoint(host).details).toMatchObject({+ failureReason: "summary_budget",+ retainedTailMode: "active_turn",+ retainedTailShape: "recent_window",+ });+ await runtime.dispose();});});diff --cc packages/agent-runtime/src/runtime.tsindex 8fa521e69,c8ad68814..8e7f17d07--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@@ -5957,19 -6022,7 +6022,19 @@@ Delegation rulesthis.setAgentMessages(messages);this.setAgentTools(tools);return {- messages: this.agent.state.messages,+ // The loop owns its context array. pi appends every streamed assistant+ // message and every tool result to the context it was handed, and its own+ // `message_end` listener appends the same message object to+ // `state.messages`; handing over the live array makes both land in one+ // array, so every message of a run's later iterations is stored twice.+ // The next turn is then built from that array, and the duplicate of an+ // assistant message that carries text plus a tool call survives the+ // request guard as a text-only clone sitting between the call and the+ // result answering it. pi-ai then closes the still-pending call with a+ // synthesized "No result provided" output next to the real one — two- // outputs for one call id, which the provider rejects (D613).++ // outputs for one call id, which the provider rejects (D619).+ // `createContextSnapshot()` copies for the same reason.+ messages: [...this.agent.state.messages],tools,systemPrompt: this.agent.state.systemPrompt,} as AgentContext;diff --cc packages/agent-runtime/src/subagent-loop-context.test.tsindex e1e670519,000000000..3f1c7b4dfmode 100644,000000..100644--- a/packages/agent-runtime/src/subagent-loop-context.test.ts+++ b/packages/agent-runtime/src/subagent-loop-context.test.ts@@@ -1,119 -1,0 +1,119 @@@+import { describe, expect, it, vi } from "vitest";+import type { SubagentDefinition } from "@pi-desktop/shared";+import { SubagentRun } from "./subagent.js";+import type { RuntimeProviderConfig } from "./provider-binding.js";++/**+ * What a turn boundary decides — compact, degrade, or report an overflow — is+ * covered by `subagent-context.test.ts`. This file pins the update the delegate+ * hands the agent loop instead, because that array is the context every later- * iteration of a run appends to (D613).++ * iteration of a run appends to (D619).+ */+vi.mock("./subagent-context.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./subagent-context.js")>();+ return {+ ...actual,+ prepareDelegateTurnContext: vi.fn(async () => ({+ kind: "degraded" as const,+ messages: [],+ tokensBefore: 1,+ })),+ };+});++const provider: RuntimeProviderConfig = {+ id: "local",+ name: "Local",+ baseUrl: "http://127.0.0.1:11434/v1",+ modelId: "local-model",+ apiKey: "",+ authKind: "none",+ supportsReasoning: false,+ supportedThinkingLevels: ["off"],+};++function definition(): SubagentDefinition {+ return {+ name: "explorer",+ description: "Search the workspace and report findings.",+ tools: ["Read"],+ prompt: "Find the answer and report it.",+ source: "builtin",+ };+}++/** The agent-loop surface the delegate wires a run through. */+type DelegateAgent = {+ state: { messages: unknown[] };+ prepareNextTurnWithContext?: (+ turn: unknown,+ signal: AbortSignal,+ ) => Promise<{ context?: { messages: unknown[] } } | undefined>;+};++function createDelegate(): DelegateAgent {+ const run = new SubagentRun({+ definition: definition(),+ sessionId: "session-1",+ turnId: "turn-1",+ parentToolCallId: "task-1",+ task: "Find where the permission dialog is rendered.",+ provider,+ thinkingLevel: "off",+ systemPrompt: "system",+ tools: [],+ onEvent: () => undefined,+ });+ return (run as unknown as { agent: DelegateAgent }).agent;+}++/** Minimal pi-ai assistant message, shaped like the ones the loop appends. */+function assistantMessage(text: string) {+ return {+ role: "assistant",+ api: "openai-completions",+ provider: "local",+ model: "local-model",+ stopReason: "stop",+ timestamp: 2,+ usage: {+ input: 10,+ output: 5,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 15,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ content: [{ type: "text", text }],+ };+}+- describe("SubagentRun loop context ownership (D613)", () => {++describe("SubagentRun loop context ownership (D619)", () => {+ it("hands the loop its own context array at a protected turn boundary", async () => {+ const agent = createDelegate();+ agent.state.messages = [+ { role: "system", content: "system", timestamp: 0 },+ { role: "user", content: "Find the permission dialog.", timestamp: 1 },+ ];++ const update = await agent.prepareNextTurnWithContext!(+ { toolResults: [] },+ new AbortController().signal,+ );++ // The boundary protected the request, so it did hand the loop a context.+ expect(update?.context?.messages).toBeDefined();+ const carried = update!.context!.messages;+ // pi's loop appends every streamed assistant message and tool result to the+ // array it was handed, while its `message_end` listener appends the same+ // message to the agent state. Handing over the state's live array would+ // store every message of the run's later iterations twice, and the trailing+ // row `useNextModel` slices off before a fallback would then leave an+ // assistant row at the head of what `continue()` refuses to resume from- // (D613).++ // (D619).+ expect(carried).not.toBe(agent.state.messages);+ const streamed = assistantMessage("round 2");+ carried.push(streamed);+ expect(agent.state.messages).not.toContain(streamed);+ });+});diff --cc packages/agent-runtime/src/subagent.tsindex ff780d6c5,ed46b8441..34b05da6e--- a/packages/agent-runtime/src/subagent.ts+++ b/packages/agent-runtime/src/subagent.ts@@@ -403,14 -403,7 +403,14 @@@ export class SubagentRun}return {context: {- messages: this.agent.state.messages,+ // The loop owns its context array: pi appends every streamed assistant+ // message and every tool result to the array it was handed, while its+ // own `message_end` listener appends the same message to+ // `state.messages`. Handing over the live array stores each message of+ // the run's later iterations twice, which doubles the estimate at the+ // next boundary and leaves `useNextModel` a trailing assistant row it- // cannot resume from (D613).++ // cannot resume from (D619).+ messages: [...this.agent.state.messages],tools: this.agent.state.tools,},};diff --cc packages/agent-runtime/src/tool-call-dedupe.test.tsindex 285ce7773,000000000..e9ea9f315mode 100644,000000..100644--- a/packages/agent-runtime/src/tool-call-dedupe.test.ts+++ b/packages/agent-runtime/src/tool-call-dedupe.test.ts@@@ -1,224 -1,0 +1,224 @@@+import { describe, expect, it, vi } from "vitest";+import type { AgentMessage } from "@earendil-works/pi-agent-core";+import { transformMessages } from "@earendil-works/pi-ai/api/transform-messages";+import {+ dedupeToolCallMessages,+ reportDuplicateToolCallDrop,+} from "./tool-call-dedupe.js";++/** Only the fields the guard reads: the role, the blocks, and the call id. */+function assistantMessage(content: unknown[]): AgentMessage {+ return { role: "assistant", content, timestamp: 1 } as unknown as AgentMessage;+}++function text(value: string) {+ return { type: "text", text: value };+}++function toolCall(id: string, name = "Read") {+ return { type: "toolCall", id, name, arguments: {} };+}++function toolResult(toolCallId: string, value = "ok"): AgentMessage {+ return {+ role: "toolResult",+ toolCallId,+ toolName: "Read",+ content: [text(value)],+ isError: false,+ timestamp: 2,+ } as unknown as AgentMessage;+}++function callIds(messages: AgentMessage[]): string[] {+ return messages.flatMap((message) =>+ message.role === "assistant"+ ? ((message as { content: unknown[] }).content ?? [])+ .filter(+ (block): block is { type: string; id: string } =>+ typeof block === "object" &&+ block !== null &&+ (block as { type?: string }).type === "toolCall",+ )+ .map((block) => block.id)+ : [],+ );+}++function resultIds(messages: AgentMessage[]): string[] {+ return messages+ .filter((message) => message.role === "toolResult")+ .map((message) => (message as { toolCallId?: string }).toolCallId ?? "");+}++describe("dedupeToolCallMessages", () => {+ it("returns the request view unchanged when every call id is unique", () => {+ const messages = [+ assistantMessage([text("reading"), toolCall("call-1")]),+ toolResult("call-1"),+ assistantMessage([text("done")]),+ ];++ const drop = dedupeToolCallMessages(messages);++ expect(drop.messages).toBe(messages);+ expect(drop.droppedCount).toBe(0);+ expect(drop.droppedMessages).toBe(0);+ expect(drop.droppedIds).toEqual([]);+ });++ it("drops a replayed round as one snapshot and one duplicate result", () => {+ // The shape production hit: pi's loop appends the streamed assistant+ // message and its tool result to the context it was handed, while its own+ // `message_end` listener appends the same objects to the session state, so- // one round reached the next turn as two copies of each (D613). The++ // one round reached the next turn as two copies of each (D619). The+ // assistant message carries text *and* a call, so dropping only the call+ // block would leave a text-only clone between the call and its result.+ const assistant = assistantMessage([+ text("reading the file"),+ toolCall("call-1|item-1"),+ ]);+ const result = toolResult("call-1|item-1");++ const drop = dedupeToolCallMessages([assistant, assistant, result, result]);++ expect(drop.droppedCount).toBe(2);+ expect(drop.droppedMessages).toBe(1);+ expect(drop.droppedIds).toEqual(["call-1"]);+ // One call, then the result that answers it: nothing sits between them.+ expect(drop.messages).toHaveLength(2);+ expect(drop.messages[0]).toBe(assistant);+ expect(drop.messages[1]).toBe(result);+ expect(callIds(drop.messages)).toEqual(["call-1|item-1"]);+ expect(resultIds(drop.messages)).toEqual(["call-1|item-1"]);+ });++ it("treats ids that differ only after the separator as one call", () => {+ // Only the part before the separator reaches the provider as `call_id`, so+ // two entries whose item half differs still collide on the wire.+ const assistant = assistantMessage([toolCall("call-1|item-1")]);++ const drop = dedupeToolCallMessages([+ assistant,+ toolResult("call-1|item-2"),+ toolResult("call-1|item-3"),+ ]);++ expect(drop.droppedCount).toBe(1);+ expect(drop.droppedMessages).toBe(0);+ expect(drop.messages).toHaveLength(2);+ // The surviving result answers the call under the call's own composite id,+ // so pi-ai pairs them instead of synthesizing a second output for the id.+ expect(resultIds(drop.messages)).toEqual(["call-1|item-1"]);+ });++ it("keeps a new call in a message that also replays an older one", () => {+ const first = assistantMessage([text("first"), toolCall("call-1")]);+ const second = assistantMessage([+ text("second"),+ toolCall("call-1"),+ toolCall("call-2"),+ ]);++ const drop = dedupeToolCallMessages([+ first,+ second,+ toolResult("call-1"),+ toolResult("call-2"),+ ]);++ expect(drop.droppedCount).toBe(1);+ expect(drop.droppedMessages).toBe(0);+ // Only the replayed block goes: the message also carries a new call, so it+ // stays, and the guard does not reorder messages to close the gap the+ // dropped call leaves behind. No writer reaches this partial replay today —+ // the runtime's own duplication repeats a message whole, which is the case+ // dropped whole above.+ expect(drop.messages.map((message) => message.role)).toEqual([+ "assistant",+ "assistant",+ "toolResult",+ "toolResult",+ ]);+ expect(callIds(drop.messages)).toEqual(["call-1", "call-2"]);+ expect(resultIds(drop.messages)).toEqual(["call-1", "call-2"]);+ });++ it("leaves a call whose result never arrived to pi-ai's placeholder", () => {+ const messages = [assistantMessage([toolCall("call-1")])];++ expect(dedupeToolCallMessages(messages).messages).toBe(messages);+ });++ it("reports the wire ids and how many messages it removed", () => {+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ reportDuplicateToolCallDrop("session-1", {+ messages: [],+ droppedCount: 2,+ droppedMessages: 1,+ droppedIds: ["call-1"],+ });+ const line = stderr.mock.calls.map(([chunk]) => String(chunk)).join("");+ expect(line).toContain(+ "dropped 2 duplicate tool call entries (1 replayed message)",+ );+ expect(line).toContain("session=session-1");+ expect(line).toContain("ids=call-1");+ } finally {+ stderr.mockRestore();+ }+ });+});++/**+ * The failure this guard exists for is invisible in the runtime's own view of a+ * request: pi-ai synthesizes the second output inside its provider transform,+ * after the point a scripted provider can capture. Driving that transform is- * what pins the mechanism the endpoint rejects (D613).++ * what pins the mechanism the endpoint rejects (D619).+ */- describe("request wire contract (D613)", () => {++describe("request wire contract (D619)", () => {+ /** Only the fields the transform reads for a non-normalizing API. */+ const model = {+ api: "openai-completions",+ id: "test-model",+ provider: "test",+ input: ["text"],+ } as never;++ /** Every output the provider would validate for this request. */+ function wireOutputIds(messages: AgentMessage[]): string[] {+ return transformMessages(messages as never, model)+ .filter((message) => message.role === "toolResult")+ .map((message) => String((message as { toolCallId?: string }).toolCallId));+ }++ it("answers a call the request separates from its result twice", () => {+ // The shape production sent: the replayed clone of the assistant message+ // sits between the call and the result answering it, so the transform+ // closes the call it can no longer see answered — `Duplicate tool output+ // for call_id`.+ const call = assistantMessage([text("reading"), toolCall("call-1")]);+ const clone = assistantMessage([text("reading")]);++ expect(wireOutputIds([call, clone, toolResult("call-1")])).toEqual([+ "call-1",+ "call-1",+ ]);+ });++ it("answers a replayed round once after the guard drops it whole", () => {+ const call = assistantMessage([text("reading"), toolCall("call-1")]);+ const replay = assistantMessage([text("reading"), toolCall("call-1")]);++ const drop = dedupeToolCallMessages([+ call,+ replay,+ toolResult("call-1"),+ toolResult("call-1"),+ ]);++ expect(drop.droppedMessages).toBe(1);+ expect(wireOutputIds(drop.messages)).toEqual(["call-1"]);+ });+});diff --cc packages/agent-runtime/src/tool-call-dedupe.tsindex ca44f65ef,7dc35e825..cb5e84e34--- a/packages/agent-runtime/src/tool-call-dedupe.ts+++ b/packages/agent-runtime/src/tool-call-dedupe.ts@@@ -16,43 -14,12 +16,43 @@@ function isRecord(value: unknown): valureturn typeof value === "object" && value !== null;}+/**+ * The id a provider validates, which is not always the id we store.+ *+ * PI-Desktop keeps pi-ai's composite Responses call id (`<call_id>|<item_id>`)+ * so a replay can address the server-side item, and the adapter sends only the+ * part before the separator as `call_id`. Two entries whose composite ids+ * differ in the item half therefore still collide on the wire, so every- * comparison below uses this wire-visible id (D613).++ * comparison below uses this wire-visible id (D619).+ */+function wireCallId(id: string): string {+ const separator = id.indexOf("|");+ return separator < 0 ? id : id.slice(0, separator);+}+/*** Keep the first call and result for every tool-call id in a provider request.** The transcript can contain repeated snapshots of one call. Returning the* original array when nothing changes preserves the common path's identity and* avoids copying messages that are already valid.+ *+ * A request that separates a call from its result is not merely untidy: pi-ai+ * closes a call whose result does not follow it with a synthesized+ * "No result provided" output *and* sends the real result, so one call id- * carries two outputs and the endpoint rejects the whole turn (D608, D613).++ * carries two outputs and the endpoint rejects the whole turn (D608, D619).+ * Dropping a replayed assistant message whole — rather than keeping the text it+ * is left with — is what keeps that separation out of the request, and the+ * duplication the runtime itself produces repeats a message whole, so that is+ * the shape the drop covers. A message that replays one call while carrying a+ * new one keeps its new call where it is, which leaves the replayed call's own+ * result one message later; no writer reaches that partial replay, and the+ * guard leaves it alone rather than reordering what the model sees.+ *+ * Ids are compared by the part the provider validates, so two entries whose+ * item half differs count as one call. That shared id is the only id sharing+ * this guard accepts: a provider that reused one `call_id` for two distinct+ * calls would lose the second call and its result, reported under that id.*/export function dedupeToolCallMessages(messages: AgentMessage[],