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(agent-runtime): keep real DeepSeek reasoning in the field relays read
vastsafe31fa13da38
diff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.tsindex 420c41d0b..06f90d2d3 100644--- a/apps/desktop/src/lib/assistant-turns.ts+++ b/apps/desktop/src/lib/assistant-turns.ts@@ -4,7 +4,11 @@ import type {MessageUsage,UiMessage,} from "@pi-desktop/shared";-import { addUsage, hostedSearchRounds } from "@pi-desktop/shared";+import {+ addUsage,+ hostedSearchRounds,+ withoutReasoningReplayPlaceholder,+} from "@pi-desktop/shared";import { getToolAction, isDelegationStartTool } from "./tool-display";import { messageContentFacts } from "./transcript-summary";@@ -65,7 +69,9 @@ export type TranscriptEntry =export function messageThinking(message: UiMessage): string {if (typeof message.thinking !== "string") return "";- return message.thinking.trim() ? message.thinking : "";+ // An echoed replay placeholder is not the model's reasoning (#1945).+ const thinking = withoutReasoningReplayPlaceholder(message.thinking);+ return thinking.trim() ? thinking : "";}function isVisibleMessage(message: UiMessage): boolean {diff --git a/apps/desktop/test/assistant-turns.test.mjs b/apps/desktop/test/assistant-turns.test.mjsindex 46453fba1..1f04b0259 100644--- a/apps/desktop/test/assistant-turns.test.mjs+++ b/apps/desktop/test/assistant-turns.test.mjs@@ -12,6 +12,7 @@ const {assistantTurnResponseOutputIsEstimated,assistantTurnUsage,buildTranscriptEntries,+ messageThinking,reuseTranscriptEntries,subagentRunsEqual,} = await import("../src/lib/assistant-turns.ts");@@ -530,3 +531,21 @@ test("reuses unchanged activity parts when only the tail thinking token changes"assert.notEqual(sharedThink, firstThink);assert.equal(sharedThink.items[0].message, nextThinking);});++test("an echoed reasoning replay placeholder is not shown as thinking (#1945)", () => {+ const placeholder = "[reasoning not retained for this turn]";+ assert.equal(messageThinking(message("a", "assistant", "answer", { thinking: placeholder })), "");+ assert.equal(+ messageThinking(message("b", "assistant", "answer", { thinking: `${placeholder}real plan` })),+ "real plan",+ );+ assert.equal(messageThinking(message("c", "assistant", "answer", { thinking: "real plan" })), "real plan");+ // A placeholder-only row adds no thinking activity to its turn.+ const { entries } = buildTranscriptEntries([+ message("u", "user", "question"),+ message("a", "assistant", "answer", { thinking: placeholder, status: "complete" }),+ ]);+ const turn = entries.find((entry) => entry.kind === "assistant-turn");+ assert.ok(turn);+ assert.equal(JSON.stringify(turn).includes('"kind":"thinking"'), false);+});diff --git a/docs/adr/0256-deepseek-reasoning-across-compaction.md b/docs/adr/0256-deepseek-reasoning-across-compaction.mdindex db42891b9..d9d94ace0 100644--- a/docs/adr/0256-deepseek-reasoning-across-compaction.md+++ b/docs/adr/0256-deepseek-reasoning-across-compaction.md@@ -5,6 +5,8 @@- Deciders: PI-Desktop core- Amends: D389 / ADR 0136 / ADR 0064- Fixes: #296+- Amended by: D677 (#1945) — decision 3 now normalizes every row to the+ newest row's field and fills only rows with no reasoning## Context@@ -41,6 +43,15 @@ the #223 empty backfill fills `""` — which strict relays reject.`[reasoning not retained for this turn]` instead of `""`.4. ADR 0136 retained-tail rules are unchanged: user-only tails, no tool-callreplay.+5. Amendment (D677, #1945): the field is taken from the newest assistant row+ that has real reasoning, not from fixed list order. Every assistant row is+ normalized to that one field: real reasoning under another field name is+ moved there, and the placeholder fills only rows with no reasoning at all.+ A rebuilt row is stamped `reasoning_content` while a live relay row keeps+ `reasoning_text`; the old pass picked `reasoning_content` and filled the+ placeholder over the live row's real reasoning, in the field the model+ reads, and the model echoed it. A leading echo of the placeholder in stored+ thinking is neither displayed nor replayed.## Consequencesdiff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex f9395a425..bb2d14937 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -127,6 +127,10 @@ Non-official DeepSeek endpoints also set `requiresNonEmptyReasoningReplay` somissing reasoning is filled with a documented placeholder instead of `""`(OpenCode / third-party relays reject empty echoes after compaction; seeADR 0256 / #296). Official `deepseek.com` rows keep empty-string fill (#223).+Every replayed assistant row carries one reasoning field, named after the+newest row with real reasoning; real reasoning under another name is moved to+it, so only rows with no reasoning are filled, and a leading echo of the+placeholder in stored thinking is neither shown nor replayed (D677, #1945).Relay rows set `supportsReasoningEffort: false` because DeepSeek-family relayswere reported rejecting the generic OpenAI `reasoning_effort` field (#1664).Official `deepseek.com` rows leave the flag to pi-ai, which sendsdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 0fda0bb47..ddb17c3e4 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1788,6 +1788,11 @@ identify the platform validation still needed.turns that had no thinking. Non-official DeepSeek-family relays use realretained thinking when available, otherwise the documented non-emptyplaceholder from ADR 0256 — never a silent empty string after compaction.+ Each assistant message carries exactly one reasoning field, named after the+ newest assistant row's field; real reasoning stored under another field name+ is moved there rather than replaced by the placeholder, which only fills rows+ with no reasoning at all (D677). The thinking panel and replayed history+ never show a leading echo of the placeholder as reasoning.Relay requests omit the generic OpenAI `reasoning_effort` field becauserelays were reported rejecting it (#1664). Official `api.deepseek.com`requests send `thinking: {type: "enabled"}` together with the selected@@ -1800,7 +1805,8 @@ identify the platform validation still needed.- **Acceptance**: B (provider Completions compatibility)- **Milestone**: M2- **Status**: Unit-covered (compat inject + convertMessages empty/non-empty fill +- compaction retained-reasoning wire proof); live OpenCode / aggregator+ mixed-field normalization + echoed-placeholder strip + compaction+ retained-reasoning wire proof); live OpenCode / aggregatorverification deferred; rendered UI scenario pending#### E2E-006: Key survives restartdiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 7a06b9d01..3322335e7 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -338,6 +338,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D674 | Per-turn changed-files summary under a finished reply | **A completed reply whose turn recorded workspace review changes renders one read-only `TurnChangesCard` below its answer and above `entryExtra`, built only from that turn's message-owned `details.review` records (no new capture, IPC, or persistence). Rows merge edits per path (`D` if the turn ends by deleting, else `A` if any edit created the file, else `M`; counts summed; rolled-back files stay listed and struck through). Up to four files use relaxed rows, more use dense rows, and rows past 12 fold into `+N more`. Clicking a row opens Review on that file's recorded changes; the per-call review rows and the Review tab are unchanged.** | Issue #1891, design 10 (adaptive density): the per-call review rows answer "what did this call change", and Review answers it for the whole session, but nothing answered "what did this turn change" without counting rows. || D675 | Inline images are admitted by pixel size as well as bytes | **Amend D361: an image whose PNG/JPEG/GIF/WebP header reports a longest edge above `MAX_INLINE_IMAGE_EDGE_PX` (8000) is never inlined. Host Read refuses it with `TOOL_FAILED`; prompt attachments and restored history take the existing `@path` fallback; and the runtime's last provider view replaces any such image block (user or tool result) with a text notice naming its size. The probe reads headers only (no decoder); unknown dimensions keep the byte-only rule. No protocol, schema, or persisted-format change.** | Issue #1913: a 1.89 MB, 780 x 14182 full-page screenshot passed every byte check, the provider rejected it with a non-retriable 400, and replay made every later request in that session fail. Dropping is deterministic for the same bytes, so the request prefix and prompt caching stay stable; resampling would need an image decoder and is deferred. || D676 | A completed turn the reader followed ends at its prompt | **Amend the stream-completion rule: when a turn completes while the transcript is visible and still following the stream, the renderer scrolls that turn's newest user message to 16px below the titlebar band the transcript reserves at its top (smooth unless reduced motion), releases follow mode, and shows jump-to-latest. Nothing moves when the prompt is already in view, the reply failed or was aborted, the pane is hidden or in a reading window, a disclosure position is held, or a new run starts before the move. Renderer only; no setting, IPC, or persistence change.** | Issue #1889: after a long reply the reader sat at its last line and had to scroll back up to find where it began. |+| D677 | DeepSeek reasoning replay uses one field per row and never covers real reasoning | **Amend ADR 0256 decision 3: the pi-ai fill pass takes the reasoning field from the newest assistant row that has real reasoning, normalizes every assistant row to that single field (moving real reasoning from another field name, deleting the others), and fills the placeholder only on rows with no reasoning. History rebuild and the thinking panel drop a leading echo of the placeholder (`withoutReasoningReplayPlaceholder`); stored text is not rewritten. No schema, IPC, or setting change.** | Issue #1945: rebuilt rows are stamped `reasoning_content` while a relay streams `reasoning_text`; the fill pass picked `reasoning_content` and wrote the placeholder over the live row's real reasoning, the model echoed it as its own thinking (13.6% of assistant rows in affected sessions), and the echo was persisted and replayed. |## M0. Model catalog decisions@@ -8057,3 +8058,25 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.`apps/desktop/test/turn-completion-scroll.test.mjs` and`pnpm test:e2e:transcript-turn-completion`(E2E-CHAT-completed-turn-scrolls-to-prompt).++## 2026-10-28 — One DeepSeek reasoning field per replayed row (D677)++- D677 amends ADR 0256 decision 3 (issue #1945). The pi-ai fill pass in+ `patches/@[email protected]` picks the reasoning field of the+ newest assistant row with real reasoning instead of the first field in a+ fixed list, and normalizes every assistant row to it. Real reasoning stored+ under another field name moves there; the other fields are removed, so a+ row never carries two (relays reject duplicate reasoning fields).+- The placeholder now fills only rows with no reasoning at all, so a live row+ with real reasoning is never sent the placeholder in the field the model+ reads.+- `withoutReasoningReplayPlaceholder` (shared) drops a leading echo of the+ placeholder, and its observed `[reasoning retained for this turn]` rewrite,+ from stored thinking in session and delegate history rebuild and in+ `messageThinking`, which feeds the thinking panel. Existing transcripts are+ not rewritten; the echo simply stops being shown or replayed.+- Not changed: strict relays still receive the non-empty placeholder for rows+ with no reasoning (#296), and official DeepSeek keeps `""`.+- Covered by `reasoning-content-backfill.test.ts`, `runtime.test.ts`,+ `provider-presets.test.ts`, and `apps/desktop/test/assistant-turns.test.mjs`.+ See E2E-005E.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.mdindex 852f2163e..cf37b783d 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@@ -117,7 +117,9 @@ OpenAI 风格的 Copilot 线路 API 仍将令牌作为请求密钥签名;所存成 `model.provider`,因此聚合网关与自定义端点会在无思考内容的助手回合漏掉`reasoning_content`。非官方 DeepSeek 端点还会设置 `requiresNonEmptyReasoningReplay`,用文档化的非空占位符而不是 `""` 填补缺失推理(OpenCode / 第三方中转在压缩后拒绝空回传;-见 ADR 0256 / #296)。官方 `deepseek.com` 行仍使用空串回填(#223)。该覆盖不改+见 ADR 0256 / #296)。官方 `deepseek.com` 行仍使用空串回填(#223)。每条回放的 assistant+行只带一个推理字段,字段名取最新一条带真实推理的行;其他字段名下的真实推理会被移过去,+因此只有没有推理的行才会被填充,已存储思考开头回显的占位符也不会被显示或回放(D677,#1945)。该覆盖不改`thinkingFormat`。中转行设置 `supportsReasoningEffort: false`,因为有 DeepSeek 系中转被报告拒绝通用 OpenAI 的 `reasoning_effort` 字段(#1664)。官方 `deepseek.com` 行把该标志交给 pi-ai,按 DeepSeek 文档在 `thinking: {type: "enabled"}` 旁发送 `reasoning_effort`diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 4f1103434..585c14f61 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -489,12 +489,12 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **前提条件**:已配置一个 Base URL 不含 `deepseek.com` 的 OpenAI 兼容提供商,模型 ID 属于 DeepSeek 系(例如硅基流动 `deepseek-ai/DeepSeek-V3.2`),并开启思考模式。- **步骤**:1) 在思考模式下开始会话。2) 完成若干回合,其中至少一条助手回复没有思考文本。3) 再发一条提示,使历史被回放到提供商。-- **预期**:后续 Completions 请求的每条 assistant 消息都带推理字段。官方 `api.deepseek.com` 行对无思考内容的回合仍可使用 `""`。非官方 DeepSeek 系中转在可用时回传保留的真实思考,否则使用 ADR 0256 文档化的非空占位符——压缩后不得静默回填空串。中转请求不携带通用 OpenAI 的 `reasoning_effort` 字段,因为有中转被报告拒绝它(#1664);官方 `api.deepseek.com` 请求同时发送 `thinking: {type: "enabled"}` 与所选的 `reasoning_effort`(#1821)。不会仅因模型 ID 含 `"deepseek"` 就把 `thinkingFormat` 改成 `"deepseek"`。官方 `api.deepseek.com` 行仍使用 pi-ai 按 URL 检测的 DeepSeek `thinkingFormat`。+- **预期**:后续 Completions 请求的每条 assistant 消息都带推理字段。官方 `api.deepseek.com` 行对无思考内容的回合仍可使用 `""`。非官方 DeepSeek 系中转在可用时回传保留的真实思考,否则使用 ADR 0256 文档化的非空占位符——压缩后不得静默回填空串。每条 assistant 消息只带一个推理字段,字段名取最新一条 assistant 行所用的字段;存放在其他字段名下的真实推理会被移到该字段,而不是被占位符替代,占位符只填充完全没有推理的行(D677)。思考面板和回放历史都不会把开头回显的占位符当作推理显示或回传。中转请求不携带通用 OpenAI 的 `reasoning_effort` 字段,因为有中转被报告拒绝它(#1664);官方 `api.deepseek.com` 请求同时发送 `thinking: {type: "enabled"}` 与所选的 `reasoning_effort`(#1821)。不会仅因模型 ID 含 `"deepseek"` 就把 `thinkingFormat` 改成 `"deepseek"`。官方 `api.deepseek.com` 行仍使用 pi-ai 按 URL 检测的 DeepSeek `thinkingFormat`。- **链接规格**:`03-runtime/11-provider-model-system.md`、`03-runtime/12-provider-config-schema.md`- **验收**:B(提供商 Completions 兼容)- **里程碑**:M2-- **状态**:单元覆盖(compat 注入 + convertMessages 空/非空补全 + 压缩保留推理上线证明);现场 OpenCode/聚合端验证仍推迟;界面场景待完成+- **状态**:单元覆盖(compat 注入 + convertMessages 空/非空补全 + 混用字段归一 + 回显占位符剥离 + 压缩保留推理上线证明);现场 OpenCode/聚合端验证仍推迟;界面场景待完成#### E2E-005F:自定义端点输入护栏diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 9eb208044..0bb34cce6 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -341,6 +341,7 @@| D674 | 已完成回复下方的按轮文件变更汇总 | **回合记录了工作区审核变更的已完成回复,会在回答下方、`entryExtra` 上方渲染一张只读的 `TurnChangesCard`,只由该回合消息拥有的 `details.review` 记录构建(不新增采集、IPC 或持久化)。按路径合并多次编辑(回合以删除结束为 `D`,否则有创建即为 `A`,其余为 `M`;计数累加;已回滚文件保留并显示删除线)。不超过四个文件用宽松行,更多用密集行,超过 12 行折叠为 `+N more`。点击一行会在审阅中打开该文件的记录变更;逐次调用的审核行和审阅选项卡保持不变。** | Issue #1891,设计 10(自适应密度):逐次调用的审核行回答“这次调用改了什么”,审阅回答整个会话的问题,但回答“这一轮改了什么”仍需自己数工具行。 || D675 | 内联图片同时按像素尺寸与字节准入 | **修订 D361:PNG/JPEG/GIF/WebP 文件头显示最长边超过 `MAX_INLINE_IMAGE_EDGE_PX`(8000)的图片永不内联。Host Read 以 `TOOL_FAILED` 拒绝;提示附件与恢复的历史走既有的 `@path` 回退;运行时在最后的提供商视图中把这类图片块(用户或工具结果)替换为写明尺寸的文本说明。探测只读文件头(无解码器);读不出尺寸时保留仅按字节的规则。不改变协议、schema 或持久化格式。** | Issue #1913:一张 1.89 MB、780 x 14182 的整页截图通过了所有字节检查,提供商以不可重试的 400 拒绝,重放使该会话此后每个请求都失败。同样的字节总是被同样地丢弃,请求前缀与提示缓存保持稳定;重采样需要图像解码器,留待以后。 || D676 | 读者跟随的已完成回合停在它的提示处 | **修订流完成规则:转录可见且仍在跟随流时回合完成,渲染层会把该回合最新的用户消息滚动到转录顶部预留的标题栏带下方 16px 处(除非减少动态效果,否则平滑滚动),退出跟随模式并显示“滚动到底部”。提示已在视野内、回复失败或被中止、面板隐藏或处于阅读窗口、披露位置被保持、或在移动前开始了新的运行时,都不移动。仅渲染层;不新增设置,不改变 IPC 或持久化。** | Issue #1889:长回复结束后读者停在最后一行,得自己往上滑才能找到回答的开头。 |+| D677 | DeepSeek 推理回放每行只用一个字段,且永不覆盖真实推理 | **修订 ADR 0256 第 3 条:pi-ai 的补全过程从最新一条带真实推理的 assistant 行取推理字段,把每条 assistant 行归一到这一个字段(真实推理从其他字段名移过来,并删除其余字段),只在没有任何推理的行上填充占位符。历史重建与思考面板会去掉开头回显的占位符(`withoutReasoningReplayPlaceholder`);不改写已存储的文本。不改变 schema、IPC 或设置。** | Issue #1945:重建行被标为 `reasoning_content`,而中转流式返回的是 `reasoning_text`;补全过程选了 `reasoning_content`,把占位符写在了 live 行真实推理之上、也就是模型读取的字段里,模型把它当作自己的思考复读(受影响会话中 13.6% 的 assistant 行),回显又被持久化并回放。 |## M0. 模型目录决策@@ -5619,3 +5620,21 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编`apps/desktop/test/turn-completion-scroll.test.mjs` 与`pnpm test:e2e:transcript-turn-completion`(E2E-CHAT-completed-turn-scrolls-to-prompt)覆盖。++## 2026-10-28 — DeepSeek 回放每行一个推理字段(D677)++- D677 修订 ADR 0256 第 3 条(issue #1945)。`patches/@[email protected]`+ 中的 pi-ai 补全过程不再按固定列表取第一个字段,而是取最新一条带真实推理的+ assistant 行所用的字段,并把每条 assistant 行归一到该字段。存放在其他字段名下的+ 真实推理会移过去;其余字段被删除,因此一行永远不会带两个推理字段(中转会拒绝+ 重复的推理字段)。+- 占位符现在只填充完全没有推理的行,带真实推理的 live 行再也不会在模型读取的字段+ 里收到占位符。+- 共享的 `withoutReasoningReplayPlaceholder` 会在会话与委托历史重建、以及供思考面板+ 使用的 `messageThinking` 中,去掉已存储思考开头回显的占位符及其被观察到的+ `[reasoning retained for this turn]` 改写。现有转录不会被改写;回显只是不再显示、+ 不再回放。+- 不变:严格中转对没有推理的行仍收到非空占位符(#296),官方 DeepSeek 仍使用 `""`。+- 由 `reasoning-content-backfill.test.ts`、`runtime.test.ts`、+ `provider-presets.test.ts` 与 `apps/desktop/test/assistant-turns.test.mjs` 覆盖。+ 见 E2E-005E。diff --git a/packages/agent-runtime/src/delegation-history.ts b/packages/agent-runtime/src/delegation-history.tsindex dbfe4e484..3af820a3c 100644--- a/packages/agent-runtime/src/delegation-history.ts+++ b/packages/agent-runtime/src/delegation-history.ts@@ -35,6 +35,7 @@ import {MAX_RESUMABLE_LISTED_FILES,MAX_RESUMABLE_READ_LINES,normalizeSubagentName,+ withoutReasoningReplayPlaceholder,type UiMessage,} from "@pi-desktop/shared";import { isRecord, timestampMs, toJsonObject, toJsonValue, usageToPi } from "./agent-messages.js";@@ -258,10 +259,13 @@ export function chainRowsToMessages(// hand the model a stopReason the provider never agreed to.if (row.status === "error" || row.isError || row.error) continue;const content: AssistantMessage["content"] = [];- if (row.thinking?.trim()) {+ // Same rule as session history: an echoed replay placeholder is not+ // reasoning to hand back (#1945).+ const thinking = withoutReasoningReplayPlaceholder(row.thinking ?? "");+ if (thinking.trim()) {content.push({type: "thinking",- thinking: row.thinking,+ thinking,...(deepSeekCompletionsReplay? { thinkingSignature: "reasoning_content" as const }: {}),diff --git a/packages/agent-runtime/src/reasoning-content-backfill.test.ts b/packages/agent-runtime/src/reasoning-content-backfill.test.tsindex 1b52901d5..447764c17 100644--- a/packages/agent-runtime/src/reasoning-content-backfill.test.ts+++ b/packages/agent-runtime/src/reasoning-content-backfill.test.ts@@ -169,6 +169,65 @@ describe("reasoning_content backfill for non-catalogue DeepSeek models", () => {]);});+ it("moves real reasoning to the newest row's field instead of filling the placeholder (#1945)", () => {+ // A rebuilt row is stamped reasoning_content while the relay streams the+ // live row's reasoning as reasoning_text. Filling reasoning_content on the+ // live row put the placeholder in the field the model reads, and the model+ // echoed it as its own reasoning.+ const compat = {+ ...baseCompat,+ requiresNonEmptyReasoningReplay: true,+ };+ const reasoning = assistantParams(+ [+ user("first"),+ assistant([+ { type: "thinking", thinking: "rebuilt plan", thinkingSignature: "reasoning_content" },+ { type: "text", text: "old answer" },+ ]),+ user("second"),+ assistant([+ { type: "thinking", thinking: "live plan", thinkingSignature: "reasoning_text" },+ { type: "text", text: "new answer" },+ ]),+ ],+ compat,+ );+ expect(reasoning).toEqual([+ { reasoning_content: undefined, reasoning_text: "rebuilt plan" },+ { reasoning_content: undefined, reasoning_text: "live plan" },+ ]);+ });++ it("keeps one reasoning field per row and fills only rows with no reasoning (#1945)", () => {+ const compat = {+ ...baseCompat,+ requiresNonEmptyReasoningReplay: true,+ };+ const reasoning = assistantParams(+ [+ user("first"),+ assistant([{ type: "text", text: "no thinking" }]),+ user("second"),+ assistant([+ { type: "thinking", thinking: "rebuilt plan", thinkingSignature: "reasoning_content" },+ { type: "text", text: "old answer" },+ ]),+ user("third"),+ assistant([+ { type: "thinking", thinking: "live plan", thinkingSignature: "reasoning_text" },+ { type: "text", text: "new answer" },+ ]),+ ],+ compat,+ );+ expect(reasoning).toEqual([+ { reasoning_content: undefined, reasoning_text: DEEPSEEK_REASONING_REPLAY_PLACEHOLDER },+ { reasoning_content: undefined, reasoning_text: "rebuilt plan" },+ { reasoning_content: undefined, reasoning_text: "live plan" },+ ]);+ });+it("restores thinking without a live signature when history rebuild stamps reasoning_content", () => {// #296 — historyToEntries must set thinkingSignature so this path is usedconst reasoning = assistantParams([diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex f5d35a72a..9913c6f14 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -4655,6 +4655,52 @@ describe("DesktopAgentRuntime thinking configuration", () => {await runtime.dispose();});+ it("does not replay an echoed reasoning placeholder as the model's own thinking (#1945)", async () => {+ const runtime = createRuntime({+ provider: {+ ...provider,+ vendorKey: "deepseek",+ baseUrl: "https://relay.example/v1",+ modelId: "deepseek-v4",+ modelConfig: {+ ...provider.modelConfig!,+ baseUrl: "https://relay.example/v1",+ },+ },+ history: [+ {+ id: "assistant-echo-only",+ role: "assistant",+ content: "first answer",+ thinking: "[reasoning not retained for this turn]",+ createdAt: new Date().toISOString(),+ status: "complete",+ },+ {+ id: "assistant-echo-prefix",+ role: "assistant",+ content: "second answer",+ thinking: "[reasoning not retained for this turn]real plan",+ createdAt: new Date().toISOString(),+ status: "complete",+ },+ ],+ });+ const assistants = (runtime as any).agent.state.messages.filter(+ (message: any) => message.role === "assistant",+ );++ expect(assistants.map((message: any) => message.content)).toEqual([+ [{ type: "text", text: "first answer" }],+ [+ { type: "thinking", thinking: "real plan", thinkingSignature: "reasoning_content" },+ { type: "text", text: "second answer" },+ ],+ ]);++ await runtime.dispose();+ });+it("keeps provider-native thinking unsigned for Anthropic history", async () => {const runtime = createRuntime({provider: {diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex d2808875b..731b0509f 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -127,6 +127,7 @@ import {type ProposalKind,type SubagentPermission,GEN_UI_SKILL_ID,+ withoutReasoningReplayPlaceholder,} from "@pi-desktop/shared";import { createStreamCoalescer, type StreamCoalescer } from "./stream-coalescer.js";import type { RuntimeHost } from "./host-client.js";@@ -3145,12 +3146,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// but must never become model context on the next turn.if (m.status === "error" || m.isError || m.error) continue;const content: AssistantMessage["content"] = [];- if (m.thinking?.trim()) {+ // A replay placeholder the model echoed is not its reasoning; sending+ // it back is what kept the model continuing it (#1945).+ const thinking = withoutReasoningReplayPlaceholder(m.thinking ?? "");+ if (thinking.trim()) {// Completions DeepSeek replay needs thinkingSignature so convertMessages// maps the block to reasoning_content instead of dropping it (#296).content.push({type: "thinking" as const,- thinking: m.thinking,+ thinking,...(deepSeekCompletionsReplay? { thinkingSignature: "reasoning_content" as const }: {}),diff --git a/packages/shared/src/provider-presets.test.ts b/packages/shared/src/provider-presets.test.tsindex a90638d05..c47237d89 100644--- a/packages/shared/src/provider-presets.test.ts+++ b/packages/shared/src/provider-presets.test.ts@@ -10,6 +10,7 @@ import {matchNamedPreset,matchZhipuPreset,normalizeEndpointUrl,+ withoutReasoningReplayPlaceholder,zhipuRequestCompat,} from "./provider-presets.js";@@ -374,3 +375,25 @@ describe("addressesPublishedVendorHost", () => {}});});++describe("withoutReasoningReplayPlaceholder", () => {+ it("drops a leading echo of the replay placeholder (#1945)", () => {+ expect(withoutReasoningReplayPlaceholder(DEEPSEEK_REASONING_REPLAY_PLACEHOLDER)).toBe("");+ expect(+ withoutReasoningReplayPlaceholder(`${DEEPSEEK_REASONING_REPLAY_PLACEHOLDER}\nreal plan`),+ ).toBe("real plan");+ expect(+ withoutReasoningReplayPlaceholder(+ `${DEEPSEEK_REASONING_REPLAY_PLACEHOLDER} ${DEEPSEEK_REASONING_REPLAY_PLACEHOLDER}real plan`,+ ),+ ).toBe("real plan");+ // The model's observed rewrite of the echoed placeholder.+ expect(withoutReasoningReplayPlaceholder("[reasoning retained for this turn] plan")).toBe("plan");+ });++ it("leaves real reasoning, including a later mention, unchanged", () => {+ expect(withoutReasoningReplayPlaceholder("real plan")).toBe("real plan");+ const mention = `the relay sent ${DEEPSEEK_REASONING_REPLAY_PLACEHOLDER} earlier`;+ expect(withoutReasoningReplayPlaceholder(mention)).toBe(mention);+ });+});diff --git a/packages/shared/src/provider-presets.ts b/packages/shared/src/provider-presets.tsindex 7c80cd234..fff151f03 100644--- a/packages/shared/src/provider-presets.ts+++ b/packages/shared/src/provider-presets.ts@@ -527,6 +527,23 @@ export function isOfficialDeepSeekEndpoint(input: { baseUrl?: string }): booleanexport const DEEPSEEK_REASONING_REPLAY_PLACEHOLDER ="[reasoning not retained for this turn]";+/**+ * The placeholder a model echoed back as the start of its own reasoning (and+ * its observed `[reasoning retained for this turn]` rewrite), repeated or not.+ */+const ECHOED_REASONING_REPLAY_PLACEHOLDER =+ /^(?:\s*\[reasoning (?:not )?retained for this turn\])+\s*/;++/**+ * Thinking without a leading echo of {@link DEEPSEEK_REASONING_REPLAY_PLACEHOLDER}.+ * Models read the replayed placeholder as their previous reasoning and+ * continued it, so persisted thinking can start with it (#1945). It is not+ * reasoning: it is neither shown nor replayed. Stored text is not rewritten.+ */+export function withoutReasoningReplayPlaceholder(thinking: string): string {+ return thinking.replace(ECHOED_REASONING_REPLAY_PLACEHOLDER, "");+}+export type DeepSeekRequestCompat = {requiresReasoningContentOnAssistantMessages: true;/**diff --git a/patches/@[email protected] b/patches/@[email protected]index 1e34fd3db..a0c855cde 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -378,7 +378,7 @@ index 42aac9d5f..6001ce47a 100644const effort = options.reasoningEffort === "none"? model.thinkingLevelMap?.off === undefineddiff --git a/dist/api/openai-completions.js b/dist/api/openai-completions.js-index 0eeaffa96..50ceb5fdd 100644+index 0eeaffa96..a67f425af 100644--- a/dist/api/openai-completions.js+++ b/dist/api/openai-completions.js@@ -1046,21 +1046,27 @@ export function convertMessages(model, context, compat, options) {@@ -415,7 +415,7 @@ index 0eeaffa96..50ceb5fdd 100644}params.push(assistantMsg);}-@@ -1128,6 +1134,41 @@ export function convertMessages(model, context, compat, options) {+@@ -1128,6 +1134,49 @@ export function convertMessages(model, context, compat, options) {}lastRole = msg.role;}@@ -430,14 +430,20 @@ index 0eeaffa96..50ceb5fdd 100644+ // Placeholder text must match DEEPSEEK_REASONING_REPLAY_PLACEHOLDER in+ // @pi-desktop/shared provider-presets.+ const reasoningFields = ["reasoning_content", "reasoning_text", "reasoning"];++ // The history can mix field names: a rebuilt row is stamped++ // reasoning_content while a live row keeps the field the relay streamed.++ // The newest row's field is the one the upstream speaks, so every row is++ // normalized to it; filling it on a row whose real reasoning sat under++ // another name put the placeholder where the model reads, and the model++ // echoed it as its own reasoning (#1945). One field per row: relays reject++ // a duplicate reasoning field.++ const realReasoningField = (m) => reasoningFields.find((field) => typeof m[field] === "string" &&++ m[field].length > 0);+ if (compat.requiresReasoningContentOnAssistantMessages) {+ let activeField;-+ for (const field of reasoningFields) {-+ if (params.some((m) => m.role === "assistant" &&-+ typeof m[field] === "string" &&-+ m[field].length > 0)) {-+ activeField = field;-+ break;++ for (let index = params.length - 1; index >= 0 && !activeField; index--) {++ if (params[index].role === "assistant") {++ activeField = realReasoningField(params[index]);+ }+ }+ if (!activeField && model.reasoning) {@@ -448,16 +454,18 @@ index 0eeaffa96..50ceb5fdd 100644+ ? "[reasoning not retained for this turn]"+ : "";+ for (const m of params) {-+ if (m.role === "assistant" && m[activeField] === undefined) {-+ m[activeField] = fill;-+ }++ if (m.role !== "assistant") continue;++ const sourceField = realReasoningField(m);++ const reasoning = sourceField ? m[sourceField] : fill;++ for (const field of reasoningFields) delete m[field];++ m[activeField] = reasoning;+ }+ }+ }return params;}function convertTools(tools, compat) {-@@ -1272,6 +1313,9 @@ function detectCompat(model) {+@@ -1272,6 +1321,9 @@ function detectCompat(model) {requiresAssistantAfterToolResult: false,requiresThinkingAsText: false,requiresReasoningContentOnAssistantMessages: isDeepSeek,@@ -467,7 +475,7 @@ index 0eeaffa96..50ceb5fdd 100644thinkingFormat: isDeepSeek? "deepseek": isZai-@@ -1325,6 +1369,8 @@ function getCompat(model) {+@@ -1325,6 +1377,8 @@ function getCompat(model) {requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ??detected.requiresReasoningContentOnAssistantMessages,@@ -1250,7 +1258,7 @@ index 45be26d82..59a980b63 100644\ No newline at end of filediff --git a/dist/utils/hosted-search.d.ts b/dist/utils/hosted-search.d.tsnew file mode 100644-index 000000000..a76ae5269+index 0000000000000000000000000000000000000000..a76ae5269313931b8476e1f153e76792875ad54c--- /dev/null+++ b/dist/utils/hosted-search.d.ts@@ -0,0 +1,10 @@@@ -1266,7 +1274,7 @@ index 000000000..a76ae5269+export declare function validateHostedSearchMessages(messages: readonly Message[]): void;diff --git a/dist/utils/hosted-search.js b/dist/utils/hosted-search.jsnew file mode 100644-index 000000000..b98cb8d12+index 0000000000000000000000000000000000000000..b98cb8d128310273014e4490e9c26144f45b56af--- /dev/null+++ b/dist/utils/hosted-search.js@@ -0,0 +1,97 @@@@ -1369,7 +1377,7 @@ index 000000000..b98cb8d12+}diff --git a/dist/utils/local-request-error.d.ts b/dist/utils/local-request-error.d.tsnew file mode 100644-index 000000000..a72f65b33+index 0000000000000000000000000000000000000000..a72f65b33c64b89f118a59bd286e62624711fd90--- /dev/null+++ b/dist/utils/local-request-error.d.ts@@ -0,0 +1,15 @@@@ -1390,7 +1398,7 @@ index 000000000..a72f65b33+export declare function prepareLocalRequest<T>(phase: LocalRequestErrorPhase, prepare: () => T): T;diff --git a/dist/utils/local-request-error.js b/dist/utils/local-request-error.jsnew file mode 100644-index 000000000..4d276ddc8+index 0000000000000000000000000000000000000000..4d276ddc8caee98dfeeeeaa9bcd234ad63dc414b--- /dev/null+++ b/dist/utils/local-request-error.js@@ -0,0 +1,38 @@@@ -1434,7 +1442,7 @@ index 000000000..4d276ddc8+}diff --git a/dist/utils/local-request-stream.d.ts b/dist/utils/local-request-stream.d.tsnew file mode 100644-index 000000000..879b78cbe+index 0000000000000000000000000000000000000000..879b78cbecb0cc2c4322049ed2c7d61f77be9375--- /dev/null+++ b/dist/utils/local-request-stream.d.ts@@ -0,0 +1,3 @@@@ -1443,7 +1451,7 @@ index 000000000..879b78cbe+export declare function withLocalRequestErrors(model: Model<Api>, options: { signal?: AbortSignal } | undefined, prepare: () => AssistantMessageEventStream): AssistantMessageEventStream;diff --git a/dist/utils/local-request-stream.js b/dist/utils/local-request-stream.jsnew file mode 100644-index 000000000..5c63b882a+index 0000000000000000000000000000000000000000..5c63b882ae4cb618e964c5d2ce8d3c18e0fe4688--- /dev/null+++ b/dist/utils/local-request-stream.js@@ -0,0 +1,24 @@diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3e84a30f5..1ecfcf568 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -206,7 +206,7 @@ overrides:patchedDependencies:'@earendil-works/[email protected]': afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0- '@earendil-works/[email protected]': 14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12+ '@earendil-works/[email protected]': fd558db9c2c721be64b04b9257f2e2f034a95df5257801a56caa578f9f634f98'@earendil-works/[email protected]': 5cb7070ec8e1695932e9968afa6828b36beb1face77418739d5cd01b2a07c371importers:@@ -234,7 +234,7 @@ importers:devDependencies:'@earendil-works/pi-ai':specifier: 1.3.0- version: 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 1.3.0(patch_hash=fd558db9c2c721be64b04b9257f2e2f034a95df5257801a56caa578f9f634f98)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-mcp':specifier: 1.3.0version: 1.3.0@@ -432,7 +432,7 @@ importers:version: 1.3.0(patch_hash=afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-ai':specifier: 1.3.0- version: 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 1.3.0(patch_hash=fd558db9c2c721be64b04b9257f2e2f034a95df5257801a56caa578f9f634f98)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-coding-agent':specifier: 1.3.0version: 1.3.0(patch_hash=5cb7070ec8e1695932e9968afa6828b36beb1face77418739d5cd01b2a07c371)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])@@ -5069,7 +5069,7 @@ snapshots:'@earendil-works/[email protected](patch_hash=afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:- '@earendil-works/pi-ai': 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ '@earendil-works/pi-ai': 1.3.0(patch_hash=fd558db9c2c721be64b04b9257f2e2f034a95df5257801a56caa578f9f634f98)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])typebox: 1.3.27transitivePeerDependencies:- '@aws-sdk/credential-provider-node'@@ -5084,7 +5084,7 @@ snapshots:- ws- zod- '@earendil-works/[email protected](patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=fd558db9c2c721be64b04b9257f2e2f034a95df5257801a56caa578f9f634f98)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@anthropic-ai/sdk': 0.129.0([email protected])'@aws-sdk/client-bedrock-runtime': 3.1127.0@@ -5109,7 +5109,7 @@ snapshots:- ws- zod- '@earendil-works/[email protected](patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=fd558db9c2c721be64b04b9257f2e2f034a95df5257801a56caa578f9f634f98)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@anthropic-ai/sdk': 0.129.0([email protected])'@aws-sdk/client-bedrock-runtime': 3.1127.0@@ -5141,7 +5141,7 @@ snapshots:'@earendil-works/[email protected](patch_hash=5cb7070ec8e1695932e9968afa6828b36beb1face77418739d5cd01b2a07c371)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':dependencies:'@earendil-works/pi-agent-core': 1.3.0(patch_hash=afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])- '@earendil-works/pi-ai': 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ '@earendil-works/pi-ai': 1.3.0(patch_hash=fd558db9c2c721be64b04b9257f2e2f034a95df5257801a56caa578f9f634f98)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-codemode': 1.3.0'@earendil-works/pi-mcp': 1.3.0'@earendil-works/pi-tui': 1.3.0