Просмотр исходного кода

Merge remote-tracking branch 'github/master' into feat/web-queue-steer-all

# Conflicts:
#	packages/client/ui-conversation/README.i18n.yaml
_Kerman 2 месяцев назад
Родитель
Сommit
07854f017e
100 измененных файлов с 1829 добавлено и 431 удалено
  1. 2 2
      .agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml
  2. 0 0
      .agents/notes/implemented/architecture/2026-07-30-web-config-plane.md
  3. 0 0
      .agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md
  4. 6 0
      .agents/notes/implemented/architecture/2026-07-31-code-runtime-portable-identifier-seam.i18n.yaml
  5. 44 0
      .agents/notes/implemented/architecture/2026-07-31-code-runtime-portable-identifier-seam.md
  6. 44 0
      .agents/notes/implemented/architecture/2026-07-31-code-runtime-portable-identifier-seam.zh.md
  7. 2 2
      .agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.i18n.yaml
  8. 2 0
      .agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md
  9. 2 0
      .agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.zh.md
  10. 6 0
      .agents/notes/implemented/bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.i18n.yaml
  11. 31 0
      .agents/notes/implemented/bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.md
  12. 31 0
      .agents/notes/implemented/bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.zh.md
  13. 6 0
      .agents/notes/implemented/bug-fix/2026-08-06-provider-credential-lifecycle.i18n.yaml
  14. 27 0
      .agents/notes/implemented/bug-fix/2026-08-06-provider-credential-lifecycle.md
  15. 27 0
      .agents/notes/implemented/bug-fix/2026-08-06-provider-credential-lifecycle.zh.md
  16. 2 2
      .agents/notes/implemented/feature/2026-06-15-code-mode.i18n.yaml
  17. 8 8
      .agents/notes/implemented/feature/2026-06-15-code-mode.md
  18. 8 8
      .agents/notes/implemented/feature/2026-06-15-code-mode.zh.md
  19. 2 2
      .agents/notes/implemented/feature/2026-07-29-web-message-icon-actions-and-clock.i18n.yaml
  20. 2 0
      .agents/notes/implemented/feature/2026-07-29-web-message-icon-actions-and-clock.md
  21. 2 0
      .agents/notes/implemented/feature/2026-07-29-web-message-icon-actions-and-clock.zh.md
  22. 6 0
      .agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.i18n.yaml
  23. 19 0
      .agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.md
  24. 39 0
      .agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.zh.md
  25. 6 0
      .agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.i18n.yaml
  26. 27 0
      .agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md
  27. 27 0
      .agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.zh.md
  28. 168 0
      apps/web/tests/goal-multi-turn-actions.e2e.ts
  29. 4 4
      apps/web/tests/message-actions.e2e.ts
  30. 67 24
      apps/web/tests/models-settings.e2e.ts
  31. 0 3
      apps/web/tests/snapshots/bash-abort-row/ui.expected.md
  32. 0 3
      apps/web/tests/snapshots/code-mode-round/ui.expected.md
  33. 0 3
      apps/web/tests/snapshots/cordis-tool-round/ui.expected.md
  34. 0 3
      apps/web/tests/snapshots/fresh-round-trip/ui.expected.md
  35. 52 0
      apps/web/tests/snapshots/goal-multi-turn-actions/replay.override.json
  36. 16 0
      apps/web/tests/snapshots/goal-multi-turn-actions/session.jsonl
  37. 200 0
      apps/web/tests/snapshots/goal-multi-turn-actions/ui.expected.md
  38. 0 3
      apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md
  39. 0 3
      apps/web/tests/snapshots/live-interactions/cancel.expected.md
  40. 0 3
      apps/web/tests/snapshots/live-interactions/error-auth.expected.md
  41. 0 3
      apps/web/tests/snapshots/live-interactions/loading.expected.md
  42. 0 3
      apps/web/tests/snapshots/live-interactions/retry.expected.md
  43. 0 3
      apps/web/tests/snapshots/markdown-cjk-strong/ui.expected.md
  44. 0 3
      apps/web/tests/snapshots/markdown-images/ui.expected.md
  45. 0 3
      apps/web/tests/snapshots/markdown-inline-code-links/ui.expected.md
  46. 0 3
      apps/web/tests/snapshots/math-rendering/ui.expected.md
  47. 0 6
      apps/web/tests/snapshots/message-actions/ui.expected.md
  48. 4 2
      apps/web/tests/snapshots/models-settings/configured.expected.md
  49. 4 4
      apps/web/tests/snapshots/models-settings/delete.expected.md
  50. 1 1
      apps/web/tests/snapshots/models-settings/empty.expected.md
  51. 7 0
      apps/web/tests/snapshots/models-settings/native-delete.expected.md
  52. 2 1
      apps/web/tests/snapshots/onboarding-deepseek-config/models.expected.md
  53. 0 3
      apps/web/tests/snapshots/plan-review/approved.expected.md
  54. 0 3
      apps/web/tests/snapshots/question-composer/answered.expected.md
  55. 0 3
      apps/web/tests/snapshots/queue-actions/collapsed.expected.md
  56. 0 3
      apps/web/tests/snapshots/queue-actions/editing.expected.md
  57. 0 3
      apps/web/tests/snapshots/queue-actions/preserved.expected.md
  58. 0 3
      apps/web/tests/snapshots/queue-actions/ui.expected.md
  59. 0 3
      apps/web/tests/snapshots/seeded-history/command-row.expected.md
  60. 0 3
      apps/web/tests/snapshots/seeded-history/ui.expected.md
  61. 0 3
      apps/web/tests/snapshots/steering/mid-steer.expected.md
  62. 0 6
      apps/web/tests/snapshots/steering/settled.expected.md
  63. 0 2
      apps/web/tests/snapshots/subagent-conversation/nested.expected.md
  64. 0 6
      apps/web/tests/snapshots/subagent-conversation/ui.expected.md
  65. 35 0
      apps/web/tests/snapshots/turn-tail-actions/running.expected.md
  66. 36 0
      apps/web/tests/snapshots/turn-tail-actions/session.jsonl
  67. 40 0
      apps/web/tests/snapshots/turn-tail-actions/settled.expected.md
  68. 0 3
      apps/web/tests/snapshots/web-search-round/ui.expected.md
  69. 152 0
      apps/web/tests/turn-tail-actions.e2e.ts
  70. 2 0
      apps/web/tsconfig.json
  71. 8 4
      docs/config-catalog.md
  72. 6 6
      docs/cordis-catalog/events.md
  73. 2 2
      docs/cordis-catalog/services.md
  74. 2 2
      docs/core-data-structures/code-runtime.i18n.yaml
  75. 18 4
      docs/core-data-structures/code-runtime.md
  76. 18 4
      docs/core-data-structures/code-runtime.zh.md
  77. 6 6
      docs/event-producer-consumer.md
  78. 2 2
      docs/tool-catalog.md
  79. 2 2
      packages/client/ui-conversation/README.i18n.yaml
  80. 3 3
      packages/client/ui-conversation/README.md
  81. 3 3
      packages/client/ui-conversation/README.zh.md
  82. 7 10
      packages/client/ui-conversation/src/client/chat/AssistantMarkdown.tsx
  83. 6 7
      packages/client/ui-conversation/src/client/chat/ChatView.tsx
  84. 3 5
      packages/client/ui-conversation/src/client/chat/MessageIconActions.tsx
  85. 5 12
      packages/client/ui-conversation/src/client/chat/MessageItem.tsx
  86. 27 13
      packages/client/ui-conversation/src/client/chat/chat-flow.ts
  87. 29 35
      packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx
  88. 55 26
      packages/client/ui-conversation/tests/chat-view.spec.tsx
  89. 2 2
      packages/client/ui-models/README.i18n.yaml
  90. 0 1
      packages/client/ui-models/README.md
  91. 0 1
      packages/client/ui-models/README.zh.md
  92. 31 0
      packages/client/ui-models/src/client/ModelsSection.module.css
  93. 166 55
      packages/client/ui-models/src/client/ModelsSection.tsx
  94. 33 16
      packages/client/ui-models/src/client/ProviderEditor.tsx
  95. 22 8
      packages/client/ui-models/src/client/locales.ts
  96. 0 12
      packages/client/ui-models/src/client/store.ts
  97. 3 3
      packages/client/ui-models/tests/apply.spec.ts
  98. 183 35
      packages/client/ui-models/tests/components.spec.tsx
  99. 17 1
      packages/client/ui-models/tests/provider-form.spec.tsx
  100. 2 2
      packages/code-runtime/README.i18n.yaml

+ 2 - 2
.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-30-web-config-plane.md
-2026-07-30-web-config-plane.md: 5225460be1d66b85a05ff2fd5ae2826b0e6c41d7
-2026-07-30-web-config-plane.zh.md: 53a21ddf31640d963c413e1793276de694547311
+2026-07-30-web-config-plane.md: 11554077d1848dcdf59b896dd9c29a39fd2f55d4
+2026-07-30-web-config-plane.zh.md: 527c2de8155a56789358b801f9c374e16c81931b

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md


Разница между файлами не показана из-за своего большого размера
+ 0 - 0
.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md


+ 6 - 0
.agents/notes/implemented/architecture/2026-07-31-code-runtime-portable-identifier-seam.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-code-runtime-portable-identifier-seam.md
+2026-07-31-code-runtime-portable-identifier-seam.md: 9e9df50235b3505458e3645e2c6ff6e9bd439183
+2026-07-31-code-runtime-portable-identifier-seam.zh.md: 31d2410ee4809d0693f2e7897e61c50163bb0758

+ 44 - 0
.agents/notes/implemented/architecture/2026-07-31-code-runtime-portable-identifier-seam.md

@@ -0,0 +1,44 @@
+# Agent Note: the code-runtime seam owns portable-identifier exclusions
+
+Status: implemented
+
+English | [中文](2026-07-31-code-runtime-portable-identifier-seam.zh.md)
+
+## Problem
+
+The code-runtime seam promises that a binding-namespace list valid on one backend is valid on every backend, so a Code Mode consumer can hand the same bindings to any registered runtime without knowing its language. The first backend, `dsh-code-runtime-worker`, privately owned the identifier rules that enforce part of that promise: an `IDENTIFIER` regex that allowed the JS-only `$`, a `RESERVED_WORDS` set holding only ECMAScript keywords, and a `RESERVED_ERROR_PROPERTIES` set of three JS `Error` slots. Those rules described the worker's own language, not the seam's portability contract.
+
+A second backend written against a different language (CPython, arriving in a later PR of this stack) would either re-declare its own rules — letting `lambda` pass the worker and fail Python, or `$tools` pass the worker and fail every non-JS backend — or import the worker's, inverting the dependency so the seam's implementation reached into a sibling implementation. Neither keeps the portability promise real: it would hold only for the backend a caller happened to test against.
+
+## Decision
+
+The seam package (`@deepseek-ai/dsh-code-runtime`) exports the portable-identifier exclusion contract as four named constants, and every backend imports them rather than re-declaring:
+
+- `PORTABLE_RESERVED_WORDS` — the union of ECMAScript and Python reserved words. A namespace global or error-class name matching any is refused on all backends, so `lambda` is refused even though it is a legal JS parameter name. Adding a language widens this union, which is a deliberate breaking review of existing binding names.
+- `RESERVED_BINDING_GLOBALS` — globals some backend owns in the program's namespace: `console` (the worker's log capture), `__dsh_main__`/`__builtins__`/`__name__` (the Python bootstrap's wrapper and seeded module globals), and `__debug__` (not a seeded slot but a CPython compile-time constant that rejects assignment, so an injected global under that name is unreachable — the same portability split by a different mechanism). Refused everywhere so a namespace list cannot pick a name that works on one backend and collides on another.
+- `RESERVED_ERROR_MEMBERS` — error-member names every backend refuses: the JS `Error` slots (`name`, `message`, `stack`) and Python's exception-protocol members (`args`, `with_traceback`, `add_note`).
+- `DUNDER_MEMBER` — the dunder-form regex (`__x__`, non-empty middle), refused as an error member wholesale because several are constrained CPython descriptors whose exact set is an interpreter-version detail.
+
+The seam also narrows the portable identifier subset to `[A-Za-z_][A-Za-z0-9_]*` (documented on `CodeBindingNamespace.global` and `CodeBindingErrorClass`), dropping the JS-only `$`. The worker consumes the shared constants directly by their seam names — `PORTABLE_RESERVED_WORDS` for both binding-global and error-class names, `RESERVED_BINDING_GLOBALS` for backend-owned slots, `RESERVED_ERROR_MEMBERS` plus `DUNDER_MEMBER` for error members — with no local re-alias; its `IDENTIFIER` regex loses `$`.
+
+The constants live at the seam even though only one backend ships in this PR: the whole point is that the contract is language-agnostic and owned above any single language. A backend that violated it would be the bug, and the shared set is where a reviewer looks to see what "portable" means.
+
+## Scope
+
+This PR delivers only the seam extension and the worker's adoption of it. No Python backend, `py-types` renderer, or Code Mode language dispatch ships here — they are later PRs in the stack that depend on these exports. The seam README's worker-only wording is left unchanged for the same reason: linking to a `dsh-code-runtime-python` README that does not yet exist would break the dead-link gate.
+
+`RESERVED_BINDING_GLOBALS` currently encodes the not-yet-merged Python bootstrap's concrete design: it seeds exactly `__builtins__`/`__name__` and wraps the program under `__dsh_main__`. The Python-backend PR that seeds any additional module global (`__doc__`, `__loader__`, `__spec__`, `__file__`, `__package__`, …) MUST widen this set in the same change, exactly as adding a language widens `PORTABLE_RESERVED_WORDS` — a name the bootstrap seeds but the set omits is the portability split this contract exists to prevent.
+
+## Alternatives considered
+
+**Each backend declares its own exclusions.** Rejected: it makes the portability promise per-backend. A binding list the caller tested on the worker could be refused by Python, which is exactly the split the seam exists to prevent.
+
+**The Python backend imports the worker's constants.** Rejected: it inverts the dependency — the seam's implementations would reach into a sibling implementation for a contract neither owns. The contract belongs above both, at the seam.
+
+**Keep `$` in the portable identifier subset.** Rejected: `$` is JS-only spelling. Allowing it would let `$tools` pass the worker and fail every non-JS backend, breaking portability for a purely cosmetic gain.
+
+## Consequences
+
+Bought: one place — the seam package — defines what a portable binding name is, and every backend enforces the same contract by import. A namespace list valid on one backend is valid on all, verifiably, not by coincidence of which backend the caller tested.
+
+Cost: existing worker callers using a `$`-containing global now fail identifier validation. Under the pre-release stance this is a corrected foundation, not a compatibility break to shim. The worker's seam-misuse tests gain cases for `$tools`, Python exception members (`args`), dunders (`__dict__`), and a Python-owned global (`__dsh_main__`), proving the shared set is enforced from the worker side.

+ 44 - 0
.agents/notes/implemented/architecture/2026-07-31-code-runtime-portable-identifier-seam.zh.md

@@ -0,0 +1,44 @@
+# Agent Note:code-runtime seam 拥有可移植标识符排除集
+
+Status: implemented
+
+[English](2026-07-31-code-runtime-portable-identifier-seam.md) | 中文
+
+## Problem
+
+code-runtime seam 承诺:在一个后端上有效的绑定命名空间列表,在每个后端上都有效,因此 Code Mode 消费方可以把同一组绑定交给任何已注册的运行时,而不必知道它的语言。首个后端 `dsh-code-runtime-worker` 私自拥有了执行这项承诺一部分的标识符规则:一个允许 JS 专有 `$` 的 `IDENTIFIER` 正则、一个只含 ECMAScript 关键字的 `RESERVED_WORDS` 集合,以及一个含三个 JS `Error` 槽位的 `RESERVED_ERROR_PROPERTIES` 集合。这些规则描述的是 worker 自身的语言,而非 seam 的可移植性契约。
+
+一个针对不同语言(CPython,将在本 stack 后续 PR 中到来)编写的第二后端,要么重新声明自己的规则——让 `lambda` 通过 worker 却在 Python 上失败,或让 `$tools` 通过 worker 却在每个非 JS 后端上失败——要么导入 worker 的规则,从而反转依赖,使 seam 的一个实现伸手进入另一个兄弟实现。二者都无法让可移植承诺成真:它只对调用方恰好测试过的那个后端成立。
+
+## Decision
+
+seam 包(`@deepseek-ai/dsh-code-runtime`)以四个具名常量导出可移植标识符排除契约,每个后端导入它们而非重新声明:
+
+- `PORTABLE_RESERVED_WORDS`——ECMAScript 与 Python 保留字的联集。任何命名空间 global 或 error-class 名称匹配其中之一,都在所有后端上被拒绝,因此 `lambda` 即便是合法的 JS 参数名也被拒绝。新增一门语言即扩宽此联集,这是对现有绑定名称的一次有意的破坏性复审。
+- `RESERVED_BINDING_GLOBALS`——某个后端在程序命名空间中拥有的 global:`console`(worker 的日志捕获)、`__dsh_main__`/`__builtins__`/`__name__`(Python bootstrap 的包装器与预置模块 global),以及 `__debug__`(不是 seed 的槽位,而是 CPython 编译期常量,赋值会被拒,故以该名注入的 global 不可达——同一种可移植性分裂,只是机制不同)。在所有后端上被拒绝,使命名空间列表无法选到一个在某后端能用、在另一后端冲突的名称。
+- `RESERVED_ERROR_MEMBERS`——每个后端都拒绝的 error-member 名称:JS `Error` 槽位(`name`、`message`、`stack`)与 Python 异常协议成员(`args`、`with_traceback`、`add_note`)。
+- `DUNDER_MEMBER`——dunder 形式正则(`__x__`,非空中缀),作为 error member 被整体拒绝,因为其中若干是受约束的 CPython 描述符,其确切集合是解释器版本细节。
+
+seam 同时把可移植标识符子集收窄为 `[A-Za-z_][A-Za-z0-9_]*`(记录在 `CodeBindingNamespace.global` 与 `CodeBindingErrorClass` 上),去掉 JS 专有的 `$`。worker 直接以 seam 名消费这些共享常量——binding-global 与 error-class 名称用 `PORTABLE_RESERVED_WORDS`、后端拥有槽位用 `RESERVED_BINDING_GLOBALS`、error member 用 `RESERVED_ERROR_MEMBERS` 加 `DUNDER_MEMBER`——不再本地起别名;其 `IDENTIFIER` 正则去掉 `$`。
+
+尽管本 PR 只交付一个后端,这些常量仍置于 seam:要点正是该契约与语言无关,且拥有权在任何单一语言之上。违反它的后端才是 bug,而共享集合正是复审者查看"可移植"含义的地方。
+
+## Scope
+
+本 PR 只交付 seam 扩展与 worker 对它的采用。这里不交付任何 Python 后端、`py-types` 渲染器或 Code Mode 的语言分发——它们是本 stack 中依赖这些导出的后续 PR。seam README 中仅描述 worker 的措辞保持不变,理由相同:链接到一个尚不存在的 `dsh-code-runtime-python` README 会破坏死链 gate。
+
+`RESERVED_BINDING_GLOBALS` 当前编码了尚未合并的 Python bootstrap 的具体设计:它恰好 seed `__builtins__`/`__name__`,并把程序包装在 `__dsh_main__` 之下。任何 seed 额外模块 global(`__doc__`、`__loader__`、`__spec__`、`__file__`、`__package__` 等)的 Python 后端 PR 必须在同一改动中扩宽此集合,正如新增一门语言即扩宽 `PORTABLE_RESERVED_WORDS`——bootstrap 会 seed 却不在集合中的名称,正是本契约要防止的可移植性分裂。
+
+## Alternatives considered
+
+**每个后端声明自己的排除集。** 拒绝:这让可移植承诺变成逐后端成立。调用方在 worker 上测过的绑定列表可能被 Python 拒绝,而这正是 seam 存在要防止的分裂。
+
+**Python 后端导入 worker 的常量。** 拒绝:这反转依赖——seam 的实现会为一个二者都不拥有的契约伸手进入兄弟实现。契约属于二者之上,即 seam。
+
+**在可移植标识符子集中保留 `$`。** 拒绝:`$` 是 JS 专有拼写。允许它会让 `$tools` 通过 worker 却在每个非 JS 后端上失败,为纯粹表面的好处破坏可移植性。
+
+## Consequences
+
+获得:一个地方——seam 包——定义什么是可移植绑定名称,每个后端通过导入执行同一契约。在一个后端上有效的命名空间列表在所有后端上都有效,这是可验证的,而非取决于调用方测试了哪个后端的巧合。
+
+代价:现有使用含 `$` global 的 worker 调用方现在会在标识符校验时失败。在预发布立场下这是一次被纠正的地基,而非需要 shim 的兼容性破坏。worker 的 seam-misuse 测试新增了 `$tools`、Python 异常成员(`args`)、dunder(`__dict__`)与一个 Python 拥有的 global(`__dsh_main__`)等用例,从 worker 侧证明共享集合被执行。

+ 2 - 2
.agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md
-2026-08-02-message-fork-actions-require-completed-turn-tail.md: f2e7fd67b65a6ce4a86ba3f4405f78842be8f234
-2026-08-02-message-fork-actions-require-completed-turn-tail.zh.md: 2c3feeaa3ef01dbde67faa73257520918996f9c8
+2026-08-02-message-fork-actions-require-completed-turn-tail.md: abdcbc79948c67619bb70a8a87741046f65b8838
+2026-08-02-message-fork-actions-require-completed-turn-tail.zh.md: a93b572c6db3c76ce3869747fd9a7660bf3ea395

+ 2 - 0
.agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md

@@ -12,6 +12,8 @@ The Web conversation attached branch to the last assistant node with nonempty te
 
 `ConversationSnapshot.turnEnds` retains the completed turn boundaries present in the raw event window. The conversation view walks transcript nodes through each boundary and enables branch only when the boundary's last node is a user message, a durable steering message, or a content-bearing assistant message. Open turns have no eligible message, and a later tool result, reasoning-only interruption, turn error, or other transcript node leaves branch unavailable on earlier messages. The unavailable control stays visible, focusable, and hoverable; `aria-disabled`, a tooltip, and `aria-describedby` explain the completed-tail requirement without sending a Host request. Copy and clock remain available under their existing message chrome, and the Host's completed-turn fork semantics remain unchanged.
 
+The message-bubble half of this eligibility is superseded by the [user-bubble branch removal](../simplification/2026-08-06-user-bubbles-drop-the-branch-action.md): user and steering bubbles no longer render the control at all, so only content-assistant tails may fork; the assistant-side gate and its visible-but-unavailable presentation stand.
+
 This narrows the message eligibility established by the earlier [Web session fork action decision](../feature/2026-07-27-web-session-fork-actions.md). Session-row forking still selects the latest completed turn, and eligible message actions still pass their event seq through the shared client runtime operation.
 
 ## Alternatives considered

+ 2 - 0
.agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.zh.md

@@ -12,6 +12,8 @@ Web 会话把分支操作挂到每个轮次中最后一个文本非空的 assist
 
 `ConversationSnapshot.turnEnds` 保留原始事件窗口中的已完成轮次边界。会话视图按各边界遍历 transcript(文本记录)节点,仅当边界的最后一个节点是用户消息、持久 steering(中途引导)消息或含内容的 assistant 消息时才启用分支操作。开放轮次没有符合条件的消息;如果后面还有工具结果、只有推理内容的中断、轮次错误或其他 transcript 节点,较早消息上的分支操作会保持不可用。不可用的控件仍然可见、可聚焦、可悬停;`aria-disabled`、tooltip 与 `aria-describedby` 会说明已完成尾部这一要求,且不会发送 Host 请求。复制和时钟仍可在既有消息 chrome 下使用,Host 按已完成轮次 fork 的语义保持不变。
 
+本资格判定中消息气泡的那一半已被 [user 气泡分支移除决策](../simplification/2026-08-06-user-bubbles-drop-the-branch-action.md)取代:user 与 steering 气泡不再渲染该控件,因此只有内容 assistant 尾部可以 fork;assistant 侧门禁及其可见但不可用的呈现保持有效。
+
 本决策收紧了较早的 [Web 会话 fork 操作决策](../feature/2026-07-27-web-session-fork-actions.md)所定义的消息资格。Session 行 fork 仍选择最新的已完成轮次;符合条件的消息操作仍通过共享 client 运行时操作传递其事件 seq。
 
 ## 考虑过的替代方案

+ 6 - 0
.agents/notes/implemented/bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.md
+2026-08-05-turn-tail-actions-require-a-completed-turn.md: 689d50bb86c830d6e428239f112568f00d74c9b8
+2026-08-05-turn-tail-actions-require-a-completed-turn.zh.md: 2cc426bbb82acb8f57d491b0f068e89771699357

+ 31 - 0
.agents/notes/implemented/bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.md

@@ -0,0 +1,31 @@
+# Agent Note: Turn-tail IconActions require a completed turn
+
+Status: implemented
+
+English | [中文](2026-08-05-turn-tail-actions-require-a-completed-turn.zh.md)
+
+## Problem
+
+Assistant IconActions were derived from the finalized transcript alone: the last content-text assistant of each turn owned the row. That quantity is stable only after the turn closes. While a turn is still producing steps, the narration a model writes before a tool call *is* the last content assistant so far, so it took the row for as long as the tool ran and then lost it to the next step's text. Readers saw copy, branch, and a clock appear under an intermediate sentence, shift the flow by one 28px row, and disappear. The row was also incoherent in that state: its branch control was already disabled through `turnEnds`, and its `Ran for` label was already withheld through `turnTimings`, so only copy worked.
+
+The [message chrome decision](../feature/2026-07-29-web-message-icon-actions-and-clock.md) always claimed mid-turn narration stays chrome-free; the derivation never carried a completion signal to make that true.
+
+## Decision
+
+`assistantActionsSeqs` takes `ConversationSnapshot.turnEnds` and grants the row only within a turn that has a `turn/end` in the window. Ownership inside a completed turn is unchanged: its last content-text assistant. A turn still producing steps grants nothing, so its narration never mounts the row, and the seat appears once, under the settled answer, when the turn closes.
+
+This is the same completion fact the branch control and the run-time label already use, so the three parts of one row now agree. Turn completion is read from the durable `turn/end` event rather than inferred from `running`, the streaming partial, or in-flight tool calls, matching the [completed-turn-tail decision](2026-08-02-message-fork-actions-require-completed-turn-tail.md). Every reason kind closes a turn, so an aborted turn's frozen tail keeps its footer, and a crash-orphaned turn receives its `turn/end` from log repair on load.
+
+`hasContentText` moves to `chat-flow.ts` and `AssistantMarkdown` imports it, so the ownership gate and the mount gate cannot drift apart.
+
+## Alternatives considered
+
+**Withhold by naming the open turn from `running` plus the streaming partial or the first in-flight tool call.** This shipped briefly in the original change and was then dropped. It infers completion instead of reading it, needs a special case so a turn accepted before its first step does not strip the previous answer's seat, and is the inference the completed-turn-tail decision rejected for the branch control. `turnEnds` answers the same question per turn with no inference and no special case.
+
+**Leave the row mounted mid-turn and disable its controls.** Rejected: mid-turn narration is not a degraded answer, it is not the answer. Copy would still write an intermediate sentence, and the row would still move to the real tail at turn end.
+
+**Keep the row under every finalized content node permanently.** Rejected again here for the reason the original decision gave: repeating copy, branch, and a clock under every step clutters the flow. It also does not solve the reported problem, since the branch control is only meaningful on the tail.
+
+## Consequences
+
+A running turn carries no message footer below the user bubble that triggered it, while every earlier completed turn keeps its own; the seat appears once when `turn/end` lands, which adds one 28px row under the settled answer at that moment. A turn whose `turn/end` is outside the loaded window grants nothing, which cannot arise from paging because a turn's end follows its own nodes. `apps/web/tests/turn-tail-actions.e2e.ts` pins both states through the assembled application: a `hang` sidecar on the second model call parks a turn whose first step narrated before calling bash, and the two goldens hold the parked flow and the flow after stopping. Package tests cover the derivation directly and the running-turn render.

+ 31 - 0
.agents/notes/implemented/bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.zh.md

@@ -0,0 +1,31 @@
+# Agent Note: 轮次尾部 IconActions 要求轮次已完成
+
+Status: implemented
+
+[English](2026-08-05-turn-tail-actions-require-a-completed-turn.md) | 中文
+
+## 问题
+
+assistant IconActions 此前只从已定稿的 transcript(文本记录)推导:每个轮次中最后一条含内容文本的 assistant 拥有该行。这个量只有在轮次关闭后才稳定。轮次仍在产出步骤时,模型在工具调用前写下的叙述就是当时该轮次的最后一条内容 assistant,于是它在工具执行期间取得该行,等下一步的文本落定又把它交出去。读者会看到复制、分支和时钟出现在一句中间叙述下方,把流程推开一行 28px,然后消失。该行在这个状态下本身也是残缺的:分支控件已经通过 `turnEnds` 判定为禁用,`Ran for` 标签已经通过 `turnTimings` 判定为不显示,只有复制可用。
+
+[消息 chrome 决策](../feature/2026-07-29-web-message-icon-actions-and-clock.md)一直声称轮次中间的叙述不带 chrome,但推导过程从未拿到能让这句话成立的完成信号。
+
+## 决策
+
+`assistantActionsSeqs` 接收 `ConversationSnapshot.turnEnds`,只在事件窗口中存在该轮次 `turn/end` 时才授予该行。已完成轮次内部的归属不变,仍是其最后一条含内容文本的 assistant。仍在产出步骤的轮次不授予任何座位,因此其叙述不会挂载该行;轮次关闭时,座位在已定稿答案下方一次性出现。
+
+这与分支控件和运行时长标签使用的完成事实相同,因此同一行的三个部分现在口径一致。轮次是否完成读自持久的 `turn/end` 事件,而不是从 `running`、流式 partial 或在途工具调用推断,与[已完成轮次尾部决策](2026-08-02-message-fork-actions-require-completed-turn-tail.md)一致。任何 reason 类别都会关闭轮次,因此已中止轮次冻结的尾部保留其操作栏,而崩溃遗留的开放轮次会在加载时由日志修复补上 `turn/end`。
+
+`hasContentText` 移入 `chat-flow.ts`,由 `AssistantMarkdown` 导入,使归属门控与挂载门控无法各自漂移。
+
+## 考虑过的替代方案
+
+**用 `running` 加流式 partial 或第一个在途工具调用指认开放轮次,据此扣留。** 这一做法曾在最初的变更中短暂存在,随后被删除。它推断完成状态而不是读取完成状态,还需要一个特例,避免轮次已被接受但尚未产出第一步时把上一条回答的座位取走;这正是已完成轮次尾部决策为分支控件否决过的推断。`turnEnds` 按轮次回答同一个问题,不需要推断,也不需要特例。
+
+**轮次进行中保留该行,只把控件置为不可用。** 不予采纳:轮次中间的叙述不是一个降级的答案,它根本不是答案。复制仍然会写入一句中间文本,该行在轮次结束时仍然要移动到真正的尾部。
+
+**让每个已定稿的内容节点长期保留该行。** 在此重新否决,理由与最初的决策相同:在每一步下重复复制、分支和时钟会打乱流程。它也解决不了本次报告的问题,因为分支控件只有落在尾部才有意义。
+
+## 后果
+
+运行中的轮次在触发它的用户气泡之下不再有任何消息操作栏,而此前每个已完成轮次仍保留各自的座位;座位在 `turn/end` 到达时一次性出现,此刻已定稿答案下方会多出一行 28px。`turn/end` 落在加载窗口之外的轮次不授予座位,而翻页不会造成这种情况,因为一个轮次的结束事件排在它自己的节点之后。`apps/web/tests/turn-tail-actions.e2e.ts` 通过组装后的应用钉住两种状态:`hang` sidecar 作用在第二次模型调用上,把一个首步先叙述再调用 bash 的轮次挂住,两份 golden 分别记录挂起中的流程和停止之后的流程。包级测试直接覆盖该推导以及运行中轮次的渲染结果。

+ 6 - 0
.agents/notes/implemented/bug-fix/2026-08-06-provider-credential-lifecycle.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-06-provider-credential-lifecycle.md
+2026-08-06-provider-credential-lifecycle.md: ce45207e7ac7224f44e34945e36ba85db0971f09
+2026-08-06-provider-credential-lifecycle.zh.md: c476417517b8ed72036344a13720a8ba378775e6

+ 27 - 0
.agents/notes/implemented/bug-fix/2026-08-06-provider-credential-lifecycle.md

@@ -0,0 +1,27 @@
+# Agent Note: Recoverable provider credential lifecycle
+
+Status: implemented
+
+English | [中文](2026-08-06-provider-credential-lifecycle.zh.md)
+
+## Problem
+
+The Models editor spans independent settings and credential RPC domains. It previously committed provider settings before storing the API key but kept the revision and original subtree from when the card opened. If the credential write failed, retry replayed the already-committed settings mutation with a stale revision and produced a conflict, leaving the user unable to complete the second stage from the same card. A blank pi-ai key also wrote the derived `apiKeyEnv` without a credential, which prevented pi-ai from using provider-native discovery. At deletion, the inverse leak remained: the profile disappeared but its page-stored key stayed in `.env` and silently became active when the provider was added again. Generic row actions and confirmation copy did not identify which provider would be changed.
+
+## Decision
+
+Provider save remains a two-stage settings-then-credentials operation over the existing wire domains, but the card treats the successful settings response as a commit checkpoint. It replaces its comparison subtree and expected revision with the returned redacted descriptor before attempting `credentials.set`; if that second stage fails, the draft key and card stay visible, and retry produces no settings ops and repeats only the credential write. Genuine concurrent changes before the first settings commit still fail with `settings-conflict`. Typed keys are trimmed at the UI and direct DeepSeek resolver boundaries, and pi-ai records a derived reference only when the normalized key is non-empty; saving a blank key materializes an empty, reference-free profile for provider-native discovery.
+
+Deletion removes a credential only when the joined row identifies the exact `<ROUTE>_API_KEY` reference derived by this page and reports it configured and writable. It unsets that credential before the user-layer profile so a settings-stage failure leaves the row and its frozen target visible for retry; both unsets are idempotent. Custom references, environment credentials, missing credentials, and targets the join cannot identify are retained. The row's accessible Edit/Delete names and the destructive dialog title, description, and final action all use the same stable `Display Name (route-id)` identity, collapsing to the route id when both strings match. The dialog states whether the stored key will be removed and owns operation failures instead of replacing the whole page with a load-error banner. Rows expose API-key state only from the value-free join: a confirmed literal or referenced credential is a green solid dot, a confirmed missing named reference is a red solid dot, and reference-free provider-native authentication or unavailable credential enrichment has no dot. Each dot has accessible copy and a tooltip, while successful Apply uses the same provider identity in a local status message and never echoes secret material.
+
+## Alternatives considered
+
+**Add a cross-domain transaction RPC.** Settings and credentials have separate owning services and durable stores; introducing a new host transaction would broaden the public wire and still require compensation for provider-specific persistence failures. The UI checkpoint makes the current ordered stages recoverable without adding a fourth configuration contract.
+
+**Delete every credential reference named by a removed profile.** A custom reference can be shared, externally managed, or intentionally survive profile churn. Exact equality with this page's derived target plus configured+writable state is the narrow evidence available to the page; anything weaker risks deleting a credential it does not own.
+
+**Remove settings first and compensate by recreating the profile.** The browser holds only a redacted subtree and cannot faithfully reconstruct stored literal secrets or concurrent edits. Credential-first deletion leaves the authoritative profile visible on partial failure and makes retry safe without synthesizing configuration.
+
+## Consequences
+
+The Models page can recover from either second-stage failure without reload, secret disclosure, or a false concurrency conflict, and blank-key pi-ai profiles preserve Bedrock, Vertex, and other provider-native authentication. Confirmed status is visible without turning route liveness, native authentication, or a failed credential lookup into a false error, and a successful replacement remains observable even when the row stays green. Deleting a page-managed provider no longer leaves a reusable local key, while ambiguous credentials deliberately remain for manual management. Save and delete are still not atomic across durable stores: a process crash can stop between stages, but their order and idempotence leave an observable, retryable state. Component tests pin partial-success retries, empty-key native auth, normalized literals, status visibility, target identity, cleanup ownership, and credential/settings rejection ordering; the keyless browser scenario pins bilingual accessible copy and verifies that confirmed deletion removes both `settings.yaml` profile and `.env` credential. This decision refines the Models apply semantics recorded in the [web configuration plane note](../architecture/2026-07-30-web-config-plane.md).

+ 27 - 0
.agents/notes/implemented/bug-fix/2026-08-06-provider-credential-lifecycle.zh.md

@@ -0,0 +1,27 @@
+# Agent Note: 可恢复的提供方凭据生命周期
+
+Status: implemented
+
+[English](2026-08-06-provider-credential-lifecycle.md) | 中文
+
+## 问题
+
+Models 编辑器横跨互相独立的 settings 与凭据 RPC 领域。之前它先提交提供方 settings,再存储 API 密钥,却一直保留卡片打开时的 revision 和原始子树。如果凭据写入失败,重试会用陈旧 revision 重放已提交的 settings 变更,并产生冲突,导致用户无法从同一张卡片完成第二个阶段。空的 pi-ai 密钥还会写入派生的 `apiKeyEnv`,却不写入凭据,从而阻止 pi-ai 使用提供方原生凭据发现。删除时则存在相反的残留问题:profile 消失了,页面存储的密钥却保留在 `.env` 中,并在重新添加提供方时静默地恢复作用。笼统的行操作与确认文案也没有标明要更改哪个提供方。
+
+## 决策
+
+提供方保存仍在现有 wire 领域上按先 settings、后凭据的两阶段顺序执行,但卡片会把成功的 settings 响应视为提交检查点。它会在尝试 `credentials.set` 之前,用返回的脱敏 descriptor 替换比较基准子树与预期 revision;如果第二阶段失败,草稿密钥与卡片会继续显示,重试不会产生 settings op,只会再次写入凭据。首次 settings 提交之前发生的真实并发变更仍会以 `settings-conflict` 失败。UI 与 DeepSeek 直连 resolver 边界均会去除所输密钥的首尾空白,且只有标准化密钥非空时,pi-ai 才会记录派生引用;留空密钥会具化一个空的、不带引用的 profile,以便使用提供方原生凭据发现。
+
+只有当联接所得的行识别出该页面派生的精确 `<ROUTE>_API_KEY` 引用,并将其报告为已配置且可写时,删除操作才会清除该凭据。它会先取消设置该凭据,再取消设置用户层 profile;如果 settings 阶段失败,该行及其已冻结的目标仍可见,便于重试。两项 unset 都具备幂等性。自定义引用、环境凭据、缺失的凭据,以及联接无法识别目标的凭据均会保留。行的无障碍 Edit/Delete 名称以及破坏性对话框的标题、说明和最终操作都使用同一个稳定的 `Display Name (route-id)` 标识;当两个字符串相同时,标识会简化为路由 id。对话框会说明是否一并删除已存密钥,并在自身内显示操作失败,而不是用加载错误横幅替换整个页面。行只根据不含值的联接结果展示 API 密钥状态:确认已配置的字面密钥或引用凭据显示为绿色实心点,确认缺失的具名引用显示为红色实心点,无引用的提供方原生认证或无法取得凭据补充信息时则不显示状态点。每个状态点都有无障碍文案和工具提示;「应用」成功后的本地状态消息会使用同一个提供方标识,且绝不回显任何机密内容。
+
+## 曾考虑的替代方案
+
+**添加跨领域事务 RPC。**settings 与凭据分属不同的主管服务与持久存储;引入新的 Host 事务会扩大公开 wire 面,而且仍需要补偿提供方特定的持久化失败。UI 检查点让当前的有序阶段变得可恢复,无需添加第四项配置契约。
+
+**删除被移除 profile 所指定的每一个凭据引用。**自定义引用可能被共享、由外部管理,或有意在 profile 反复增删时存留。与该页面派生目标精确相等,再加上已配置且可写的状态,是页面所能获得的最小范围证据;比这更弱的判定都有可能删除不属于它的凭据。
+
+**先删除 settings,再重建 profile 以作补偿。**浏览器只持有脱敏后的子树,无法忠实重建已存的字面机密或并发编辑。先删除凭据可以让权威 profile 在部分失败时仍然可见,并且无需合成配置就能安全重试。
+
+## 后果
+
+Models 页可以从任一第二阶段失败中恢复,无需重新加载,也不会泄露机密或产生虚假的并发冲突;空密钥的 pi-ai profile 会保留 Bedrock、Vertex 与其他提供方原生认证。已确认的状态清晰可见,同时不会把路由存活状态、原生认证或凭据查询失败误报为错误;即使该行继续显示绿色,密钥替换成功也仍然可观察。删除由页面管理的提供方不再遗留可重用的本地密钥,而存在歧义的凭据会有意保留,交由手动管理。保存与删除在跨持久存储时仍非原子操作:进程可能在两个阶段之间崩溃,但它们的顺序与幂等性会留下可观察、可重试的状态。组件测试固定了部分成功后的重试、空密钥原生认证、标准化字面值、状态可见性、目标标识、清理所有权,以及凭据/settings 拒绝顺序;无密钥的浏览器场景固定了双语无障碍文案,并验证确认删除会同时清除 `settings.yaml` profile 与 `.env` 凭据。此决策细化了 [web 配置平面 note](../architecture/2026-07-30-web-config-plane.md) 中记录的 Models 应用语义。

+ 2 - 2
.agents/notes/implemented/feature/2026-06-15-code-mode.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-06-15-code-mode.md
-2026-06-15-code-mode.md: b6a24ecd9700e32912b8112b59cbd8b6ab131eb5
-2026-06-15-code-mode.zh.md: a00a43ece1e581190de6096be8138df25a23f07f
+2026-06-15-code-mode.md: 99bbed3edab32512f88ece9694d6519a1f89c2dd
+2026-06-15-code-mode.zh.md: ca1bbe9ed3e412186763d1ed4fca9ed06669d4c3

+ 8 - 8
.agents/notes/implemented/feature/2026-06-15-code-mode.md

@@ -6,7 +6,7 @@ English | [中文](2026-06-15-code-mode.zh.md)
 
 ## Problem
 
-In the registry's native presentation, the agent loop advertises every visible capability as a JSON-schema function definition. `ToolRegistry` contributes its schemas to the system-prompt assembly, the assembly's `tools` land on the wire (and in the logged request header), the model invokes one `tool-call` block per step, and the loop dispatches each call through `ctx.tools.execute()` **sequentially** (parallel tool execution is an explicit open TODO in `dsh-tools` and [docs/architecture.md](../../../../docs/architecture.md)), with **every** intermediate `tool-result` re-entering the model's context on the next request.
+In the registry's native presentation, the agent loop advertises every visible capability as a JSON-schema function definition. `ToolRegistry` contributes its schemas to the system-prompt assembly, the assembly's `tools` land on the wire (and in the logged request header), the model invokes one `tool-call` block per step, and at the time of this note the loop dispatched each call through `ctx.tools.execute()` **sequentially** (parallel tool execution was an open TODO then; bounded parallel dispatch has since shipped — the [parallel tool-call note](2026-07-10-parallel-tool-call-execution.md), the rolling pool in [docs/architecture.md](../../../../docs/architecture.md)) — with **every** intermediate `tool-result` re-entering the model's context on the next request.
 
 For multi-step tool work this is token-heavy and serial. The model cannot compose tools — loop over a result set, branch on an intermediate value, fan out, post-process — without a full model round-trip per call, and each round-trip drags the entire intermediate result back into context whether the model needs it or not.
 
@@ -32,7 +32,7 @@ This note owns Code Mode's presentation, composition, isolation, and settlement
 
 **Interaction with `toolOrder`, stated up front:** a configured `systemPrompt.toolOrder` naming native capabilities rejects every assembly under `mode: 'code'`, because those names are outside that mode's wire-validation universe. This is correct behavior, not a bug: a deployment using Code Mode updates its order config or drops it.
 
-**SDK prompt section.** In `'code'` and `'both'`, the lazy `tools:sdk` section in the tool-guidance order band renders TypeScript declarations plus fixed usage instructions for the scope's visible capabilities. It shares lookup and execution visibility, excludes `run_code`, and sorts tools lexicographically for byte-stable output.
+**SDK prompt section.** In `'code'` and `'both'`, the lazy `tools:sdk` section in the tool-guidance order band renders the loaded runtime's language declarations plus fixed usage instructions for the scope's visible capabilities (TypeScript by default; the [language-dispatch note](2026-07-31-code-mode-language-dispatch.md) added Python and the `ctx.codeRuntime.language` renderer table). It shares lookup and execution visibility, excludes `run_code`, and sorts tools lexicographically for byte-stable output.
 
 **Assembly ownership.** `run_code` and `tools:sdk` enter the trusted `system-prompt/assemble` waterfall as normal assembly inputs. A scoped `tools:sdk` section may shadow the global default before dispatch, and a listener may remove or replace either contribution. The waterfall's returned assembly is final, so whoever changes these inputs owns preserving a viable Code Mode protocol when the deployment expects Code Mode to remain usable; no restoration pass overrides deliberate composition.
 
@@ -48,7 +48,7 @@ Under `'code'` and `'both'` the registry owns `run_code` as a reserved presentat
 
 **Sub-call contexts are deferred through the parent.** Injecting inside `run_code` would break parent call/result adjacency, so `ToolRunContext.deferContext()` collects every sub-result `additionalContexts` entry in dispatch order. The registry carries that array even when the program later throws, and the loop appends each entry only after the outer result and every sibling result in the step. An outer post-execute block discards tool-deferred entries and exposes only contexts explicitly attached by the blocking decision.
 
-**Concurrency is serialized.** Each run owns a dispatch queue, so even `Promise.all` executes tool calls in submission order. Settlement abandons queued calls that have not started. Parallelism requires per-tool concurrency-safety metadata.
+**Concurrency is bounded, not serialized.** Each run owns a dispatch queue that starts calls strictly in submission order and classifies each one through `registry.executionMode`, the same fail-closed `isConcurrencySafe` contract the native loop uses. Consecutive parallel-classified calls overlap up to `maxParallelSubCalls` (default 10; `1` restores serial dispatch); an exclusive call drains the pool and runs alone. Settlement abandons queued calls that have not started. This note shipped the serialized placeholder; the [live-parallel Agent Note](2026-07-26-code-mode-live-parallel-dispatch.md) owns the scheduler that replaced it.
 
 **Presentation.** `run_code`'s render intent is decided here per the [render-intent Agent Note](../architecture/2026-07-02-tool-render-intent-union.md): `presentCall` creates a `generic` card with `kind: 'execute'`, the program text as its title, and the same program text as `rawInput`; `run_code` intentionally declares no `presentResult`, so the TUI and host/client runtime (Web) complete that card through their generic raw-content fallback using the final durable `tool/result.content`, including captured logs plus the returned value, failure, or post-policy spill preview. This is not a `terminal` card: that card's semantics are "a shell command in a working directory", which a program is not. See the [result-card completeness note](../../archived/bug-fix/2026-07-20-code-mode-result-card-completeness.md).
 
@@ -64,7 +64,7 @@ Each sub-dispatch appends a log-only `tool/code-dispatch-start` event at pool en
 - `CodeBindingNamespace = { global: string; functions: Record<string, (args: unknown) => Promise<CodeJsonValue>>; errorClass?: { name: string; memberNameProperty: string } }` — the runtime exposes each namespace as a global object of async functions inside the program; the optional descriptor asks the runtime to inject a real program-visible rejection class without teaching the seam consumer-specific names. `CodeJsonValue` is this dependency-light seam's structural lossless-JSON type, so binding arguments and resolutions cross the implementation's serialization boundary whole.
 - `CodeRunResult = { value?: CodeJsonValue; logs: string[]; error?: CodeRunFailure }` — program execution outcomes resolve as the `error` field. `run()` may reject only for caller/seam misuse (for example a duplicate binding namespace); consumers still contain a non-conforming backend rejection at their own error boundary.
 - `CodeRunFailure = { kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit'; message: string }` — orthogonal outcomes reported independently per [defensive patterns](../../../../docs/defensive-patterns.md); a timed-out run is not an exception, an abort is not a timeout, a lossy completion is not an overflow, and a substrate exit is none of them.
-- Two readonly backend descriptors, informational not gating: `language` (what the program must be written in — `'typescript'` for the shipped backend; a Python backend would say so, and pair with its own SDK generator on the presentation side) and `isolation` (`'worker-thread'` for the shipped backend; `'process'`, `'container'`, … for future ones). `dsh-tools` requires `language === 'typescript'` in the MVP — its codegen emits TS — and fails the assembly loudly otherwise, the same misconfiguration idiom as `toolOrder` violations (as when `mode` is non-native with no `ctx.codeRuntime` loaded at all).
+- Two readonly backend descriptors, informational not gating: `language` (what the program must be written in — `'typescript'` for the first backend; a Python backend says `'python'` and pairs with its own SDK generator on the presentation side) and `isolation` (`'worker-thread'` for the shipped backend; `'process'`, `'container'`, … for future ones). `dsh-tools` accepts any `language` with a registered SDK renderer and `run_code` flavor (TypeScript and Python ship; see the [language-dispatch note](2026-07-31-code-mode-language-dispatch.md)) and fails the assembly loudly otherwise, the same misconfiguration idiom as `toolOrder` violations (as when `mode` is non-native with no `ctx.codeRuntime` loaded at all).
 
 Requests contain every runtime input; implementations own validated timeout and cap defaults. The registry looks up the optional runtime only when Code Mode is assembled, so native mode does not depend on one. Missing or language-incompatible runtimes fail loudly. Alternate substrates or languages can replace the implementation behind the same seam, paired with the appropriate SDK generator.
 
@@ -85,11 +85,11 @@ The worker runtime provides containment, not a security boundary: model code can
 
 ### What the model sees
 
-The SDK instructs the model to write an async erasable-TypeScript body, call tools through `await tools.name(args)`, catch rejected tool calls when needed, and return or log only the output that should re-enter context. Calls remain sequential even under `Promise.all`. The declaration prefix can be as large as native schemas, especially in `'both'`, but remains stable for provider caching.
+The SDK instructs the model to write an async body in the loaded runtime's language (an erasable-TypeScript body by default; a Python `async` body under a Python runtime — see the [language-dispatch note](2026-07-31-code-mode-language-dispatch.md)), call tools through `await tools.name(args)`, catch rejected tool calls when needed, and return or log only the output that should re-enter context. Both flavors state the same contract in their own primitive: independent read-only calls MAY overlap under `Promise.all` (TypeScript) or `asyncio.gather` (Python), mutating calls run alone in submission order, and dependent work sequences with `await`. The declaration prefix can be as large as native schemas, especially in `'both'`, but remains stable for provider caching.
 
 ## Consequences
 
-Deployments switching to `'code'` must update any native-only `toolOrder`. Assembly listeners own the integrity of any rewritten protocol surface. Sub-dispatch remains serialized, while per-call contexts retain their source, envelope, and metadata through the outer result.
+Deployments switching to `'code'` must update any native-only `toolOrder`. Assembly listeners own the integrity of any rewritten protocol surface. Sub-dispatch starts in submission order under a bounded overlap pool, while per-call contexts retain their source, envelope, and metadata through the outer result.
 
 ## Testing
 
@@ -106,7 +106,7 @@ Deployments switching to `'code'` must update any native-only `toolOrder`. Assem
 
 **Result elision / summarization over native tool-calling.** Addresses only the context-bloat half of the problem: trimming old `tool-result`s is cheap to add as a logged surface replacement under reconstructable requests, but still pays one model round-trip per call and cannot express loops, branches, or joins. Complementary, not competing; it can layer under Code Mode for residual native calls.
 
-**Parallel native dispatch in the loop.** The other answer to round-trip cost; still valid future work (the open TODO), still blocked on concurrency-safety metadata, and still no composition — it parallelizes calls the model already decided on in one step. Code Mode's serialized-queue decision keeps the two compatible: when the metadata lands, both native parallel dispatch and per-tool binding parallelism unlock together.
+**Parallel native dispatch in the loop.** The other answer to round-trip cost at decision time; it was blocked on concurrency-safety metadata and offers no composition either way — it parallelizes calls the model already decided on in one step. Code Mode's queue decision kept the two compatible, and that is how it played out: the metadata landed as `isConcurrencySafe` (the [parallel tool-call note](2026-07-10-parallel-tool-call-execution.md)), and native rolling-pool dispatch and per-tool binding parallelism unlocked on the same classifier.
 
 **Always-exclusive (Cloudflare-faithful, no mode).** Rejected for this SDK's primary consumer: a coding agent's bread-and-butter single calls (`bash`, `read`, `edit`) are already ideal as native calls, and forcing every edit through a program taxes the common case. The mode config keeps the faithful form (`'code'`) one line away without imposing it.
 
@@ -128,6 +128,6 @@ Deployments switching to `'code'` must update any native-only `toolOrder`. Assem
 
 **Large lossless JSON values can exhaust memory.** Tool bindings snapshot lossless JSON before dispatch and return canonical JSON resolutions whole. The runtime validates both sides of the worker port and applies no per-binding byte cap; structured-clone cost and process or worker memory are the practical bounds. The combined outer-output ledger for logs, the completion value, and a failure diagnostic is the only byte-capped boundary.
 
-**Serialized-only sub-dispatch.** `Promise.all` gains no wall-clock parallelism yet, only fewer round-trips; models may over-expect. The instructions state it; lifting it is tied to the same concurrency-safety metadata the native parallel-dispatch TODO needs.
+**Sub-dispatch overlap is bounded by tool safety claims, not by the caller.** A program's `Promise.all` or `asyncio.gather` buys wall-clock parallelism only across calls the tool itself classifies concurrency-safe; a run of exclusive calls still costs its round-trips in sequence, and models may over-expect. Both flavors' SDK instructions state the real contract. This note shipped the serialized placeholder that made the risk absolute; the [live-parallel Agent Note](2026-07-26-code-mode-live-parallel-dispatch.md) owns the scheduler and its overlap cap.
 
 **Budget metering reads the event loop, not a flag.** Busy-time polling (`eventLoopUtilization()`) is coarser than an exact CPU meter — a budget expires up to one poll interval late — and its correctness claim ("a pending dispatch cannot pause it") is load-bearing against a hostile program. Both sides are unit-tested (hot loop with a pending decoy dispatch dies at `computeMs`; idle-on-slow-binding survives to `maxWallMs`), and the poll interval is an internal constant, not config — nothing a deployment could mis-tune into a bypass. `maxWallMs` is config, and it reaches `setTimeout`, which clamps a delay above `MAX_TIMER_DELAY_MS` (2^31-1 ms) to 1 ms; a positivity check alone therefore accepts a 25-day ceiling that expires on the first tick and times out every run. The worker runtime range-checks the field at load for that reason. `computeMs` needs no upper bound because it is compared against measured utilization instead of being handed to a timer.

+ 8 - 8
.agents/notes/implemented/feature/2026-06-15-code-mode.zh.md

@@ -6,7 +6,7 @@ Status: implemented
 
 ## 问题
 
-在注册表的原生呈现方式下,agent loop(智能体循环)将每个可见能力以 JSON Schema 函数定义的形式通告给模型。`ToolRegistry` 将其 schema 贡献给系统提示词组装,组装结果中的 `tools` 落到协议格式(wire format)上(也记录在请求头日志中),模型每步调用一个 `tool-call` 块,循环通过 `ctx.tools.execute()` **逐个**分发每次调用(并行工具执行是 `dsh-tools` 和 [docs/architecture.md](../../../../docs/architecture.md) 中明确标注的 open TODO),且**每一个**中间 `tool-result` 都会在下一次请求时重新进入模型上下文。
+在注册表的原生呈现方式下,agent loop(智能体循环)将每个可见能力以 JSON Schema 函数定义的形式通告给模型。`ToolRegistry` 将其 schema 贡献给系统提示词组装,组装结果中的 `tools` 落到协议格式(wire format)上(也记录在请求头日志中),模型每步调用一个 `tool-call` 块,而在本 note 写作时,循环通过 `ctx.tools.execute()` **逐个**分发每次调用(并行工具执行当时还是 open TODO;此后有界的并行分发已经交付——见[并行工具调用 note](2026-07-10-parallel-tool-call-execution.md),以及 [docs/architecture.md](../../../../docs/architecture.md) 中的 rolling pool)——且**每一个**中间 `tool-result` 都会在下一次请求时重新进入模型上下文。
 
 对于多步工具操作,这种方式 token 开销大且串行。模型无法组合工具——遍历结果集、根据中间值分支、扇出、后处理——每次调用都需要一次完整的模型往返,而每次往返都会把完整的中间结果拖回上下文,不管模型是否需要。
 
@@ -32,7 +32,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
 
 **与 `toolOrder` 的交互,预先说明:** 如果配置的 `systemPrompt.toolOrder` 引用了原生能力名称,在 `mode: 'code'` 下会拒绝所有组装,因为那些名称不在该模式的协议校验范围内。这是正确行为而非 bug:使用 Code Mode 的部署需要更新其 order 配置或移除它。
 
-**SDK 提示词段。** 在 `'code'` 和 `'both'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染 TypeScript 声明加固定的使用说明。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。
+**SDK 提示词段。** 在 `'code'` 和 `'both'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染所加载运行时语言的声明加固定的使用说明(默认 TypeScript;[语言分发 note](2026-07-31-code-mode-language-dispatch.md) 加入了 Python 与按 `ctx.codeRuntime.language` 选择的渲染器表)。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。
 
 **组装所有权。** `run_code` 和 `tools:sdk` 作为正常的组装输入进入受信任的 `system-prompt/assemble` waterfall。一个 scoped 的 `tools:sdk` 段可以在分发前遮蔽全局默认值,监听器也可以移除或替换任一贡献。waterfall 返回的组装结果是最终的,因此修改这些输入的人有责任在部署期望 Code Mode 可用时保持协议面的完整性;没有恢复 pass 会覆盖有意的组合。
 
@@ -48,7 +48,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
 
 **子调用上下文通过父调用延后。** 在 `run_code` 内部注入会破坏父调用/结果的相邻性,因此 `ToolRunContext.deferContext()` 按分发顺序收集每个子结果的 `additionalContexts` 条目。即使程序后来抛出异常,注册表仍携带该数组;循环只在外层结果与步骤中所有兄弟结果之后追加每个条目。外层 post-execute 阻止会丢弃工具延后的条目,只暴露阻止 decision 显式附加的上下文。
 
-**并发被序列化。** 每次 run 拥有一个分发队列,因此即使 `Promise.all` 也按提交顺序执行工具调用。结算时放弃尚未开始的排队调用。并行化需要每个工具的并发安全元数据。
+**并发是有界的,而非被序列化。** 每次 run 拥有一个分发队列,严格按提交顺序启动调用,并通过 `registry.executionMode` 对每个调用分类——与原生循环所用的 fail-closed `isConcurrencySafe` 契约相同。连续的 parallel 类调用最多重叠 `maxParallelSubCalls` 个(默认 10;设为 `1` 恢复串行分发);exclusive 类调用会排空池并单独运行。结算时放弃尚未开始的排队调用。本 note 交付的是被序列化的占位实现;取代它的调度器由[实时并行 Agent Note](2026-07-26-code-mode-live-parallel-dispatch.md) 负责。
 
 **呈现。** `run_code` 的 render intent 按[呈现意图 Agent Note](../architecture/2026-07-02-tool-render-intent-union.md)在此决定:`presentCall` 创建一个 `generic` 卡片,`kind: 'execute'`,以程序文本作为标题,并将同一程序文本作为 `rawInput`;`run_code` 有意不声明 `presentResult`,因此 TUI 和宿主/客户端运行时(Web)会通过通用原始内容回退机制,使用最终持久化的 `tool/result.content` 补全该卡片,其中包括捕获的日志,以及返回值、失败信息或 post-policy 输出落盘预览。这不是 `terminal` 卡片:该卡片的语义是「工作目录中的 shell 命令」,程序不是。参见[结果卡片完整性说明](../../archived/bug-fix/2026-07-20-code-mode-result-card-completeness.md)。
 
@@ -64,7 +64,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
 - `CodeBindingNamespace = { global: string; functions: Record<string, (args: unknown) => Promise<CodeJsonValue>>; errorClass?: { name: string; memberNameProperty: string } }`——运行时将每个命名空间作为程序内部的全局异步函数对象暴露;可选描述符要求运行时注入真正的、程序可见的 reject 类,而无需让 seam 获知消费方专用名称。`CodeJsonValue` 是这个低依赖 seam 的结构化无损 JSON 类型,因此绑定参数与返回值可以完整跨越实现的序列化边界。
 - `CodeRunResult = { value?: CodeJsonValue; logs: string[]; error?: CodeRunFailure }`——程序执行失败时,执行 promise 仍会 fulfill,并通过 `error` 字段返回失败结果。只有调用方/seam 误用(例如重复的绑定命名空间)时,`run()` 才会 reject;消费方仍在自己的错误边界处理不合规后端的拒绝。
 - `CodeRunFailure = { kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit'; message: string }`——按[防御性模式](../../../../docs/defensive-patterns.md)独立报告的正交结果;超时的 run 不是异常,abort 不是超时,有损完成值不是溢出,基底退出也与上述情况相互独立。
-- 两个只读的后端描述符,仅供信息参考而非门禁判定:`language`(程序必须使用的语言——交付的后端为 `'typescript'`;Python 后端会声明自己,并在呈现侧配对自己的 SDK 生成器)和 `isolation`(交付的后端为 `'worker-thread'`;未来可为 `'process'`、`'container'` 等)。`dsh-tools` 在 MVP 中要求 `language === 'typescript'`——其代码生成输出 TS——否则组装会大声失败,与 `toolOrder` 违规时的配置错误惯用法相同(如 `mode` 为非 native 但根本没有加载 `ctx.codeRuntime`)。
+- 两个只读的后端描述符,仅供信息参考而非门禁判定:`language`(程序必须使用的语言——首个后端为 `'typescript'`;Python 后端声明 `'python'`,并在呈现侧配对自己的 SDK 生成器)和 `isolation`(交付的后端为 `'worker-thread'`;未来可为 `'process'`、`'container'` 等)。`dsh-tools` 接受任何注册了 SDK 渲染器与 `run_code` flavor 的 `language`(TypeScript 与 Python 已交付;见[语言分发 note](2026-07-31-code-mode-language-dispatch.md)),否则组装会大声失败,与 `toolOrder` 违规时的配置错误惯用法相同(如 `mode` 为非 native 但根本没有加载 `ctx.codeRuntime`)。
 
 请求包含所有运行时输入;实现方拥有经校验的超时和上限默认值。注册表仅在组装 Code Mode 时查找可选的运行时,因此 native 模式不依赖它。缺失或语言不兼容的运行时会大声失败。替代基底或语言可以在同一 seam 背后替换实现,配对相应的 SDK 生成器。
 
@@ -85,11 +85,11 @@ worker 运行时只能约束程序的运行,而不构成安全边界:模型
 
 ### 模型看到的内容
 
-SDK 指示模型编写一个异步的可擦除 TypeScript 函数体,通过 `await tools.name(args)` 调用工具,在需要时捕获被拒绝的工具调用,并仅 return 或 log 应重新进入上下文的输出。即使在 `Promise.all` 下调用仍保持顺序。声明前缀可能与原生 schema 一样大,尤其在 `'both'` 下,但对提供方缓存保持稳定。
+SDK 指示模型编写一个所加载运行时语言的异步函数体(默认可擦除 TypeScript;Python 运行时下为 Python `async` 函数体——见[语言分发 note](2026-07-31-code-mode-language-dispatch.md)),通过 `await tools.name(args)` 调用工具,在需要时捕获被拒绝的工具调用,并仅 return 或 log 应重新进入上下文的输出。两种 flavor 用各自的原语陈述同一契约:相互独立的只读调用可以在 `Promise.all`(TypeScript)或 `asyncio.gather`(Python)下重叠,有副作用的调用按提交顺序单独运行,有依赖的工作用 `await` 排序。声明前缀可能与原生 schema 一样大,尤其在 `'both'` 下,但对提供方缓存保持稳定。
 
 ## 后果
 
-切换到 `'code'` 的部署必须更新任何仅限 native 的 `toolOrder`。组装监听器有责任维护任何被重写的协议面的完整性。子分发保持序列化,而每次调用的上下文会通过外层结果保留其 source、信封与元数据。
+切换到 `'code'` 的部署必须更新任何仅限 native 的 `toolOrder`。组装监听器有责任维护任何被重写的协议面的完整性。子分发在有界的重叠池下按提交顺序启动,而每次调用的上下文会通过外层结果保留其 source、信封与元数据。
 
 ## 测试
 
@@ -106,7 +106,7 @@ SDK 指示模型编写一个异步的可擦除 TypeScript 函数体,通过 `aw
 
 **在原生工具调用上做结果省略/摘要。** 仅解决问题中上下文膨胀这一半:裁剪旧 `tool-result` 作为可重建请求下的日志化表面替换成本低,但仍需每次调用一次模型往返,且无法表达循环、分支或汇合。互补而非竞争;它可以在 Code Mode 下为残余的原生调用分层。
 
-**循环中的并行原生分发。** 往返成本的另一个答案;仍是有效的未来工作(open TODO),仍被并发安全元数据阻塞,且仍无组合能力——它并行化的是模型在一步中已经决定的调用。Code Mode 的序列化队列决策保持两者兼容:当元数据就绪时,原生并行分发和每工具绑定并行化一起解锁。
+**循环中的并行原生分发。** 决策当时对往返成本的另一个答案;它被并发安全元数据阻塞,且无论如何都不提供组合能力——它并行化的是模型在一步中已经决定的调用。Code Mode 的队列决策保持了两者兼容,后续也正是这样落地的:元数据以 `isConcurrencySafe` 的形式就绪(见[并行工具调用 note](2026-07-10-parallel-tool-call-execution.md)),原生 rolling-pool 分发与每工具绑定并行化基于同一个分类器一起解锁。
 
 **始终排他(忠于 Cloudflare,无模式)。** 否决,因为本 SDK 的主要消费方是编码 agent:其日常的单次调用(`bash`、`read`、`edit`)作为原生调用已经是最优的,强制每次编辑都通过程序会给常见场景增加负担。mode 配置让忠实形式(`'code'`)只需一行配置即可启用,而不强加于人。
 
@@ -128,6 +128,6 @@ SDK 指示模型编写一个异步的可擦除 TypeScript 函数体,通过 `aw
 
 **大型无损 JSON 值可能耗尽内存。** 工具绑定会在分发前对无损 JSON 创建快照,并完整返回规范 JSON 返回值。运行时会校验 worker 端口两侧,但不对单次绑定设置字节数上限;结构化克隆成本以及进程或 worker 内存构成实际边界。只有包含日志、完成值和失败诊断的组合外层输出账本受字节数上限约束。
 
-**仅序列化的子分发。** `Promise.all` 尚未获得挂钟并行性,仅减少往返次数;模型可能过度期望。说明中已声明;解除此限制与原生并行分发 TODO 所需的并发安全元数据绑定。
+**子分发的重叠由工具自身的安全声明限定,而非由调用方决定。** 程序里的 `Promise.all` 或 `asyncio.gather` 只在工具自己分类为并发安全的调用之间换来挂钟并行性;一串 exclusive 调用仍要按顺序付出各自的往返开销,模型可能过度期望。两种 flavor 的 SDK 说明都陈述了真实契约。本 note 交付的是使该风险绝对化的序列化占位实现;调度器及其重叠上限由[实时并行 Agent Note](2026-07-26-code-mode-live-parallel-dispatch.md) 负责。
 
 **预算计量读取事件循环,而非 flag。** 忙碌时间轮询(`eventLoopUtilization()`)比精确 CPU 计量更粗糙——预算到期最多延迟一个轮询间隔——且其正确性声明(「pending 的分发不能暂停它」)是抵御恶意程序的关键。两种情况均有单元测试(带 pending 诱饵分发的热循环会在耗尽 `computeMs` 预算时终止;等待慢速绑定的空闲程序则会持续运行至 `maxWallMs`),轮询间隔是内部常量而非配置——部署无法将其误调为绕过手段。`maxWallMs` 是配置项,且会传入 `setTimeout`,后者会把超过 `MAX_TIMER_DELAY_MS`(2^31-1 ms)的延迟夹到 1 ms;因此仅有正数校验会放行一个 25 天的上限,它在第一个 tick 就到期,使每次运行都超时。worker 运行时正因如此在加载时对该字段做范围校验。`computeMs` 不需要上界,因为它对照的是实测占用率,而不是交给定时器。

+ 2 - 2
.agents/notes/implemented/feature/2026-07-29-web-message-icon-actions-and-clock.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-29-web-message-icon-actions-and-clock.md
-2026-07-29-web-message-icon-actions-and-clock.md: f43f7f9c9687e4494993d7e225d11cf6446a9954
-2026-07-29-web-message-icon-actions-and-clock.zh.md: a6261c65c1e9d77cea2de5624b2c9fde1278c612
+2026-07-29-web-message-icon-actions-and-clock.md: feced6aeb11d176d6c774242a4d1dae14f6730f8
+2026-07-29-web-message-icon-actions-and-clock.zh.md: 5e33182421b423f45c84dbe1a979505f4c31b819

+ 2 - 0
.agents/notes/implemented/feature/2026-07-29-web-message-icon-actions-and-clock.md

@@ -12,6 +12,8 @@ The web chat user bubble already had copy / branch / edit IconActions but no clo
 
 **User bubbles prepend a date-aware local clock to the existing IconActions row; the last content-text assistant of each turn appends a copy / branch / clock row with `margin-top: 16px`; both seats stay visible whenever mounted and re-format at the next local midnight.**
 
+The assistant seat is narrowed by the [completed-turn decision](../bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.md): only a turn with a `turn/end` grants it, so a turn still producing steps hands the row to nothing. The user seat's branch control is removed outright by the [user-bubble branch removal](../simplification/2026-08-06-user-bubbles-drop-the-branch-action.md); a user row's IconActions are clock and copy.
+
 Both seats format `node.time` through `formatMessageClock`: same calendar day → `HH:mm`, earlier this year → `M月D日 HH:mm`, other years → `YYYY年M月D日 HH:mm`. `useCalendarDay` is a component-local day tick (timeout to the next local midnight) so memoized rows re-render when the calendar day changes without a new framework hook. `MessageItem` places the label before copy (figma `388:20051`). `ChatView` derives turn-tail seqs via `assistantActionsSeqs` and withholds `time` for mid-turn content; `AssistantMarkdown` places the row after branch (figma `43:32997`) only when `streaming` is false, the event time is known, and the node has non-empty text content. Think-only nodes, mid-turn narration, and the streaming tail omit the row. Copy writes joined text blocks. Both message rows pass their event's `seq` to the same fork callback; [Web session fork actions](2026-07-27-web-session-fork-actions.md) define the real mutation contract. Clipboard write and the clock helpers live in `message-chrome.ts`. The assembled surface is pinned by `apps/web/tests/message-actions.e2e.ts` (cold-seeded history + aria golden); aria normalization collapses every clock shape to `{{clock}}`.
 
 ## Alternatives considered

+ 2 - 0
.agents/notes/implemented/feature/2026-07-29-web-message-icon-actions-and-clock.zh.md

@@ -12,6 +12,8 @@ Web 聊天的用户气泡已有复制、分支、编辑 IconActions,但没有
 
 **用户气泡在既有 IconActions 行的开头添加感知日期的本地时钟;每个轮次中最后一条带 text 内容的 assistant 在正文下追加带 `margin-top: 16px` 的复制、分支、时钟;两边只要挂载就保持可见,并在下一个本地午夜重新格式化。**
 
+assistant 一侧的座位由[已完成轮次决策](../bug-fix/2026-08-05-turn-tail-actions-require-a-completed-turn.md)收紧:只有存在 `turn/end` 的轮次才授予该行,仍在产出步骤的轮次不把该行交给任何节点。user 一侧的分支控件被 [user 气泡分支移除决策](../simplification/2026-08-06-user-bubbles-drop-the-branch-action.md)直接移除;user 行的 IconActions 只有时钟与复制。
+
 两边都通过 `formatMessageClock` 格式化 `node.time`:同一日历日 → `HH:mm`,同年更早 → `M月D日 HH:mm`,跨年 → `YYYY年M月D日 HH:mm`。`useCalendarDay` 是组件本地的日刻度(定时到下一个本地午夜),因此 memo 行在日历日变化时会重渲染,且不新增框架钩子。`MessageItem` 把标签放在复制之前(figma `388:20051`)。`ChatView` 通过 `assistantActionsSeqs` 推导轮次尾部的 seq,并不为轮次中间的内容传入 `time`;`AssistantMarkdown` 把该行放在分支之后(figma `43:32997`),且仅在 `streaming` 为 false、已知事件时间、且节点含非空 text 内容时渲染。纯 Think 节点、轮次中间的叙述与流式尾部省略该行。复制写入拼接后的 text 块。两种消息行都把自己的事件 `seq` 交给同一个 fork 回调;真实 mutation 契约由 [Web session fork 操作](2026-07-27-web-session-fork-actions.md)定义。剪贴板写入与时钟辅助函数放在 `message-chrome.ts`。组装后的界面由 `apps/web/tests/message-actions.e2e.ts`(冷 seed 历史 + aria golden)钉住;aria 归一化把每种时钟形态折叠为 `{{clock}}`。
 
 ## 曾考虑的方案

+ 6 - 0
.agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.md
+2026-07-31-code-mode-language-dispatch.md: 96001252d6494d058a8df9974fb5a0d59e7d7112
+2026-07-31-code-mode-language-dispatch.zh.md: aa7eb2a6b4b9117f1d707b37afcdbe12b814bad2

Разница между файлами не показана из-за своего большого размера
+ 19 - 0
.agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.md


Разница между файлами не показана из-за своего большого размера
+ 39 - 0
.agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.zh.md


+ 6 - 0
.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md
+2026-08-06-user-bubbles-drop-the-branch-action.md: 817b5e72b7e18b03ddb3a160e6f7a86b04f02764
+2026-08-06-user-bubbles-drop-the-branch-action.zh.md: dab3890818d872d7bbb3ac9bcab014ce9b829a61

+ 27 - 0
.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md

@@ -0,0 +1,27 @@
+# Agent Note: User and steering bubbles drop the branch action
+
+Status: implemented
+
+English | [中文](2026-08-06-user-bubbles-drop-the-branch-action.zh.md)
+
+## Problem
+
+Every user and consumed-steering bubble rendered the branch control under the completed-turn-tail gate of the [completed-turn-tail decision](../bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md). On those bubbles the gate is effectively permanent: a turn-opening user message is followed by its own turn's nodes, and a consumed steering message is mid-turn by construction, so the control could enable only when the turn ended with no node after the message at all — a cancel before the first model event. Readers therefore saw a control that never enables, with a tooltip promising a state the button cannot reach. The affordance also misled when read at all: a fork at a message seq cuts at the containing `turn/end`, so "branch at my message" includes the answer below it — the opposite of the branch-to-re-ask reading a control on one's own bubble suggests.
+
+## Decision
+
+User and steering bubbles render no branch action. `MessageItem` loses its fork props, `PendingSteeringBubble` loses its `showBranch` special case, and `messageBranchSeqs` narrows to `assistantBranchSeqs`: only a completed turn's transcript tail that is the turn's own content-text assistant may fork. The branch affordance lives solely under the settled answer.
+
+A turn containing a steer keeps its fork point unchanged: fork is a log-prefix cut at `turn/end`, and the steer is model-visible history the child must inherit, so the settled answer of a steered turn forks like any other. The assistant-side gate and its visible-but-unavailable presentation are also unchanged — under an answer, unavailable is a transient, reachable state (a trailing tool or error row currently owns the tail), which is exactly what the tooltip is for.
+
+## Alternatives considered
+
+**Hide the control on message bubbles only while ineligible.** Rejected: it preserves the near-unreachable enabled case at the cost of an icon that appears on one's own bubble only when a turn died before producing anything, an inconsistency not worth the case it serves.
+
+**Keep the visible-but-unavailable control (status quo).** Rejected: the [completed-turn-tail decision](../bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md) chose visibility so the tooltip could explain a boundary the reader can reach; on user and steering bubbles the boundary is unreachable in practice, so the explanation props up a control that should not exist there.
+
+**Branch-before-the-message semantics on user bubbles.** Out of scope: re-asking from one's own prompt needs a cut before the message plus composer prefill, a different Host operation. Removing the current control keeps that seat free for such a feature instead of squatting on it with opposite semantics.
+
+## Consequences
+
+The only fork handles are the enabled branch controls under settled answers. A turn cancelled before any node followed its message loses its only handle and has no fork point, matching turns whose tail is a content-free interrupted node. Web aria goldens across `apps/web` drop the user-bubble disabled-branch row and its hidden explanation text. Package tests pin that user and steering bubbles render no branch control and that a steering-tail turn leaves the narration's control unavailable.

+ 27 - 0
.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.zh.md

@@ -0,0 +1,27 @@
+# Agent Note:user 与 steering 气泡移除分支操作
+
+Status: implemented
+
+[English](2026-08-06-user-bubbles-drop-the-branch-action.md) | 中文
+
+## 问题
+
+每个 user 气泡和已消费的 steering(中途引导)气泡都渲染分支控件,受[已完成轮次尾部决策](../bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md)的门禁约束。在这些气泡上,该门禁实际上是永久性的:开轮的 user 消息后面必然跟着本轮自己的节点,已消费的 steering 消息按构造就处在轮次中间,因此只有当轮次结束时该消息之后一个节点都没有——即在第一个模型事件之前就取消——控件才可能启用。读者因此看到一个永远不会启用的控件,tooltip 许诺的是这个按钮到达不了的状态。这个操作入口本身也有误导:在消息 seq 处 fork 会切在所在轮次的 `turn/end`,"在我的消息处分支"实际会把下方的回答一并带走,与在自己气泡上看到分支时"分叉重问"的直觉预期恰好相反。
+
+## 决策
+
+user 与 steering 气泡不再渲染分支操作。`MessageItem` 移除其 fork props,`PendingSteeringBubble` 移除其 `showBranch` 特例,`messageBranchSeqs` 收窄为 `assistantBranchSeqs`:只有已完成轮次的 transcript 尾部、且该尾部是本轮自己的带 text 内容 assistant 节点才可 fork。分支入口只存在于已定稿的回答之下。
+
+含有 steer 的轮次的 fork 点保持不变:fork 是切在 `turn/end` 上的日志前缀,steer 是子会话必须继承的模型可见历史,因此被引导过的轮次的已定稿回答与其他轮次一样可以 fork。assistant 侧的门禁及其可见但不可用的呈现也保持不变——在回答之下,不可用是一个短暂且可到达的状态(当前尾部被后续工具行或错误行占据),这正是 tooltip 的用武之地。
+
+## 考虑过的替代方案
+
+**仅在不可用时隐藏消息气泡上的控件。** 否决:它保住了那个几乎不可达的启用场景,代价是图标只在轮次尚未产出任何东西就中止时才出现在自己的气泡上,这种不一致不值得为它服务的场景付出。
+
+**保留可见但不可用的控件(现状)。** 否决:[已完成轮次尾部决策](../bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md)选择可见,是为了让 tooltip 解释一个读者可以到达的边界;在 user 与 steering 气泡上这个边界实际不可达,解释文本是在为一个不该存在于此的控件打补丁。
+
+**在 user 气泡上采用切在消息之前的分支语义。** 不在本次范围内:从自己的提示词重问需要切在消息之前并预填输入框,是另一个 Host 操作。移除当前控件恰好为这样的功能留出位置,而不是让语义相反的控件占着它。
+
+## 后果
+
+唯一的 fork 入口是已定稿回答下方启用的分支控件。在任何节点跟上其消息之前就被取消的轮次失去了它唯一的入口,从此没有 fork 点,与尾部是无内容 interrupted 节点的轮次一致。`apps/web` 的 aria golden 全部移除 user 气泡的禁用分支行及其隐藏说明文本。包测试钉住:user 与 steering 气泡不渲染分支控件,steering 作为尾部的轮次让叙述节点的控件保持不可用。

+ 168 - 0
apps/web/tests/goal-multi-turn-actions.e2e.ts

@@ -0,0 +1,168 @@
+// Keyless replay of a real two-round Goal run. Each autonomous round ends as
+// its own turn, so the first answer must keep its IconActions when Goal opens
+// round two and the final answer must own a second, distinct action row.
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import type { Browser, Page } from 'playwright'
+import { chromium } from 'playwright'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
+import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
+import type {} from '@deepseek-ai/dsh-goal'
+import {
+  assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
+  launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
+
+const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/goal-multi-turn-actions', import.meta.url))
+const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
+const OVERRIDE = join(SNAPSHOT_DIR, 'replay.override.json')
+const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md')
+const MODE = webSnapshotMode()
+
+const PROMPT = '做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的'
+const COMMAND = `/goal ${PROMPT}`
+
+const PACKAGE_FILES: Readonly<Record<string, string>> = {
+  'packages/client/ui-conversation/README.md': '# UI conversation\n',
+  'packages/client/ui-conversation/package.json': '{"name":"@deepseek-ai/dsh-client-ui-conversation"}\n',
+  'packages/client/ui-conversation/src/client.ts': 'export {}\n',
+  'packages/client/ui-conversation/tests/chat-view.spec.tsx': 'export {}\n',
+  'packages/context/session-reference/README.md': '# Session reference\n',
+  'packages/context/session-reference/package.json': '{"name":"@deepseek-ai/dsh-session-reference"}\n',
+  'packages/context/session-reference/src/index.ts': 'export {}\n',
+  'packages/context/session-reference/src/uri.ts': 'export {}\n',
+  'packages/context/session-reference/tests/session-reference.spec.ts': 'export {}\n',
+  'packages/llm/token-meter/README.md': '# Token meter\n',
+  'packages/llm/token-meter/package.json': '{"name":"@deepseek-ai/dsh-token-meter"}\n',
+  'packages/llm/token-meter/src/index.ts': 'export {}\n',
+  'packages/llm/token-meter/tests/token-meter.spec.ts': 'export {}\n',
+  'packages/skill/skill-local/README.md': '# Local skill provider\n',
+  'packages/skill/skill-local/package.json': '{"name":"@deepseek-ai/dsh-skill-local"}\n',
+  'packages/skill/skill-local/src/index.ts': 'export {}\n',
+  'packages/skill/skill-local/src/invariant.ts': 'export {}\n',
+  'packages/skill/skill-local/tests/skill-local.spec.ts': 'export {}\n',
+}
+
+/** Materialize a stable package inventory inside the isolated session workspace. */
+async function seedPackageInventory(workspaceRoot: string): Promise<void> {
+  for (const [relativePath, content] of Object.entries(PACKAGE_FILES)) {
+    const path = join(workspaceRoot, 'workspace', relativePath)
+    await mkdir(dirname(path), { recursive: true })
+    await writeFile(path, content)
+  }
+}
+
+/** Await exactly the requested number of durable turn ends, then flush the session. */
+function whenTurnsSettled(scaffold: WebScaffold, count: number, timeoutMs: number): Promise<SessionId> {
+  return new Promise<SessionId>((resolve, reject) => {
+    let completed = 0
+    const timer = setTimeout(() => {
+      off()
+      reject(new Error(`only ${completed}/${count} Goal turns ended within ${timeoutMs}ms`))
+    }, timeoutMs)
+    const off = scaffold.ctx.on('session/event', (session, event: SessionEvent) => {
+      if (event.type !== 'turn/end') return
+      completed += 1
+      if (completed !== count) return
+      clearTimeout(timer)
+      off()
+      scaffold.ctx.sessions.flush(session).then(() => { resolve(session.id) }, reject)
+    })
+  })
+}
+
+/** Goal-owned round numbers in durable user-message order. */
+function goalRounds(events: readonly SessionEvent[]): number[] {
+  return events.flatMap(event => event.type === 'user/message' && event.data.source.kind === 'goal'
+    ? [event.data.source.round]
+    : [])
+}
+
+/** Objective written by each durable Goal creation. */
+function createdObjectives(events: readonly SessionEvent[]): string[] {
+  return events.flatMap(event => event.type === 'goal/change' && event.data.operation === 'create'
+    ? [event.data.goal.objective]
+    : [])
+}
+
+describe('web e2e: Goal keeps one assistant action row per completed turn', () => {
+  let scaffold: WebScaffold | undefined
+  let browser: Browser | undefined
+  let page: Page
+  let tripwire: ReturnType<typeof watchConsole>
+  let sessionEvents: SessionEvent[]
+
+  afterEach(async () => {
+    const failures: unknown[] = []
+    await browser?.close().catch((error: unknown) => failures.push(error))
+    browser = undefined
+    const closing = scaffold
+    scaffold = undefined
+    await closing?.close().catch((error: unknown) => failures.push(error))
+    if (failures.length === 1) throw failures[0]
+    if (failures.length > 1) throw new AggregateError(failures, 'goal-multi-turn-actions teardown failed')
+  })
+
+  /** Boot the real Web composition and connect a fresh package fixture workspace. */
+  async function launch(): Promise<void> {
+    sessionEvents = []
+    scaffold = await launchWebScaffold(
+      MODE === 'record' ? {} : { replayFixture: FIXTURE, replayOverride: OVERRIDE },
+    )
+    await seedPackageInventory(scaffold.workspaceCwd)
+    scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
+    browser = await chromium.launch()
+    page = await newEnglishPage(browser)
+    tripwire = watchConsole(page)
+    await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
+    await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
+    await connectFreshWorkspace(page, scaffold.workspaceCwd)
+  }
+
+  /** Submit the Goal command after arming the two-turn barrier. */
+  async function runGoal(timeoutMs: number): Promise<SessionId> {
+    const input = page.locator('textarea').first()
+    await input.waitFor({ timeout: 10_000 })
+    const settled = whenTurnsSettled(scaffold!, 2, timeoutMs)
+    await input.fill(COMMAND)
+    await input.press('Enter')
+    return settled
+  }
+
+  it.skipIf(MODE !== 'record')('records the two-round Goal through the real model', async () => {
+    await launch()
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-goal-multi-turn-actions-record'))
+    const sessionId = await runGoal(360_000)
+    await recordFixture(scaffold!, sessionId, FIXTURE)
+  }, 380_000)
+
+  it.skipIf(MODE === 'record')('keeps actions on both completed Goal turn tails', async () => {
+    const fixtureEvents = parseSessionLog(await readFile(FIXTURE, 'utf8'))
+    expect(createdObjectives(fixtureEvents)).toEqual([PROMPT])
+    expect(goalRounds(fixtureEvents)).toEqual([1, 2])
+
+    await launch()
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-goal-multi-turn-actions'))
+    await runGoal(120_000)
+
+    expect(sessionEvents.flatMap(event => event.type === 'turn/end' ? [event.data.turn] : []))
+      .toEqual([1, 2])
+    expect(goalRounds(sessionEvents)).toEqual([1, 2])
+    const branchButtons = page.getByRole('button', { name: 'Branch into a new conversation' })
+    await expect.poll(() => branchButtons.count(), { timeout: 15_000 }).toBe(2)
+    expect(await branchButtons.evaluateAll(buttons => buttons.map(button => button.getAttribute('aria-disabled'))))
+      .toEqual([null, null])
+    await branchButtons.last().focus()
+    const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
+    await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
+    expect(tripwire.pageErrors).toEqual([])
+    expect(tripwire.warnings).toEqual([])
+  }, 140_000)
+
+  it.skipIf(MODE === 'record')('keeps a closed fixture inventory', async () => {
+    await assertFixtureInventory(SNAPSHOT_DIR, ['replay.override.json', 'session.jsonl', 'ui.expected.md'])
+  })
+})

+ 4 - 4
apps/web/tests/message-actions.e2e.ts

@@ -107,17 +107,17 @@ describe('web e2e: message IconActions and clocks on settled history', () => {
     await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
 
     // Focus-reveal the footers (hover:hover keeps them opacity-hidden until
-    // hover/focus-within). Every durable message footer keeps branch visible,
-    // but only the final assistant at a completed transcript tail enables it.
+    // hover/focus-within). Branch renders only under assistant answers — user
+    // bubbles carry none — and only a completed transcript tail enables it.
     const copyButtons = page.getByRole('button', { name: 'Copy' })
     await expect.poll(() => copyButtons.count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(4)
     await copyButtons.first().focus()
     const branchButtons = page.getByRole('button', { name: 'Branch into a new conversation' })
-    await expect.poll(() => branchButtons.count(), { timeout: 5_000 }).toBe(4)
+    await expect.poll(() => branchButtons.count(), { timeout: 5_000 }).toBe(2)
     await expect.poll(
       () => branchButtons.evaluateAll(buttons => buttons.map(button => button.getAttribute('aria-disabled'))),
       { timeout: 5_000 },
-    ).toEqual(['true', 'true', 'true', null])
+    ).toEqual(['true', null])
     await branchButtons.first().focus()
     await expect.poll(() => page.getByRole('tooltip').textContent(), { timeout: 5_000 })
       .toBe('Available only on the last message of a completed turn')

+ 67 - 24
apps/web/tests/models-settings.e2e.ts

@@ -1,15 +1,17 @@
 // Web e2e scenario: the Models settings page end to end through the real
-// wire — the add card offers the dormant pi-ai catalog, typing an API key
+// wire — the add card offers the dormant pi-ai catalog, a blank key saves a
+// reference-free profile for provider-native auth, and typing an API key later
 // stores it write-only under the derived reference (`MINIMAX_CN_API_KEY`)
-// while the settings document records only that reference; the saved row
-// appears after the route topology invalidation without presenting liveness
-// as provider status. The customized-settings fold writes the curated
+// while the settings document records only that reference. Each saved row
+// appears after route topology invalidation without presenting liveness as
+// provider status. The customized-settings fold writes the curated
 // reasoning field as a merge patch. Zero model calls: configuration is pure
 // settings/credentials/llm-domain traffic, so there is no fixture and a
 // stray stream would fail loud on the open seam. The provider under test is
 // minimax-cn so a developer's real ANTHROPIC/OPENAI environment keys can
-// never shadow the derived reference. Removing that row is guarded by the
-// localized provider-confirmation dialog before the unset reaches the wire.
+// never shadow the derived reference. The deletion dialog distinguishes a
+// reference-free profile from a page-managed key before the credential and
+// settings unsets reach the wire.
 import { readFile } from 'node:fs/promises'
 import { fileURLToPath } from 'node:url'
 import { join } from 'node:path'
@@ -25,6 +27,7 @@ import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
 const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/models-settings', import.meta.url))
 const EMPTY_EXPECTED = join(SNAPSHOT_DIR, 'empty.expected.md')
 const CONFIGURED_EXPECTED = join(SNAPSHOT_DIR, 'configured.expected.md')
+const NATIVE_DELETE_EXPECTED = join(SNAPSHOT_DIR, 'native-delete.expected.md')
 const DELETE_EXPECTED = join(SNAPSHOT_DIR, 'delete.expected.md')
 const MODE = webSnapshotMode()
 
@@ -70,34 +73,71 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
     expect(options).toContain('anthropic')
     expect(options).toContain('minimax-cn')
     await pick.selectOption('minimax-cn')
-    await dialog.getByLabel('API 密钥').waitFor({ timeout: 10_000 })
+    await dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).waitFor({ timeout: 10_000 })
     const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
     await compareOrRefreshGolden(EMPTY_EXPECTED, snapshot, MODE)
   }, 60_000)
 
-  it('stores the key under the derived reference and the route registers live', async () => {
+  it('saves a blank key as a reference-free provider-native profile', async () => {
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-models-native-auth'))
+    const dialog = page.getByRole('dialog', { name: '设置' })
+    await dialog.getByRole('button', { name: '保存', exact: true }).click()
+    const row = dialog.getByText('minimax-cn', { exact: true }).first()
+    await row.waitFor({ timeout: 10_000 })
+    await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 10_000 })
+    expect(await dialog.getByRole('img', { name: 'API 密钥已配置' }).count()).toBe(0)
+    expect(await dialog.getByRole('img', { name: 'API 密钥缺失' }).count()).toBe(0)
+    const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
+    expect(document).toContain('minimax-cn: {}')
+    expect(document).not.toContain('MINIMAX_CN_API_KEY')
+  }, 60_000)
+
+  it('describes reference-free deletion without claiming a credential exists', async () => {
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-models-native-delete'))
+    const settingsDialog = page.getByRole('dialog', { name: '设置' })
+    await settingsDialog.getByRole('button', { name: '删除 minimax-cn', exact: true }).click()
+    const deleteDialog = page.getByRole('dialog', { name: '删除 minimax-cn?' })
+    await deleteDialog.waitFor({ timeout: 10_000 })
+    const snapshot = await captureStableAria(
+      page,
+      '[role="dialog"][aria-label="删除 minimax-cn?"]',
+      scaffold.workspaceCwd,
+    )
+    await compareOrRefreshGolden(NATIVE_DELETE_EXPECTED, snapshot, MODE)
+    await deleteDialog.getByRole('button', { name: '取消', exact: true }).click()
+  }, 60_000)
+
+  it('stores the key under the derived reference and keeps the route live', async () => {
     onTestFailed(() => saveFailureShot(page, 'web-e2e-models-add'))
     const dialog = page.getByRole('dialog', { name: '设置' })
-    await dialog.getByLabel('API 密钥').fill('sk-e2e-minimax')
+    await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click()
+    await dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).fill('sk-e2e-minimax')
     await dialog.getByRole('button', { name: '保存', exact: true }).click()
     // The profile lands in settings.yaml with only the derived reference, the
     // key value lands in the harness home's .env, the dormant route
     // registers, and the topology frame invalidates the page into the row.
-    const row = dialog.getByText('minimax-cn', { exact: true }).first()
-    await row.waitFor({ timeout: 10_000 })
+    await expect.poll(
+      async () => dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).count(),
+      { timeout: 10_000 },
+    ).toBe(0)
+    await dialog.getByRole('img', { name: 'API 密钥已配置' }).waitFor({ timeout: 10_000 })
+    await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 10_000 })
     const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
     expect(document).toContain('minimax-cn:')
     expect(document).toContain('apiKeyEnv: MINIMAX_CN_API_KEY')
     expect(document).not.toContain('sk-e2e-minimax')
-    const stored = await readFile(join(scaffold.harnessHome, '.env'), 'utf8')
-    expect(stored).toContain('MINIMAX_CN_API_KEY=sk-e2e-minimax')
+    const credentialFile = join(scaffold.harnessHome, '.env')
+    await expect.poll(
+      async () => readFile(credentialFile, 'utf8').catch(() => ''),
+      { timeout: 10_000 },
+    ).toContain('MINIMAX_CN_API_KEY=sk-e2e-minimax')
     expect(await page.content()).not.toContain('sk-e2e-minimax')
   }, 60_000)
 
   it('applies a customized-settings field as a merge patch', async () => {
     onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized'))
     const dialog = page.getByRole('dialog', { name: '设置' })
-    await dialog.getByRole('button', { name: '编辑' }).click()
+    await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click()
     await dialog.getByText('自定义设置').click()
     const effort = dialog.getByLabel('推理强度')
     await effort.waitFor({ timeout: 10_000 })
@@ -106,6 +146,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
     // The editor closes back to the row; the fold's write merged into the
     // stored profile beside the reference.
     await expect.poll(async () => dialog.getByLabel('推理强度').count(), { timeout: 10_000 }).toBe(0)
+    await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 10_000 })
     const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
     expect(document).toContain('reasoning: high')
     expect(document).toContain('apiKeyEnv: MINIMAX_CN_API_KEY')
@@ -114,32 +155,32 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
     expect(tripwire.pageErrors).toEqual([])
   }, 60_000)
 
-  it('confirms provider deletion before removing its settings profile', async () => {
+  it('confirms an identified provider deletion before removing its profile and key', async () => {
     onTestFailed(() => saveFailureShot(page, 'web-e2e-models-delete'))
     const settingsDialog = page.getByRole('dialog', { name: '设置' })
-    await settingsDialog.getByRole('button', { name: '删除', exact: true }).click()
-    const deleteDialog = page.getByRole('dialog', { name: '删除模型提供方?' })
+    await settingsDialog.getByRole('button', { name: '删除 minimax-cn', exact: true }).click()
+    const deleteDialog = page.getByRole('dialog', { name: '删除 minimax-cn?' })
     await deleteDialog.waitFor({ timeout: 10_000 })
     const snapshot = await captureStableAria(
       page,
-      '[role="dialog"][aria-label="删除模型提供方?"]',
+      '[role="dialog"][aria-label="删除 minimax-cn?"]',
       scaffold.workspaceCwd,
     )
     await compareOrRefreshGolden(DELETE_EXPECTED, snapshot, MODE)
 
     await deleteDialog.getByRole('button', { name: '取消', exact: true }).click()
     expect(await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')).toContain('minimax-cn:')
-    await settingsDialog.getByRole('button', { name: '删除', exact: true }).click()
-    await page.getByRole('dialog', { name: '删除模型提供方?' })
-      .getByRole('button', { name: '删除提供方', exact: true }).click()
+    await settingsDialog.getByRole('button', { name: '删除 minimax-cn', exact: true }).click()
+    await page.getByRole('dialog', { name: '删除 minimax-cn?' })
+      .getByRole('button', { name: '删除 minimax-cn', exact: true }).click()
     await expect.poll(
       async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'),
       { timeout: 10_000 },
     ).not.toContain('minimax-cn:')
     expect(await readFile(join(scaffold.harnessHome, '.env'), 'utf8'))
-      .toContain('MINIMAX_CN_API_KEY=sk-e2e-minimax')
+      .not.toContain('MINIMAX_CN_API_KEY')
     await expect.poll(
-      async () => page.getByRole('dialog', { name: '删除模型提供方?' }).count(),
+      async () => page.getByRole('dialog', { name: '删除 minimax-cn?' }).count(),
       { timeout: 10_000 },
     ).toBe(0)
     await page.keyboard.press('Escape')
@@ -147,6 +188,8 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
   }, 60_000)
 
   it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
-    await assertFixtureInventory(SNAPSHOT_DIR, ['configured.expected.md', 'delete.expected.md', 'empty.expected.md'])
+    await assertFixtureInventory(SNAPSHOT_DIR, [
+      'configured.expected.md', 'delete.expected.md', 'empty.expected.md', 'native-delete.expected.md',
+    ])
   })
 })

+ 0 - 3
apps/web/tests/snapshots/bash-abort-row/ui.expected.md

@@ -7,9 +7,6 @@
 - text: "Run two shell commands: wait for cancellation, then write skipped.txt. {{date}} {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/code-mode-round/ui.expected.md

@@ -7,9 +7,6 @@
 - text: "Using ONE run_code program: run bash `echo CODE_ROUND_OK`, then read the file missing.txt catching its error in the program. Return an object with both outcomes. Then reply DONE and stop. {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/cordis-tool-round/ui.expected.md

@@ -7,9 +7,6 @@
 - text: "Use only Cordis tools. First call cordis_inspect with what \"temporary\". Then call cordis_mount with this exact code: \"return { name: \\\"snapshot-noop\\\", apply(ctx) {} }\". Read its returned id and call cordis_unmount with that exact id. After all three calls succeed, reply exactly CORDIS_UI_DONE and stop. {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/fresh-round-trip/ui.expected.md

@@ -7,9 +7,6 @@
 - text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 52 - 0
apps/web/tests/snapshots/goal-multi-turn-actions/replay.override.json

@@ -0,0 +1,52 @@
+{
+  "patches": [
+    {
+      "at": 2,
+      "entry": {
+        "kind": "chunks",
+        "chunks": [
+          { "type": "block-start", "index": 0, "blockType": "reasoning" },
+          { "type": "reasoning-delta", "index": 0, "text": "There are 4 packages:\n- client/ui-conversation\n- context/session-reference\n- llm/token-meter\n- skill/skill-local\n\nFor this turn (turn 1 of 2), I should randomly pick one package and output its file structure. Let me pick randomly — I'll use $RANDOM or just pick one. Let me use a quick random selection." },
+          { "type": "block-end", "index": 0, "block": { "type": "reasoning", "text": "There are 4 packages:\n- client/ui-conversation\n- context/session-reference\n- llm/token-meter\n- skill/skill-local\n\nFor this turn (turn 1 of 2), I should randomly pick one package and output its file structure. Let me pick randomly — I'll use $RANDOM or just pick one. Let me use a quick random selection." } },
+          { "type": "block-start", "index": 1, "blockType": "tool-call" },
+          { "type": "tool-call-delta", "index": 1, "id": "call_00_dAM4qfVp4LLtRCiJi7d71418", "name": "bash", "argumentsDelta": "{\"command\": \"find packages -maxdepth 2 -mindepth 2 -type d | sort | awk '{print NR\\\": \\\"$0}' && echo \\\"---random pick---\\\" && find packages -maxdepth 2 -mindepth 2 -type d | sort | PATH=/__dsh_fixture_missing__ shuf -n 1\", \"description\": \"Randomly pick one package directory\"}" },
+          { "type": "block-end", "index": 1, "block": { "type": "tool-call", "id": "call_00_dAM4qfVp4LLtRCiJi7d71418", "name": "bash", "arguments": "{\"command\": \"find packages -maxdepth 2 -mindepth 2 -type d | sort | awk '{print NR\\\": \\\"$0}' && echo \\\"---random pick---\\\" && find packages -maxdepth 2 -mindepth 2 -type d | sort | PATH=/__dsh_fixture_missing__ shuf -n 1\", \"description\": \"Randomly pick one package directory\"}" } },
+          { "type": "usage", "usage": { "inputTokens": 156, "outputTokens": 202, "cacheReadTokens": 8448, "reasoningTokens": 80 } },
+          { "type": "finish", "reason": { "kind": "tool-calls" } }
+        ]
+      }
+    },
+    {
+      "at": 7,
+      "entry": {
+        "kind": "chunks",
+        "chunks": [
+          { "type": "block-start", "index": 0, "blockType": "reasoning" },
+          { "type": "reasoning-delta", "index": 0, "text": "The random pick returned the same package as turn 1. Since turn 1 already covered `session-reference`, it would be better to pick a different one for variety. Let me re-roll, excluding the already-covered package." },
+          { "type": "block-end", "index": 0, "block": { "type": "reasoning", "text": "The random pick returned the same package as turn 1. Since turn 1 already covered `session-reference`, it would be better to pick a different one for variety. Let me re-roll, excluding the already-covered package." } },
+          { "type": "block-start", "index": 1, "blockType": "tool-call" },
+          { "type": "tool-call-delta", "index": 1, "id": "call_00_3K2lg9zGfGsTvuh19xv65220", "name": "bash", "argumentsDelta": "{\"command\": \"python3 -c \\\"\\nimport random\\nfrom pathlib import Path\\npkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json'))\\ncandidates = [p for p in pkgs if p != 'packages/context/session-reference']\\nprint(random.Random(0).choice(candidates))\\n\\\"\", \"description\": \"Re-roll excluding the package from turn 1\"}" },
+          { "type": "block-end", "index": 1, "block": { "type": "tool-call", "id": "call_00_3K2lg9zGfGsTvuh19xv65220", "name": "bash", "arguments": "{\"command\": \"python3 -c \\\"\\nimport random\\nfrom pathlib import Path\\npkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json'))\\ncandidates = [p for p in pkgs if p != 'packages/context/session-reference']\\nprint(random.Random(0).choice(candidates))\\n\\\"\", \"description\": \"Re-roll excluding the package from turn 1\"}" } },
+          { "type": "usage", "usage": { "inputTokens": 62, "outputTokens": 164, "cacheReadTokens": 9728, "reasoningTokens": 46 } },
+          { "type": "finish", "reason": { "kind": "tool-calls" } }
+        ]
+      }
+    },
+    {
+      "at": 10,
+      "entry": {
+        "kind": "chunks",
+        "chunks": [
+          { "type": "block-start", "index": 0, "blockType": "text" },
+          { "type": "text-delta", "index": 0, "text": "两个 turn 均已完成,目标达成,标记 goal 为完成。" },
+          { "type": "block-end", "index": 0, "block": { "type": "text", "text": "两个 turn 均已完成,目标达成,标记 goal 为完成。" } },
+          { "type": "block-start", "index": 1, "blockType": "tool-call" },
+          { "type": "tool-call-delta", "index": 1, "id": "call_goal_complete", "name": "update_goal", "argumentsDelta": "{\"goal_id\":\"{{fromRequest:goal-[0-9a-f-]+}}\",\"revision\":1,\"action\":\"complete\"}" },
+          { "type": "block-end", "index": 1, "block": { "type": "tool-call", "id": "call_goal_complete", "name": "update_goal", "arguments": "{\"goal_id\":\"{{fromRequest:goal-[0-9a-f-]+}}\",\"revision\":1,\"action\":\"complete\"}" } },
+          { "type": "usage", "usage": { "inputTokens": 132, "outputTokens": 157, "cacheReadTokens": 10368, "reasoningTokens": 44 } },
+          { "type": "finish", "reason": { "kind": "tool-calls" } }
+        ]
+      }
+    }
+  ]
+}

Разница между файлами не показана из-за своего большого размера
+ 16 - 0
apps/web/tests/snapshots/goal-multi-turn-actions/session.jsonl


+ 200 - 0
apps/web/tests/snapshots/goal-multi-turn-actions/ui.expected.md

@@ -0,0 +1,200 @@
+- banner:
+  - navigation "Session hierarchy":
+    - button "workspace" [disabled]
+  - tablist:
+    - tab "Chat" [selected]
+    - tab "Trajectory"
+- 'button "goal Goal created Status: active Objective: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的 Rounds: 0/256 Activation: armed Commands: /goal edit <objective>, /goal pause, /goal clear"':
+  - img
+  - img
+  - text: "goal Goal created Status: active Objective: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的 Rounds: 0/256 Activation: armed Commands: /goal edit <objective>, /goal pause, /goal clear"
+- button "Context injection goal":
+  - img
+  - img
+  - text: Context injection goal
+- button "Context injection @deepseek-ai/dsh-system-prompt":
+  - img
+  - img
+  - text: Context injection @deepseek-ai/dsh-system-prompt
+- 'button "Think The user''s goal is: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\" — which translates to: \"Do two turns, each turn output the file structure of a random package. Note that after you finish one turn, directly output the content and stop; our system will help you open another turn, and you just do something similar.\""':
+  - img
+  - img
+  - text: "Think The user's goal is: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\" — which translates to: \"Do two turns, each turn output the file structure of a random package. Note that after you finish one turn, directly output the content and stop; our system will help you open another turn, and you just do something similar.\""
+- button "Bash Show working directory and its contents":
+  - img
+  - img
+  - text: Bash Show working directory and its contents
+- 'button "Tool call get_goal · {}"':
+  - img
+  - img
+  - text: "Tool call get_goal · {}"
+- 'button "Think There''s a `packages` directory. Let me look inside to see what packages are available."':
+  - img
+  - img
+  - text: "Think There's a `packages` directory. Let me look inside to see what packages are available."
+- button "Bash List packages directory contents":
+  - img
+  - img
+  - text: Bash List packages directory contents
+- button "Think There are 4 packages:":
+  - img
+  - img
+  - text: "Think There are 4 packages:"
+- button "Failed Bash Randomly pick one package directory":
+  - img
+  - text: Failed Bash Randomly pick one package directory
+- 'button "Think shuf is not available on macOS. I''ll use a different approach for random selection. Let me use $RANDOM in bash or use `sort -R` or Python."':
+  - img
+  - img
+  - text: "Think shuf is not available on macOS. I'll use a different approach for random selection. Let me use $RANDOM in bash or use `sort -R` or Python."
+- button "Bash Randomly select one package with Python":
+  - img
+  - img
+  - text: Bash Randomly select one package with Python
+- 'button "Think The random pick for turn 1 is `packages/context/session-reference`. Now I''ll output its file structure. Let me get the file tree."':
+  - img
+  - img
+  - text: "Think The random pick for turn 1 is `packages/context/session-reference`. Now I'll output its file structure. Let me get the file tree."
+- button "Bash List all files in session-reference package":
+  - img
+  - img
+  - text: Bash List all files in session-reference package
+- 'button "Think Turn 1 is done. Per the objective: \"你做完一个turn之后,直接输出内容,停止\" — after finishing a turn, directly output the content and stop. The system will open another turn."':
+  - img
+  - img
+  - text: "Think Turn 1 is done. Per the objective: \"你做完一个turn之后,直接输出内容,停止\" — after finishing a turn, directly output the content and stop. The system will open another turn."
+- paragraph:
+  - strong: Turn 1 / 2
+  - text: — 随机选中的包:
+  - code: packages/context/session-reference
+  - text: 📦
+- button "Copy"
+- code: session-reference ├── README.md ├── package.json ├── src │ ├── index.ts │ └── uri.ts └── tests └── session-reference.spec.ts
+- button "Copy"
+- code: "session-reference/ ├── README.md # 包说明文档 ├── package.json # 包元数据与依赖声明 ├── src/ │ ├── index.ts # 入口,导出公共 API │ └── uri.ts # 会话引用 URI 相关实现 └── tests/ └── session-reference.spec.ts # 单元测试"
+- paragraph: 这是一个很典型的轻量 TypeScript 包结构:入口 + 实现 + 测试。这一轮到此结束,等系统开启下一个 turn。
+- button "Copy":
+  - img
+- button "Branch into a new conversation":
+  - img
+- text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s
+- button "Context injection goal":
+  - img
+  - img
+  - text: Context injection goal
+- 'button "Think This is turn 2 of 2. I need to randomly pick another package and output its file structure. In the first turn I picked `packages/context/session-reference`. Let me pick a different one randomly this time."':
+  - img
+  - img
+  - text: "Think This is turn 2 of 2. I need to randomly pick another package and output its file structure. In the first turn I picked `packages/context/session-reference`. Let me pick a different one randomly this time."
+- button "Bash Randomly select another package with Python":
+  - img
+  - img
+  - text: Bash Randomly select another package with Python
+- 'button "Think The random pick returned the same package as turn 1. Since turn 1 already covered `session-reference`, it would be better to pick a different one for variety. Let me re-roll, excluding the already-covered package."':
+  - img
+  - img
+  - text: "Think The random pick returned the same package as turn 1. Since turn 1 already covered `session-reference`, it would be better to pick a different one for variety. Let me re-roll, excluding the already-covered package."
+- button "Bash Re-roll excluding the package from turn 1":
+  - img
+  - img
+  - text: Bash Re-roll excluding the package from turn 1
+- button "Bash List all files in token-meter package":
+  - img
+  - img
+  - text: Bash List all files in token-meter package
+- 'button "Think This is turn 2 of 2. I''ve output the file structure for `packages/llm/token-meter`. Both turns are done. I should output the content, stop, and then mark the goal as complete since both turns are finished."':
+  - img
+  - img
+  - text: "Think This is turn 2 of 2. I've output the file structure for `packages/llm/token-meter`. Both turns are done. I should output the content, stop, and then mark the goal as complete since both turns are finished."
+- paragraph:
+  - strong: Turn 2 / 2
+  - text: — 随机选中的包:
+  - code: packages/llm/token-meter
+  - text: 📦
+- button "Copy"
+- code: token-meter ├── README.md ├── package.json ├── src │ └── index.ts └── tests └── token-meter.spec.ts
+- button "Copy"
+- code: "token-meter/ ├── README.md # 包说明文档 ├── package.json # 包元数据与依赖声明 ├── src/ │ └── index.ts # 入口,导出公共 API(token 计量逻辑) └── tests/ └── token-meter.spec.ts # 单元测试"
+- paragraph:
+  - text: 两个 turn 都完成了(turn 1:
+  - code: session-reference
+  - text: ,turn 2:
+  - code: token-meter
+  - text: )。这一轮到此结束。
+- 'button "Tool call get_goal · {}"':
+  - img
+  - img
+  - text: "Tool call get_goal · {}"
+- paragraph: 两个 turn 均已完成,目标达成,标记 goal 为完成。
+- button "Tool call update_goal · goal-{{uuid}}":
+  - img
+  - img
+  - text: Tool call update_goal · goal-{{uuid}}
+- 'button "Context injection tool-goal complete: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的"':
+  - img
+  - img
+  - text: "Context injection tool-goal complete: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的"
+- paragraph: 两个 turn 都完成了 ✅
+- paragraph:
+  - strong: 总结:
+- list:
+  - listitem:
+    - strong: Turn 1
+    - text: — 随机选中
+    - code: packages/context/session-reference
+    - text: ,输出了文件结构:
+    - button "Copy"
+    - code: session-reference/ ├── README.md ├── package.json ├── src/ │ ├── index.ts │ └── uri.ts └── tests/ └── session-reference.spec.ts
+  - listitem:
+    - strong: Turn 2
+    - text: — 随机选中
+    - code: packages/llm/token-meter
+    - text: ,输出了文件结构:
+    - button "Copy"
+    - code: token-meter/ ├── README.md ├── package.json ├── src/ │ └── index.ts └── tests/ └── token-meter.spec.ts
+- paragraph:
+  - strong: 验证方式:
+  - text: 两个包的随机选择都通过
+  - code: python3 random.choice
+  - text: 从工作区的
+  - code: packages/
+  - text: 目录下实际枚举的 4 个候选包中抽取(
+  - code: ui-conversation
+  - text: 、
+  - code: session-reference
+  - text: 、
+  - code: token-meter
+  - text: 、
+  - code: skill-local
+  - text: ),文件结构则用
+  - code: find
+  - text: 实际列出文件后整理输出,均已排除
+  - code: node_modules
+  - text: 和
+  - code: .git
+  - text: 。第二次随机抽到了与 turn 1 相同的包,为避免重复换抽了另一个。
+- paragraph:
+  - strong: 说明:
+  - text: 本轮没有产生任何文件修改或提交——任务本身就是"输出文件结构",所有产物都在上面的消息文本里。
+- paragraph:
+  - text: 如果你还想看剩下两个包(
+  - code: ui-conversation
+  - text: 、
+  - code: skill-local
+  - text: )的结构,或者其他格式的输出(比如带文件大小的树形图),随时告诉我。
+- button "Copy":
+  - img
+- button "Branch into a new conversation":
+  - img
+- tooltip "Branch into a new conversation"
+- text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s
+- textbox "Message the agent"
+- button "Commands":
+  - img
+- 'button "Access mode, current: Workspace Write"': Workspace Write
+- button "Select model, current DeepSeek-V4-Flash":
+  - text: DeepSeek-V4-Flash
+  - img
+- button "9% of context used"
+- button "Send message" [disabled]
+- text: 2 turns · 12 steps LLM {{duration}} · Tool call {{duration}} TTFT avg {{duration}} · {{throughput}} tok/s Cache hit 91% Input 113K tok · Output 2.4K tok

+ 0 - 3
apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with the single word LIGHTHOUSE and stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/live-interactions/cancel.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/live-interactions/error-auth.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/live-interactions/loading.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/live-interactions/retry.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/markdown-cjk-strong/ui.expected.md

@@ -7,9 +7,6 @@
 - text: Render adjacent CJK strong emphasis. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - heading "CJK strong emphasis" [level=2]
 - paragraph:
   - strong: 注意:

+ 0 - 3
apps/web/tests/snapshots/markdown-images/ui.expected.md

@@ -7,9 +7,6 @@
 - text: Show the Markdown image policy. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - heading "Markdown images" [level=2]
 - paragraph:
   - img "Remote test image"

+ 0 - 3
apps/web/tests/snapshots/markdown-inline-code-links/ui.expected.md

@@ -7,9 +7,6 @@
 - text: Show the local preview URL. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - heading "Inline code links" [level=2]
 - paragraph:
   - text: "Preview:"

+ 0 - 3
apps/web/tests/snapshots/math-rendering/ui.expected.md

@@ -7,9 +7,6 @@
 - text: Render this mathematical proof. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - heading "Math rendering" [level=2]
 - paragraph:
   - text: Inline dollar

+ 0 - 6
apps/web/tests/snapshots/message-actions/ui.expected.md

@@ -8,9 +8,6 @@
 - button "Copy":
   - img
 - tooltip "Copy"
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel.":
   - img
   - img
@@ -38,9 +35,6 @@
 - text: Stopped Now give the final answer. 7/25 {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - paragraph: DONE
 - button "Copy":
   - img

+ 4 - 2
apps/web/tests/snapshots/models-settings/configured.expected.md

@@ -13,11 +13,13 @@
     - text: 关闭
   - heading "模型" [level=2]
   - paragraph: 填入各提供方的 API 密钥即可使用其模型。
+  - status: 已保存 minimax-cn。
   - list:
     - listitem:
       - text: minimax-cn
-      - button "编辑"
-      - button "删除"
+      - img "API 密钥已配置"
+      - button "编辑 minimax-cn": 编辑
+      - button "删除 minimax-cn": 删除
   - button "添加提供方":
     - img
     - text: 添加提供方

+ 4 - 4
apps/web/tests/snapshots/models-settings/delete.expected.md

@@ -1,7 +1,7 @@
-- dialog "删除模型提供方?":
-  - heading "删除模型提供方?" [level=2]
+- dialog "删除 minimax-cn?":
+  - heading "删除 minimax-cn?" [level=2]
   - button "关闭":
     - img
-  - paragraph: 删除此模型提供方会移除其配置。在重新添加前,你将无法继续使用其模型。
+  - paragraph: 删除 minimax-cn 会移除其配置和存储的 API 密钥。
   - button "取消"
-  - button "删除提供方"
+  - button "删除 minimax-cn"

+ 1 - 1
apps/web/tests/snapshots/models-settings/empty.expected.md

@@ -55,7 +55,7 @@
     - option "zai-coding-cn"
   - text: API 密钥
   - textbox "API 密钥":
-    - /placeholder: 输入 API 密钥
+    - /placeholder: 输入 API 密钥,或留空使用环境认证
   - group: 自定义设置
   - button "取消"
   - button "保存"

+ 7 - 0
apps/web/tests/snapshots/models-settings/native-delete.expected.md

@@ -0,0 +1,7 @@
+- dialog "删除 minimax-cn?":
+  - heading "删除 minimax-cn?" [level=2]
+  - button "关闭":
+    - img
+  - paragraph: 删除 minimax-cn 会移除其配置;其使用的凭证(如有)由其他位置管理,将会保留。
+  - button "取消"
+  - button "删除 minimax-cn"

+ 2 - 1
apps/web/tests/snapshots/onboarding-deepseek-config/models.expected.md

@@ -16,7 +16,8 @@
   - list:
     - listitem:
       - text: DeepSeek
-      - button "编辑"
+      - img "API 密钥已配置"
+      - button "编辑 DeepSeek (deepseek-official)": 编辑
       - text: DeepSeek deepseek-official API 密钥
       - textbox "API 密钥":
         - /placeholder: 已配置——输入新值可替换

+ 0 - 3
apps/web/tests/snapshots/plan-review/approved.expected.md

@@ -8,9 +8,6 @@
 - text: "plan Plan mode on. Use /plan off to leave. Interjection Plan a small change: add a --greeting flag to a CLI. Do not read or write any files. Call exit_plan_mode with a short plan of at most five bullet points. Once the plan is approved, reply with the single word DONE and stop. {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/question-composer/answered.expected.md

@@ -7,9 +7,6 @@
 - text: "Use the ask_user_question tool to ask me exactly one multi-select question with id \"color\", question \"Which color do you prefer?\", header \"Pick one\", and two options: label \"Blue\" with description \"A cool recessive hue that reads as calm and trustworthy in long reading sessions and dense dashboards.\", and label \"Green\" with description \"A restful mid-spectrum hue with the highest perceived brightness, easiest on the eye over long sessions.\" Set multi_select to true. After I answer, reply with the single word DONE and stop. {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/queue-actions/collapsed.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/queue-actions/editing.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/queue-actions/preserved.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/queue-actions/ui.expected.md

@@ -7,9 +7,6 @@
 - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/seeded-history/command-row.expected.md

@@ -7,9 +7,6 @@
 - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. 7/25 {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel.":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/seeded-history/ui.expected.md

@@ -7,9 +7,6 @@
 - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. 7/25 {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel.":
   - img
   - img

+ 0 - 3
apps/web/tests/snapshots/steering/mid-steer.expected.md

@@ -7,9 +7,6 @@
 - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 0 - 6
apps/web/tests/snapshots/steering/settled.expected.md

@@ -7,9 +7,6 @@
 - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img
@@ -25,9 +22,6 @@
 - text: "Interjection Interjection: include the word BANANA in your final reply. {{clock}}"
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Think The user selected \"Yes\" and wants me to include the word \"BANANA\" in my final reply. Let me acknowledge their answer.":
   - img
   - img

+ 0 - 2
apps/web/tests/snapshots/subagent-conversation/nested.expected.md

@@ -11,8 +11,6 @@
 - text: Give one concrete event sourcing example. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation":
-  - img
 - status:
   - strong: This subagent is read-only for now
   - text: The parent session is offline; reopen it to continue sending messages.

+ 0 - 6
apps/web/tests/snapshots/subagent-conversation/ui.expected.md

@@ -12,9 +12,6 @@
 - text: Explain event sourcing in one sentence. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img
@@ -31,9 +28,6 @@
 - text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s Now give the same explanation to a human reader. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Think The user is asking for a one-sentence description of event sourcing. This is a straightforward knowledge question that doesn't require any skill loading or tool calls.":
   - img
   - img

+ 35 - 0
apps/web/tests/snapshots/turn-tail-actions/running.expected.md

@@ -0,0 +1,35 @@
+- banner:
+  - navigation "Session hierarchy":
+    - button "Begin your reply with the" [disabled]
+  - tablist:
+    - tab "Chat" [selected]
+    - tab "Trajectory"
+- text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}}
+- button "Copy":
+  - img
+- tooltip "Copy"
+- button "Context injection @deepseek-ai/dsh-system-prompt":
+  - img
+  - img
+  - text: Context injection @deepseek-ai/dsh-system-prompt
+- button "Think The user wants me to begin with \"Reading the workspace now.\" and call bash with \"echo alpha\" in the same message. Then after the tool result, reply with the single word DONE and stop.":
+  - img
+  - img
+  - text: Think The user wants me to begin with "Reading the workspace now." and call bash with "echo alpha" in the same message. Then after the tool result, reply with the single word DONE and stop.
+- paragraph: Reading the workspace now.
+- button "Bash Print alpha to stdout":
+  - img
+  - img
+  - text: Bash Print alpha to stdout
+- paragraph: partial
+- status: Deep diving...
+- textbox "Message the agent"
+- button "Commands":
+  - img
+- 'button "Access mode, current: Workspace Write"': Workspace Write
+- button "Select model, current DeepSeek-V4-Flash":
+  - text: DeepSeek-V4-Flash
+  - img
+- button "6% of context used"
+- button "Stop generating"
+- text: 1 turns · 1 steps LLM {{duration}} · Tool call {{duration}} TTFT avg {{duration}} · {{throughput}} tok/s Cache hit 0% Input 7.8K tok · Output 109 tok

+ 36 - 0
apps/web/tests/snapshots/turn-tail-actions/session.jsonl

@@ -0,0 +1,36 @@
+{"type":"session","version":0,"id":"{{sessionId}}","createdAt":1785918212891,"cwd":"{{cwd}}/workspace"}
+{"type":"permission/preset","seq":0,"time":1785918212892,"data":{"preset":"workspace-write"}}
+{"type":"sandbox/mode","seq":1,"time":1785918212893,"data":{"mode":"workspace-write"}}
+{"type":"approval/policy","seq":2,"time":1785918212893,"data":{"policy":"ask"}}
+{"type":"turn/start","seq":3,"time":1785918212945,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user","rpcId":"{{rpcId}}"}}}}
+{"type":"user/message","seq":4,"time":1785918212945,"data":{"content":[{"type":"text","text":"Begin your reply with the plain sentence \"Reading the workspace now.\" as text, and in that same message call the bash tool with the command \"echo alpha\". After the tool result, reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpcId}}"},"role":"user","id":"4dcaa766-7ea2-4c6a-84cb-0d6ab53b5fb4"},"surfaceOp":"append"}
+{"type":"session/title","seq":5,"time":1785918212946,"data":{"title":"Begin your reply with the","messageSeqs":[4],"source":{"kind":"fallback"}}}
+{"type":"user/message","seq":6,"time":1785918212956,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}/workspace\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"role":"user","id":"60b8851a-888c-4d7e-9513-7d845f8d769b"},"surfaceOp":"append"}
+{"type":"step/start","seq":7,"time":1785918212956,"data":{"turn":1,"step":1}}
+{"type":"request/header","seq":8,"time":1785918212957,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}}
+{"type":"request/context","seq":9,"time":1785918212958,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}
+{"type":"assistant/chunk","seq":10,"time":1785918214389,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}}
+{"type":"reasoning-chunks","seq0":11,"time0":1785918214390,"data":{"turn":1,"step":1,"index":0,"dt":[101,1,0,0,0,56,1,0,0,0,0,0,0,72,1,0,0,0,0,29,0,0,0,0,35,1,0,17,39,0,0,0,0,0,31,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," begin"," with"," \"","Reading"," the"," workspace"," now",".\""," and"," call"," bash"," with"," \"","echo"," alpha","\""," in"," the"," same"," message","."," Then"," after"," the"," tool"," result",","," reply"," with"," the"," single"," word"," D","ONE"," and"," stop","."]}}
+{"type":"assistant/chunk","seq":53,"time":1785918214774,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"text"}}}
+{"type":"text-chunks","seq0":54,"time0":1785918214774,"data":{"turn":1,"step":1,"index":1,"dt":[0,0,0,48],"texts":["Reading"," the"," workspace"," now","."]}}
+{"type":"assistant/chunk","seq":59,"time":1785918214841,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}}}
+{"type":"tool-call-chunks","seq0":60,"time0":1785918214842,"data":{"turn":1,"step":1,"index":2,"dt":[28,0,0,0,0,25,0,0,0,52,1,0,0,0,25,0,0,1,15,0,25],"id":"call_00_1yZGg4XTqe0N5r1rnDLx5082","name":"bash","args":["","{","\"","command","\"",": ","\"","echo"," alpha","\"",", ","\"","description","\"",": ","\"","Print"," alpha"," to"," stdout","\"","}"]}}
+{"type":"assistant/chunk","seq":82,"time":1785918215056,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to begin with \"Reading the workspace now.\" and call bash with \"echo alpha\" in the same message. Then after the tool result, reply with the single word DONE and stop."}}}}
+{"type":"assistant/chunk","seq":83,"time":1785918215057,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"Reading the workspace now."}}}}
+{"type":"assistant/chunk","seq":84,"time":1785918215057,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_1yZGg4XTqe0N5r1rnDLx5082","name":"bash","arguments":"{\"command\": \"echo alpha\", \"description\": \"Print alpha to stdout\"}"}}}}
+{"type":"assistant/chunk","seq":85,"time":1785918215057,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":7788,"outputTokens":109,"cacheReadTokens":0,"reasoningTokens":42}}}}
+{"type":"assistant/chunk","seq":86,"time":1785918215057,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
+{"type":"assistant/message","seq":87,"time":1785918215061,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to begin with \"Reading the workspace now.\" and call bash with \"echo alpha\" in the same message. Then after the tool result, reply with the single word DONE and stop."},{"type":"text","text":"Reading the workspace now."},{"type":"tool-call","id":"call_00_1yZGg4XTqe0N5r1rnDLx5082","name":"bash","arguments":"{\"command\": \"echo alpha\", \"description\": \"Print alpha to stdout\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"73708391-4b5f-429e-b71c-ef2114244a95"},"usage":{"inputTokens":7788,"outputTokens":109,"cacheReadTokens":0,"reasoningTokens":42}},"sourceEventSeqs":[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86],"surfaceOp":"append"}
+{"type":"tool/call","seq":88,"time":1785918215062,"data":{"turn":1,"step":1,"callId":"call_00_1yZGg4XTqe0N5r1rnDLx5082","name":"bash","arguments":"{\"command\": \"echo alpha\", \"description\": \"Print alpha to stdout\"}"}}
+{"type":"tool/result","seq":89,"time":1785918215096,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_1yZGg4XTqe0N5r1rnDLx5082"},"content":[{"type":"tool-result","toolCallId":"call_00_1yZGg4XTqe0N5r1rnDLx5082","content":[{"type":"text","text":"alpha\n"}],"isError":false}],"role":"user","id":"8b7ad694-b19e-4728-a804-eef9f53820b9"}},"sourceEventSeqs":[88],"surfaceOp":"append"}
+{"type":"step/end","seq":90,"time":1785918215097,"data":{"turn":1,"step":1}}
+{"type":"step/start","seq":91,"time":1785918215106,"data":{"turn":1,"step":2}}
+{"type":"assistant/chunk","seq":92,"time":1785918216259,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
+{"type":"assistant/chunk","seq":93,"time":1785918216259,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":0,"text":"D"}}}
+{"type":"assistant/chunk","seq":94,"time":1785918216288,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":0,"text":"ONE"}}}
+{"type":"assistant/chunk","seq":95,"time":1785918216289,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}}
+{"type":"assistant/chunk","seq":96,"time":1785918216289,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":103,"outputTokens":3,"cacheReadTokens":7808,"reasoningTokens":0}}}}
+{"type":"assistant/chunk","seq":97,"time":1785918216289,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
+{"type":"assistant/message","seq":98,"time":1785918216289,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"fbb5a6d0-9945-4b52-ad15-978173d450a7"},"usage":{"inputTokens":103,"outputTokens":3,"cacheReadTokens":7808,"reasoningTokens":0}},"sourceEventSeqs":[92,93,94,95,96,97],"surfaceOp":"append"}
+{"type":"step/end","seq":99,"time":1785918216289,"data":{"turn":1,"step":2}}
+{"type":"turn/end","seq":100,"time":1785918216289,"data":{"turn":1,"reason":{"kind":"completed"}}}

+ 40 - 0
apps/web/tests/snapshots/turn-tail-actions/settled.expected.md

@@ -0,0 +1,40 @@
+- banner:
+  - navigation "Session hierarchy":
+    - button "Begin your reply with the" [disabled]
+  - tablist:
+    - tab "Chat" [selected]
+    - tab "Trajectory"
+- text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}}
+- button "Copy":
+  - img
+- button "Context injection @deepseek-ai/dsh-system-prompt":
+  - img
+  - img
+  - text: Context injection @deepseek-ai/dsh-system-prompt
+- button "Think The user wants me to begin with \"Reading the workspace now.\" and call bash with \"echo alpha\" in the same message. Then after the tool result, reply with the single word DONE and stop.":
+  - img
+  - img
+  - text: Think The user wants me to begin with "Reading the workspace now." and call bash with "echo alpha" in the same message. Then after the tool result, reply with the single word DONE and stop.
+- paragraph: Reading the workspace now.
+- button "Bash Print alpha to stdout":
+  - img
+  - img
+  - text: Bash Print alpha to stdout
+- paragraph: partial
+- text: Stopped
+- button "Copy":
+  - img
+- tooltip "Copy"
+- button "Branch into a new conversation":
+  - img
+- text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s
+- textbox "Message the agent"
+- button "Commands":
+  - img
+- 'button "Access mode, current: Workspace Write"': Workspace Write
+- button "Select model, current DeepSeek-V4-Flash":
+  - text: DeepSeek-V4-Flash
+  - img
+- button "6% of context used"
+- button "Send message" [disabled]
+- text: 1 turns · 2 steps LLM {{duration}} · Tool call {{duration}} TTFT avg {{duration}} · {{throughput}} tok/s Cache hit 0% Input 7.8K tok · Output 109 tok

+ 0 - 3
apps/web/tests/snapshots/web-search-round/ui.expected.md

@@ -7,9 +7,6 @@
 - text: Use web_search to search exactly "DeepSeek Harness snapshot search". Then reply exactly SEARCH_DONE and stop. {{clock}}
 - button "Copy":
   - img
-- button "Branch into a new conversation" [disabled]:
-  - img
-- text: Available only on the last message of a completed turn
 - button "Context injection @deepseek-ai/dsh-system-prompt":
   - img
   - img

+ 152 - 0
apps/web/tests/turn-tail-actions.e2e.ts

@@ -0,0 +1,152 @@
+// Web e2e scenario: assistant IconActions belong to the settled answer, so
+// they arrive with `turn/end` and not before. The recorded turn narrates in
+// plain text before its tool call, which is the shape that used to hand the
+// footer to mid-turn narration for the seconds a tool runs and then move it
+// down. A `hang` sidecar on the SECOND model call parks the turn after the
+// narration and the tool result are durable, so the running state is stable by
+// construction rather than by timing; stopping from that park writes the
+// `turn/end` that hands the footer to the turn's transcript tail.
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { fileURLToPath } from 'node:url'
+import { join } from 'node:path'
+import type { Browser, Page } from 'playwright'
+import { chromium } from 'playwright'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import type { ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
+import type { SessionEvent } from '@deepseek-ai/dsh-session'
+import {
+  assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+  launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
+
+const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/turn-tail-actions', import.meta.url))
+const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
+// Two goldens for the same message: parked mid-turn, then settled.
+const RUNNING_EXPECTED = join(SNAPSHOT_DIR, 'running.expected.md')
+const SETTLED_EXPECTED = join(SNAPSHOT_DIR, 'settled.expected.md')
+const MODE = webSnapshotMode()
+
+// The recording must carry text in the SAME assistant message as the tool
+// call; a Think-only step would leave nothing for the footer to attach to and
+// the scenario would pass against either implementation.
+const NARRATION = 'Reading the workspace now.'
+const PROMPT = `Begin your reply with the plain sentence "${NARRATION}" as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop.`
+
+describe('web e2e: assistant IconActions wait for the turn to end', () => {
+  let scaffold: WebScaffold | undefined
+  let browser: Browser | undefined
+  let page: Page
+  let tripwire: ReturnType<typeof watchConsole>
+  let sessionEvents: SessionEvent[]
+  let sidecarDir: string | undefined
+
+  afterEach(async () => {
+    // close() carries the fixture-consumption tripwire, so its failure is the
+    // scenario's failure; run every teardown step, then rethrow what failed.
+    const failures: unknown[] = []
+    await browser?.close().catch((error: unknown) => failures.push(error))
+    browser = undefined
+    const closing = scaffold
+    scaffold = undefined
+    await closing?.close().catch((error: unknown) => failures.push(error))
+    if (sidecarDir !== undefined) await rm(sidecarDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
+    sidecarDir = undefined
+    if (failures.length === 1) throw failures[0]
+    if (failures.length > 1) throw new AggregateError(failures, 'turn-tail-actions teardown failed')
+  })
+
+  /** Boot scaffold + page, materializing the sidecar before the replay row installs. */
+  async function launch(buildOverride?: (sidecarHome: string) => ReplayOverrideDoc): Promise<void> {
+    sessionEvents = []
+    let overridePath: string | undefined
+    if (buildOverride !== undefined) {
+      sidecarDir = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sidecar-'))
+      overridePath = join(sidecarDir, 'replay.override.json')
+      await writeFile(overridePath, JSON.stringify(buildOverride(sidecarDir)))
+    }
+    scaffold = await launchWebScaffold(
+      MODE === 'record'
+        ? {}
+        : { replayFixture: FIXTURE, ...(overridePath === undefined ? {} : { replayOverride: overridePath }) },
+    )
+    scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
+    browser = await chromium.launch()
+    page = await newEnglishPage(browser)
+    tripwire = watchConsole(page)
+    await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
+    await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
+    await connectFreshWorkspace(page, scaffold.workspaceCwd)
+  }
+
+  /** Send the recorded prompt with the settled barrier pre-armed (returned wrapped so the caller can act mid-turn). */
+  async function sendPrompt(timeoutMs?: number): Promise<{ settled: ReturnType<WebScaffold['whenTurnSettled']> }> {
+    const input = page.locator('textarea').first()
+    await input.waitFor({ timeout: 10_000 })
+    const settled = scaffold!.whenTurnSettled(timeoutMs)
+    await input.fill(PROMPT)
+    await input.press('Enter')
+    return { settled }
+  }
+
+  it.skipIf(MODE !== 'record')('records the narrate-then-call turn live through the composer', async () => {
+    await launch()
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-turn-tail-actions-record'))
+    const { settled } = await sendPrompt(180_000)
+    const sessionId = await settled
+    await recordFixture(scaffold!, sessionId, FIXTURE)
+  }, 200_000)
+
+  it.skipIf(MODE === 'record')('withholds the footer while the turn runs and grants it at turn/end', async () => {
+    expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
+    let marker = ''
+    // Patch the SECOND call: the first one delivers the narration and the tool
+    // call as recorded, so the park happens with a durable mid-turn message.
+    await launch((sidecarHome) => {
+      marker = join(sidecarHome, '.hang-ready')
+      return { patches: [{ at: 1, entry: { kind: 'hang', readyFile: marker } }] }
+    })
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-turn-tail-actions'))
+    // The barrier is armed before the park and awaited only after the stop
+    // click, so its budget must cover the whole parked phase: marker poll,
+    // three UI polls, and two captures with their stability windows. The
+    // replay default (30s) leaves no headroom on a slow runner.
+    const { settled } = await sendPrompt(120_000)
+    // The marker IS the synchronization: the second call is provably parked,
+    // so the first step's message and tool result are already durable.
+    await expect.poll(() => existsSync(marker), { timeout: 20_000 }).toBe(true)
+    await expect.poll(() => page.getByText(NARRATION, { exact: true }).count(), { timeout: 10_000 }).toBe(1)
+    await expect.poll(
+      () => page.getByRole('status').filter({ hasText: 'Deep diving...' }).isVisible(),
+      { timeout: 10_000 },
+    ).toBe(true)
+    // Only the user bubble owns a footer (clock + copy; user bubbles carry no
+    // branch action): the narration is not the answer yet.
+    const copyButtons = page.getByRole('button', { name: 'Copy' })
+    await expect.poll(() => copyButtons.count(), { timeout: 10_000 }).toBe(1)
+    expect(await page.getByRole('button', { name: 'Branch into a new conversation' }).count()).toBe(0)
+    await copyButtons.first().focus()
+    const running = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
+    await compareOrRefreshGolden(RUNNING_EXPECTED, running, MODE)
+
+    // Closing the turn from the park is the state change under test: an
+    // aborted turn is durably closed, so its transcript tail (the frozen
+    // partial) takes the seat while the mid-turn narration keeps none.
+    await page.getByRole('button', { name: 'Stop generating' }).click()
+    await settled
+    expect(sessionEvents.filter(e => e.type === 'turn/end').map(e => e.data.reason.kind)).toEqual(['aborted'])
+    await expect.poll(() => copyButtons.count(), { timeout: 10_000 }).toBe(2)
+    await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 10_000 }).toBe(0)
+    await copyButtons.last().focus()
+    const settledAria = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
+    await compareOrRefreshGolden(SETTLED_EXPECTED, settledAria, MODE)
+    expect(tripwire.pageErrors).toEqual([])
+    expect(tripwire.warnings).toEqual([])
+  }, 120_000)
+
+  it.skipIf(MODE === 'record')('keeps a closed fixture inventory', async () => {
+    await assertFixtureInventory(SNAPSHOT_DIR, ['running.expected.md', 'session.jsonl', 'settled.expected.md'])
+  })
+})

+ 2 - 0
apps/web/tsconfig.json

@@ -63,6 +63,8 @@
     "tests/startup-auto-selection.e2e.ts",
     "tests/subagent-conversation.e2e.ts",
     "tests/bash-abort-row.e2e.ts",
+    "tests/turn-tail-actions.e2e.ts",
+    "tests/goal-multi-turn-actions.e2e.ts",
     "tests/chat-scroll-fixture.ts",
     "tests/chat-scroll-contract.e2e.ts",
     "tests/chat-long-interactions.e2e.ts",

+ 8 - 4
docs/config-catalog.md

@@ -668,7 +668,10 @@ Requires: `llm`
  * reasoning effort resolves to `high`.
  */
 export interface Config {
-  /** Literal API key; prefer {@link apiKeyEnv} so no secret enters configuration files. */
+  /**
+   * Trimmed literal API key; whitespace-only is absent. Prefer
+   * {@link apiKeyEnv} to keep secrets out of configuration files.
+   */
   apiKey?: string
   /** Credential reference (environment-variable name) resolved per request; defaults to `DEEPSEEK_API_KEY`. */
   apiKeyEnv?: string
@@ -2218,8 +2221,9 @@ export interface Config {
   /**
    * Model presentation. `native` (default) sends every visible schema; `code`
    * sends only `run_code` plus a generated SDK prompt; `both` sends both forms.
-   * Code modes require a TypeScript runtime and fail prompt assembly when it is
-   * absent or mismatched. Under `code`, native names in `toolOrder` are invalid.
+   * Code modes require a `ctx.codeRuntime` whose `language` has a registered
+   * SDK renderer (TypeScript or Python) and fail prompt assembly when it is
+   * absent or has no renderer. Under `code`, native names in `toolOrder` are invalid.
    */
   mode?: ToolPresentationMode
   /**
@@ -2236,7 +2240,7 @@ export interface Config {
 export type ToolPresentationMode = 'native' | 'code' | 'both'
 ```
 
-Source: [`packages/core/tools/src/index.ts:592`](../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:616`](../packages/core/tools/src/index.ts)
 
 ## `@deepseek-ai/dsh-typert-loader`
 

+ 6 - 6
docs/cordis-catalog/events.md

@@ -842,7 +842,7 @@ A tool was registered or unregistered, or a scoped restriction changed (the avai
 'tools/change'(): void
 ```
 
-Source: [`packages/core/tools/src/index.ts:167`](../../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:191`](../../packages/core/tools/src/index.ts)
 
 ### `tools/code-dispatch-log` — waterfall
 
@@ -866,7 +866,7 @@ Shape the DURABLE LOG COPY of one `run_code` sub-dispatch outcome before the bri
 
 Types: [CodeDispatchLog](../core-data-structures/tools.md) · [ContentBlock](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) · [ToolRegistry](../core-data-structures/tools.md)
 
-Source: [`packages/core/tools/src/index.ts:149`](../../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:173`](../../packages/core/tools/src/index.ts)
 
 ### `tools/execute` — waterfall
 
@@ -888,7 +888,7 @@ Around-dispatch waterfall for timeout, retry, or metrics. `next()` returns a nor
 
 Types: [Scoped](../core-data-structures/scope.md) · [ToolDispatchExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md)
 
-Source: [`packages/core/tools/src/index.ts:124`](../../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:148`](../../packages/core/tools/src/index.ts)
 
 ### `tools/post-execute` — waterfall
 
@@ -911,7 +911,7 @@ Accept, replace, enrich, or block a normalized dispatch result. `next()` accepts
 
 Types: [PostToolDecision](../core-data-structures/tools.md) · [Scoped](../core-data-structures/scope.md) · [ToolExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md)
 
-Source: [`packages/core/tools/src/index.ts:136`](../../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:160`](../../packages/core/tools/src/index.ts)
 
 ### `tools/pre-execute` — waterfall
 
@@ -932,7 +932,7 @@ Allow, deny, or ask before dispatch. `next()` delegates to allow; missing approv
 
 Types: [PreToolDecision](../core-data-structures/tools.md) · [Scoped](../core-data-structures/scope.md) · [ToolExecution](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md)
 
-Source: [`packages/core/tools/src/index.ts:113`](../../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:137`](../../packages/core/tools/src/index.ts)
 
 ### `tools/result` — emit
 
@@ -951,7 +951,7 @@ Observe the frozen, lossless-JSON final outcome. Listener failures are contained
 
 Types: [Scoped](../core-data-structures/scope.md) · [ToolExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md)
 
-Source: [`packages/core/tools/src/index.ts:157`](../../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:181`](../../packages/core/tools/src/index.ts)
 
 ## `workflow/*`
 

+ 2 - 2
docs/cordis-catalog/services.md

@@ -398,7 +398,7 @@ abstract run(request: CodeRunRequest): Promise<CodeRunResult>
 
 Types: [CodeRunRequest](../core-data-structures/code-runtime.md) · [CodeRunResult](../core-data-structures/code-runtime.md)
 
-Source: [`packages/code-runtime/code-runtime/src/index.ts:33`](../../packages/code-runtime/code-runtime/src/index.ts)
+Source: [`packages/code-runtime/code-runtime/src/index.ts:104`](../../packages/code-runtime/code-runtime/src/index.ts)
 
 ## `ctx.commands` — `CommandService`
 
@@ -2523,7 +2523,7 @@ async execute(exec: ToolExecutionInput): Promise<ToolExecutionResult>
 
 Types: [ScopeKey](../core-data-structures/scope.md) · [ToolDefinition](../core-data-structures/tools.md) · [ToolExecutionInput](../core-data-structures/tools.md) · [ToolExecutionMode](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolGuard](../core-data-structures/tools.md) · [ToolRestriction](../core-data-structures/tools.md) · [ToolSchema](../core-data-structures/tools.md)
 
-Source: [`packages/core/tools/src/index.ts:714`](../../packages/core/tools/src/index.ts)
+Source: [`packages/core/tools/src/index.ts:739`](../../packages/core/tools/src/index.ts)
 
 ## `ctx.typert` — `TypertRegistry`
 

+ 2 - 2
docs/core-data-structures/code-runtime.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/core-data-structures/code-runtime.md
-code-runtime.md: 64de3c45d4f1d1d981daa6c6f074abb667e0aa52
-code-runtime.zh.md: daf07aaf613852a6c4a7b1aff152fcc61052fbca
+code-runtime.md: fbce7d812b7609716fb43ae01610253008e0a92c
+code-runtime.zh.md: 700146cfaa9cfab37ec4d85e550020acf1d9f294

+ 18 - 4
docs/core-data-structures/code-runtime.md

@@ -72,9 +72,14 @@ Each `CodeBindingNamespace` becomes one global object of async callables inside
  * of a particular consumer such as Code Mode.
  */
 interface CodeBindingErrorClass {
-  /** Constructor global and resulting `Error.name` (must be a usable JS identifier). */
+  /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link CodeBindingNamespace.global}. */
   name: string
-  /** Non-empty own property for the member name; cannot replace `name`, `message`, or `stack`. */
+  /**
+   * Non-empty own property for the member name. The portable exclusion set is
+   * `RESERVED_ERROR_MEMBERS` plus dunder-form names (`__x__`, non-empty
+   * middle), enforced identically by every backend; any other name —
+   * identifiers or not — is accepted everywhere.
+   */
   memberNameProperty: string
 }
 ```
@@ -88,7 +93,16 @@ interface CodeBindingErrorClass {
  * collisions.
  */
 interface CodeBindingNamespace {
-  /** The global identifier the program sees (must be a valid JS identifier). */
+  /**
+   * The global identifier the program sees. Must match the LANGUAGE-PORTABLE
+   * identifier subset `[A-Za-z_][A-Za-z0-9_]*` and no language's reserved
+   * words, so the same namespace list works against every backend regardless
+   * of `language` — a JS-only spelling like `$tools` is rejected by design,
+   * not just by the Python backend. Names that satisfy the identifier rule but
+   * name a backend-owned slot (`RESERVED_BINDING_GLOBALS`, e.g. `console`,
+   * `__dsh_main__`) are also refused everywhere; see its declaration for the
+   * exact set and why each entry is reserved.
+   */
   global: string
   /** The callable members, keyed by the exact name the program calls. */
   functions: Record<string, CodeBindingFunction>
@@ -144,4 +158,4 @@ interface CodeRunFailure {
 
 ## The service
 
-`CodeRuntime` (`ctx.codeRuntime`, abstract — defined in [`packages/code-runtime/code-runtime/src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts)) is `run(request)` plus two readonly descriptors: `language` (what the program must be written in — `'typescript'` is the well-known value; a consumer generating language-specific presentation switches on it and fails loud on one it cannot present) and `isolation` (the execution substrate — `'worker-thread'`, `'process'`, `'container'`; a diagnostic label, **not a security claim**). Implementations must keep runs isolated from each other (no cross-run state) and dispose to quiescence: in-flight runs are terminated and awaited before teardown completes.
+`CodeRuntime` (`ctx.codeRuntime`, abstract — defined in [`packages/code-runtime/code-runtime/src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts)) is `run(request)` plus two readonly descriptors: `language` (what the program must be written in — `'typescript'` and `'python'` are the well-known values, those `dsh-tools` presents, and only `'typescript'` has a published backend; a consumer generating language-specific presentation switches on it and fails loud on one it cannot present) and `isolation` (the execution substrate — `'worker-thread'`, `'process'`, `'container'`; a diagnostic label, **not a security claim**). Implementations must keep runs isolated from each other (no cross-run state) and dispose to quiescence: in-flight runs are terminated and awaited before teardown completes.

+ 18 - 4
docs/core-data-structures/code-runtime.zh.md

@@ -72,9 +72,14 @@ interface CodeRunResult {
  * of a particular consumer such as Code Mode.
  */
 interface CodeBindingErrorClass {
-  /** Constructor global and resulting `Error.name` (must be a usable JS identifier). */
+  /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link CodeBindingNamespace.global}. */
   name: string
-  /** Non-empty own property for the member name; cannot replace `name`, `message`, or `stack`. */
+  /**
+   * Non-empty own property for the member name. The portable exclusion set is
+   * `RESERVED_ERROR_MEMBERS` plus dunder-form names (`__x__`, non-empty
+   * middle), enforced identically by every backend; any other name —
+   * identifiers or not — is accepted everywhere.
+   */
   memberNameProperty: string
 }
 ```
@@ -88,7 +93,16 @@ interface CodeBindingErrorClass {
  * collisions.
  */
 interface CodeBindingNamespace {
-  /** The global identifier the program sees (must be a valid JS identifier). */
+  /**
+   * The global identifier the program sees. Must match the LANGUAGE-PORTABLE
+   * identifier subset `[A-Za-z_][A-Za-z0-9_]*` and no language's reserved
+   * words, so the same namespace list works against every backend regardless
+   * of `language` — a JS-only spelling like `$tools` is rejected by design,
+   * not just by the Python backend. Names that satisfy the identifier rule but
+   * name a backend-owned slot (`RESERVED_BINDING_GLOBALS`, e.g. `console`,
+   * `__dsh_main__`) are also refused everywhere; see its declaration for the
+   * exact set and why each entry is reserved.
+   */
   global: string
   /** The callable members, keyed by the exact name the program calls. */
   functions: Record<string, CodeBindingFunction>
@@ -144,4 +158,4 @@ interface CodeRunFailure {
 
 ## 服务
 
-`CodeRuntime`(`ctx.codeRuntime`,抽象服务,定义于 [`packages/code-runtime/code-runtime/src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts))由 `run(request)` 加两个只读描述符组成:`language`(程序必须使用的语言,`'typescript'` 是已知值;生成语言相关展示的消费方据此切换,遇到无法展示的语言时应显式报错)和 `isolation`(执行基底,`'worker-thread'`、`'process'`、`'container'`;仅为诊断标签,**不构成安全承诺**)。实现必须保证各次运行彼此隔离(无跨运行状态),并在 dispose(资源释放)时等待系统完全停稳:teardown 要等到所有进行中的运行均已终止并结算后才完成。
+`CodeRuntime`(`ctx.codeRuntime`,抽象服务,定义于 [`packages/code-runtime/code-runtime/src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts))由 `run(request)` 加两个只读描述符组成:`language`(程序必须使用的语言,已知值为 `'typescript'` 与 `'python'`,即 `dsh-tools` 能呈现的那些,其中只有 `'typescript'` 有已发布的后端;生成语言相关展示的消费方据此切换,遇到无法展示的语言时应显式报错)和 `isolation`(执行基底,`'worker-thread'`、`'process'`、`'container'`;仅为诊断标签,**不构成安全承诺**)。实现必须保证各次运行彼此隔离(无跨运行状态),并在 dispose(资源释放)时等待系统完全停稳:teardown 要等到所有进行中的运行均已终止并结算后才完成。

+ 6 - 6
docs/event-producer-consumer.md

@@ -44,12 +44,12 @@ This matrix shows which packages dispatch each harness-owned event and which pac
 | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:29`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`agent`](../packages/core/agent), [`system-prompt`](../packages/core/system-prompt) |
 | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:35`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - |
 | `telemetry/record` | `waterfall` | [`packages/telemetry/session-telemetry/src/index.ts:41`](../packages/telemetry/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/telemetry/session-telemetry) (`waterfall`) | - |
-| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:167`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`emit`) | - |
-| `tools/code-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:149`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) |
-| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:124`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`timeout-policy`](../packages/timeout/timeout-policy) |
-| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:136`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) |
-| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:113`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`tool-tasks`](../packages/tasks/tool-tasks) |
-| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:157`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`workspace-context`](../packages/context/workspace-context) |
+| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:191`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`emit`) | - |
+| `tools/code-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:173`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) |
+| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:148`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`timeout-policy`](../packages/timeout/timeout-policy) |
+| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:160`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) |
+| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:137`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`tool-tasks`](../packages/tasks/tool-tasks) |
+| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:181`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`workspace-context`](../packages/context/workspace-context) |
 | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:81`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`workflow`](../packages/workflow/workflow) |
 | `workflow/agent-start` | `emit` | [`packages/workflow/workflow/src/index.ts:70`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`workflow`](../packages/workflow/workflow) |
 | `workflow/end` | `emit` | [`packages/workflow/workflow/src/index.ts:91`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`workflow`](../packages/workflow/workflow) |

+ 2 - 2
docs/tool-catalog.md

@@ -16,7 +16,7 @@ This table connects model-visible tool names to the plugin package and service s
 | Tool package | Model-visible names | Requires | Writes / affects | Shipped aliases | Deployment note |
 | --- | --- | --- | --- | --- | --- |
 | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userInteraction` | `tool/call`, `tool/result after a UI/provider answers the question` | - | ask_user_question pauses the tool call until the active UI provider returns a human answer. |
-| `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated TypeScript SDK section, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. |
+| `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated SDK section in the loaded runtime's language, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. |
 | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.userInteraction (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-interaction seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. |
 | `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. |
 | `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); it mirrors the bash tool call-for-call minus the sandbox surface — `run_in_background` runs register with the generic `ctx.tasks` runtime and are collected/stopped through the `task_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-bash-env`. Each call runs in a fresh process (no persistent PTY session; ConPTY is roadmap work), with native `C:\...` paths and `$env:NAME` variables. |
@@ -139,7 +139,7 @@ Execute a TypeScript program against the available tools. Write the BODY of an a
 
 Source: [`packages/core/tools/src/code-mode.ts`](../packages/core/tools/src/code-mode.ts)
 
-Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated TypeScript SDK section, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result.
+Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated SDK section in the loaded runtime's language, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result.
 
 ## `@deepseek-ai/dsh-plan-mode`
 

+ 2 - 2
packages/client/ui-conversation/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md
-README.md: 31ae990d2d97757a4d7ea06b323e2131f764b5f7
-README.zh.md: 0f21da2f48dbfd6673fb02d6719390bec872afeb
+README.md: a75f25d8669cd688795842a655106e0e27bb7173
+README.zh.md: f0d744c31020730857d210d75749b907dbffca08

+ 3 - 3
packages/client/ui-conversation/README.md

@@ -38,7 +38,7 @@ The todo surfaces are two registrations over that shape, both using slot declara
 
 `QueueDock` is the terminal input-dock entry at `order: 20`. It hides while empty, renders one pending row directly, and defaults two or more rows to a collapsed `"<n> 条排队消息"` header whose button expands or collapses the complete list. The header exposes `aria-expanded` and `aria-controls`; the expanded list scrolls within a 180px height bound. An active edit or mutation keeps its rows visible, and emptying the queue restores the collapsed default for the next queue. Each visible ordinary-session row remains a single-line preview with its exact-occurrence edit, delete, and strict-steer actions; addressed subagents retain the rows as a read-only projection because their continuation transport does not expose queue mutation. If strict steer loses to a closed window, the original occurrence remains queued for normal delivery; if the driver already claimed it, normal delivery is already underway. Neither converged race displays a failure, while transport and unknown failures do.
 
-The Host's placement-aware `session/queue` snapshot also carries pending steering. QueueDock filters it out, while ChatView projects it as a user-style bubble with Copy at the conversation tail; non-user next-step items (injected context) carry the `context` placement instead and render nowhere until claimed. Fork stays absent because the message has not entered a durable turn. The Host delays steering retirement until the durable `user/message` carrying the steering has entered the mux stream. On that accepted live event, the client runtime retires the first matching current steering occurrence before publishing the snapshot; historical events cannot hide later occurrences that reuse the same `MessageId`. The bubble therefore hands off without a gap or duplicate, immediately restores Copy and the branch control from the durable node, enables branch only when that node is the completed turn's transcript tail, and survives reconnect from the same authority.
+The Host's placement-aware `session/queue` snapshot also carries pending steering. QueueDock filters it out, while ChatView projects it as a user-style bubble with Copy at the conversation tail; non-user next-step items (injected context) carry the `context` placement instead and render nowhere until claimed. Fork is absent here as on every user-style bubble. The Host delays steering retirement until the durable `user/message` carrying the steering has entered the mux stream. On that accepted live event, the client runtime retires the first matching current steering occurrence before publishing the snapshot; historical events cannot hide later occurrences that reuse the same `MessageId`. The bubble therefore hands off without a gap or duplicate, immediately restores Copy and the clock from the durable node — a steering bubble, like a user bubble, carries no branch action ([decision](../../../.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md)) — and survives reconnect from the same authority.
 
 Keyboard message submission resolves delivery from the addressed session's running state and steering capability. While idle, Enter and Cmd/Ctrl+Enter both perform an ordinary Queue send. While a primary session is running, the browser-persisted General Settings preference assigns plain Enter to `Queue` (the default) or `Steer`, and Cmd/Ctrl+Enter performs the other behavior; Shift+Enter remains a newline. With an empty draft, Cmd/Ctrl+Enter instead steers every still-pending queued message into the running turn in FIFO order (the dock's per-row strict-steer action applied to the whole queue); plain Enter with an empty draft remains a no-op. Addressed subagents keep both gestures on their Queue-only continuation transport even while running. The preference affects only the steer-capable busy-state gesture pair, and the send button and non-keyboard submit actions remain Queue. Composer Steer uses the existing best-effort `session.prompt(mode: 'steer')` contract: if the current next-step window closes before acceptance, AgentLoop admits the message as the next waking Queue turn without surfacing a failure or losing the draft transaction.
 
@@ -63,8 +63,8 @@ None; this package neither assembles nor sends a provider request.
 - **Compaction markers show no scale** — the row does not yet report how many messages or which range the checkpoint replaced.
 - **Stats-line durations and speeds cover the in-window flow only** — LLM and tool wall times plus the TTFT and throughput averages fold the snapshot's assistant `timing` and tool call/result pairs, so nodes outside the loaded event window (older history) are not counted.
 - **The details panel has no entry point** — `ChatViewInjected.openDetails` is implemented but uncalled, so the raw selected-call display is unreachable in the assembled application. There is no Input/Output/Metadata switch, Prev/Next stepping, or trajectory deep link.
-- **Assistant per-message paging is a reserved slot** — drawn in the design, not implemented. The finalized content IconActions row (copy / clock / branch) ships under the last content-text assistant of each turn only; mid-turn narration and Think-only nodes stay chrome-free. Branch stays disabled unless that message is also the last transcript node of a completed turn; when enabled, it forks through that turn, increments the inherited title on the client, and opens the child. A fork or rename failure leaves the source selected ([decision](../../../.agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md)).
-- **Sent user messages cannot be edited** — user bubbles retain clock, copy, and branch; branch stays disabled unless a completed turn's transcript ends at that user message. Editing returns with the capability behind it: a client mutation over a settled user message, plus the host behavior for the turn that already consumed it ([decision](../../../.agents/notes/implemented/simplification/2026-07-31-drop-user-message-edit-stub.md)).
+- **Assistant per-message paging is a reserved slot** — drawn in the design, not implemented. The finalized content IconActions row (copy / clock / branch) ships under the last content-text assistant of each turn that has ended; mid-turn narration, Think-only nodes, and every node of a turn still producing steps stay chrome-free. Branch stays disabled unless that message is also the last transcript node of a completed turn; when enabled, it forks through that turn, increments the inherited title on the client, and opens the child. A fork or rename failure leaves the source selected ([decision](../../../.agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md)).
+- **Sent user messages cannot be edited** — user bubbles retain clock and copy; branch lives only under assistant answers ([decision](../../../.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md)). Editing returns with the capability behind it: a client mutation over a settled user message, plus the host behavior for the turn that already consumed it ([decision](../../../.agents/notes/implemented/simplification/2026-07-31-drop-user-message-edit-stub.md)).
 - **The sparkle icon for the others tool row is a hand-drawn approximation** — the design glyph's vector geometry is not exportable locally; promotion into ui-primitives waits on an exact export.
 - **The approval panel has no durable grant control** — it supports allow-once and reject only.
 - **TodoPanel truncates long item text to one ellipsized line** — the figma strip has no wrap or expand affordance; full text is not readable inline.

+ 3 - 3
packages/client/ui-conversation/README.zh.md

@@ -38,7 +38,7 @@ todo 两个面就是在该形状上的两个注册项,都使用 slot 声明注
 
 `QueueDock` 是 `order: 20` 的末端 input-dock 条目。队列为空时隐藏;只有一个待处理项时直接渲染该行;存在两个或更多待处理项时,默认收起为 `"<n> 条排队消息"` 表头,其按钮可展开或收起完整列表。表头暴露 `aria-expanded` 和 `aria-controls`;展开后的列表以 180px 为高度上限,并可滚动。存在进行中的编辑或变更时,列表行会保持可见;队列清空后,下一次出现队列时会恢复默认收起状态。普通会话中的每条可见行仍是单行预览,并提供针对精确单次入队项的编辑、删除和严格 steering 操作;已寻址 subagent 则保留只读行,因为其继续执行传输不提供 Queue 变更。如果严格 steering 输给已关闭的窗口,原单次入队项会留在 Queue 中正常投递;如果驱动器已经认领该项,正常投递就已开始。这两种已收敛的竞态都不显示失败,传输和未知错误仍会显示。
 
-Host 带 placement 的 `session/queue` 快照也会携带待处理 steering。QueueDock 会将其过滤掉,ChatView 则把它投影为会话流末尾带复制操作的用户样式气泡;非用户来源的 next-step 项(注入上下文)改以 `context` placement 广播,领取前不在任何界面渲染。消息尚未进入持久轮次,因此不显示 fork。Host 会等携带该 steering 的持久 `user/message` 进入 mux 流之后再退役 steering。客户端运行时接纳该实时事件时,会在发布快照前退役第一个匹配的当前 steering 单次入队项;历史事件无法隐藏后来复用同一 `MessageId` 的单次入队项。气泡交接时因而不会产生空档或重复,会立即从持久节点恢复复制操作与分支控件,仅当该节点是已完成轮次的 transcript 尾部时才启用分支,并能在重连后从同一权威恢复。
+Host 带 placement 的 `session/queue` 快照也会携带待处理 steering。QueueDock 会将其过滤掉,ChatView 则把它投影为会话流末尾带复制操作的用户样式气泡;非用户来源的 next-step 项(注入上下文)改以 `context` placement 广播,领取前不在任何界面渲染。与所有用户样式气泡一样,这里不显示 fork。Host 会等携带该 steering 的持久 `user/message` 进入 mux 流之后再退役 steering。客户端运行时接纳该实时事件时,会在发布快照前退役第一个匹配的当前 steering 单次入队项;历史事件无法隐藏后来复用同一 `MessageId` 的单次入队项。气泡交接时因而不会产生空档或重复,会立即从持久节点恢复复制操作与时钟——steering 气泡与 user 气泡一样不带分支操作([决策](../../../.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md))——并能在重连后从同一权威恢复。
 
 键盘消息提交会根据所寻址会话的运行状态和 steering 能力解析投递方式。空闲时,Enter 和 Cmd/Ctrl+Enter 都执行普通 Queue 发送。主会话运行期间,浏览器持久化的 General Settings 偏好会把普通 Enter 分配为 `Queue`(默认值)或 `Steer`,Cmd/Ctrl+Enter 则执行另一种行为;Shift+Enter 仍然换行。草稿为空时,Cmd/Ctrl+Enter 改为按 FIFO 顺序把仍在排队的消息全部插话进运行中的轮次(把 dock 的逐条严格 steer 操作应用于整个队列);空草稿 + 普通 Enter 仍是无操作。已寻址 subagent 即使正在运行,也会让这两个手势都使用其仅支持 Queue 的继续执行传输。该偏好只影响支持 steering 的繁忙态手势对,发送按钮与非键盘提交操作仍使用 Queue。Composer Steer 复用现有尽力而为的 `session.prompt(mode: 'steer')` 契约:如果当前 next-step 窗口在接纳前关闭,AgentLoop 会把消息接纳为下一条唤醒 Queue 轮次,不显示失败,也不会丢失草稿事务。
 
@@ -63,8 +63,8 @@ Host 带 placement 的 `session/queue` 快照也会携带待处理 steering。Qu
 - **压缩标记不显示规模**:该行尚不报告检查点替换了多少条消息或哪段范围。
 - **统计行的耗时与速率只覆盖窗口内消息流**:LLM 与工具墙钟时间以及 TTFT 与吞吐平均值由快照的 assistant `timing` 与工具 call/result 配对折算,落在已加载事件窗口之外的节点(更早的历史)不计入。
 - **详情面板没有入口**:`ChatViewInjected.openDetails` 虽已实现却无人调用,因此以原始形式显示已选择调用的那部分在组装后的应用中不可达。没有 Input/Output/Metadata 切换、Prev/Next 步进,也没有 trajectory 深链接。
-- **assistant 逐消息分页是预留 slot**:设计中已有图稿,尚未实现。已定稿的内容 IconActions 行(复制/时钟/分支)只挂在每个轮次中最后一条带 text 内容的 assistant 下;轮次中间的叙述与纯 Think 节点不带 chrome。除非该消息同时也是已完成轮次的最后一个 transcript 节点,否则分支保持禁用;启用后,它会 fork 到该轮次末尾,在 client 端递增继承标题并打开子会话。fork 或改名失败时源会话保持选中([决策](../../../.agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md))。
-- **已发送的 user 消息无法编辑**:user 气泡保留时钟、复制和分支;除非已完成轮次的 transcript 结束于该 user 消息,否则分支保持禁用。编辑功能要与其背后的能力一起回归:既需要针对已定稿 user 消息的 client 变更,也需要 host 侧对已经消费过它的轮次给出行为([决策](../../../.agents/notes/implemented/simplification/2026-07-31-drop-user-message-edit-stub.md))。
+- **assistant 逐消息分页是预留 slot**:设计中已有图稿,尚未实现。已定稿的内容 IconActions 行(复制/时钟/分支)只挂在每个已结束轮次中最后一条带 text 内容的 assistant 下;轮次中间的叙述、纯 Think 节点,以及仍在产出步骤的轮次里的所有节点都不带 chrome。除非该消息同时也是已完成轮次的最后一个 transcript 节点,否则分支保持禁用;启用后,它会 fork 到该轮次末尾,在 client 端递增继承标题并打开子会话。fork 或改名失败时源会话保持选中([决策](../../../.agents/notes/implemented/bug-fix/2026-08-02-message-fork-actions-require-completed-turn-tail.md))。
+- **已发送的 user 消息无法编辑**:user 气泡保留时钟和复制;分支只存在于 assistant 回答之下([决策](../../../.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md))。编辑功能要与其背后的能力一起回归:既需要针对已定稿 user 消息的 client 变更,也需要 host 侧对已经消费过它的轮次给出行为([决策](../../../.agents/notes/implemented/simplification/2026-07-31-drop-user-message-edit-stub.md))。
 - **others 工具行的闪光图标是手绘近似版本**:无法在本地导出设计字形的矢量几何;等到存在精确导出后再将其提升到 ui-primitives。
 - **审批面板的「始终允许此类」暂缓**:持久授权需要授权存储设计;今天只能回答允许一次/拒绝。
 - **TodoPanel 将过长条目截成单行省略号**:figma 条没有换行或展开入口,完整文本无法在行内读完。

+ 7 - 10
packages/client/ui-conversation/src/client/chat/AssistantMarkdown.tsx

@@ -4,10 +4,10 @@
 // view groups them into tool rows through its keyed toolview slot (figma
 // step-summary flow). Shared by finalized nodes and the streaming partial;
 // the turn-level loading dots live in the chat view's tail, not here.
-// Finalized content (text) nodes append IconActions once streaming ends
-// (`time` is omitted for mid-turn narration); their branch action is enabled
-// only when the node is also the completed turn's transcript tail. Think /
-// tool-head-only nodes stay chrome-free.
+// Finalized content (text) nodes append IconActions once their turn ends
+// (`time` is omitted for mid-turn narration and while the turn still runs);
+// their branch action is enabled only when the node is also the completed
+// turn's transcript tail. Think / tool-head-only nodes stay chrome-free.
 
 import { memo, useMemo } from 'react'
 import type { AssistantBlock } from '@deepseek-ai/dsh-client-runtime/client'
@@ -15,6 +15,7 @@ import {
   IconThinkOutline14, JsonBlock, MarkdownText,
 } from '@deepseek-ai/dsh-client-ui-primitives'
 import type { ChatViewSlotProps } from '../contract/slots.ts'
+import { hasContentText } from './chat-flow.ts'
 import { MessageIconActions } from './MessageIconActions.tsx'
 import { ToolRow } from './ToolRow.tsx'
 import css from './AssistantMarkdown.module.css'
@@ -25,7 +26,8 @@ export interface AssistantMarkdownProps {
   /** Frozen partial of an aborted turn: rendered with a stopped marker. */
   interrupted?: boolean | undefined
   /** Unix epoch ms for the IconActions clock; omitted while streaming or when
-   *  the parent withholds chrome (mid-turn content assistants). */
+   *  the parent withholds chrome (mid-turn content assistants and every node
+   *  of a turn that has not ended). */
   time?: number | undefined
   /** Turn wall time in ms for the IconActions run-time label; omitted when the
    *  turn's triggering input is outside the loaded window. */
@@ -65,11 +67,6 @@ function copyText(blocks: readonly AssistantBlock[]): string {
   return parts.join('')
 }
 
-/** True when the node has model-visible text content worth chrome under. */
-function hasContentText(blocks: readonly AssistantBlock[]): boolean {
-  return blocks.some(block => block.kind === 'text' && block.text.trim() !== '')
-}
-
 /** Reasoning block as the Think variant summary row (figma 39:28304). */
 function ThinkRow({ text, running, t }: { text: string; running: boolean; t: AssistantMarkdownProps['t'] }) {
   return (

+ 6 - 7
packages/client/ui-conversation/src/client/chat/ChatView.tsx

@@ -30,7 +30,7 @@ import type {
 import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
 import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'
 import type { ChatViewSlotProps } from '../contract/slots.ts'
-import { assistantActionsSeqs, deriveChatFlow, messageBranchSeqs, runningTurnStartTime, type ChatFlowItem } from './chat-flow.ts'
+import { assistantActionsSeqs, assistantBranchSeqs, deriveChatFlow, runningTurnStartTime, type ChatFlowItem } from './chat-flow.ts'
 import { AssistantMarkdown } from './AssistantMarkdown.tsx'
 import { GenericCommandCard } from './GenericCommandCard.tsx'
 import { GenericToolCard } from './GenericToolCard.tsx'
@@ -358,10 +358,11 @@ export function ChatView({
     [inbox],
   )
   const activeRetry = useMemo(() => activeRetrySeq(nodes, running), [nodes, running])
-  // Only the last content assistant of each turn owns IconActions; mid-turn
-  // text (before tools) omits `time` so AssistantMarkdown stays chrome-free.
-  const actionSeqs = useMemo(() => assistantActionsSeqs(nodes), [nodes])
-  const branchSeqs = useMemo(() => messageBranchSeqs(nodes, turnEnds), [nodes, turnEnds])
+  // Only the last content assistant of each completed turn owns IconActions;
+  // mid-turn text and every node of a running turn omit `time`, so
+  // AssistantMarkdown stays chrome-free until the answer settles.
+  const actionSeqs = useMemo(() => assistantActionsSeqs(nodes, turnEnds), [nodes, turnEnds])
+  const branchSeqs = useMemo(() => assistantBranchSeqs(nodes, turnEnds), [nodes, turnEnds])
   const runningTurnStart = useMemo(() => runningTurnStartTime(turnTimings), [turnTimings])
   const turnMetrics = useMemo(() => deriveTurnMetrics(nodes), [nodes])
 
@@ -631,8 +632,6 @@ export function ChatView({
       <MessageItem
         node={node}
         retryActive={node.kind === 'model-retry' && node.seq === activeRetry}
-        onFork={forkAt}
-        forkUnavailable={!branchSeqs.has(node.seq)}
         t={t}
       />
     )

+ 3 - 5
packages/client/ui-conversation/src/client/chat/MessageIconActions.tsx

@@ -27,8 +27,6 @@ export interface MessageIconActionsProps {
   onBranch?: (() => void) | undefined
   /** The message is not a completed transcript tail, so branch stays visible but unavailable. */
   branchUnavailable?: boolean | undefined
-  /** Additional branch visibility gate for transient message chrome; defaults to true. */
-  showBranch?: boolean | undefined
   /** Parent layout class composed onto the actions row. */
   className?: string | undefined
   /** The owning view's locale seat, passed down as a plain prop. */
@@ -41,7 +39,7 @@ export interface MessageIconActionsProps {
  * @returns The actions row element.
  */
 export function MessageIconActions({
-  text, time, runMs, ttftMs, tokensPerSecond, clock, onBranch, branchUnavailable = false, showBranch = true, className, t,
+  text, time, runMs, ttftMs, tokensPerSecond, clock, onBranch, branchUnavailable = false, className, t,
 }: MessageIconActionsProps) {
   const day = useCalendarDay()
   const reasonId = useId()
@@ -111,7 +109,7 @@ export function MessageIconActions({
           {copied ? <IconCheckOutline16 /> : <IconCopyOutline16 />}
         </button>
       </Tooltip>
-      {showBranch && onBranch !== undefined && (
+      {onBranch !== undefined && (
         <Tooltip label={branchUnavailable ? t('message.branchUnavailable') : t('message.branch')} side="bottom">
           {/* Native disabled buttons do not deliver the hover/focus events Tooltip needs. */}
           <button
@@ -127,7 +125,7 @@ export function MessageIconActions({
           </button>
         </Tooltip>
       )}
-      {showBranch && onBranch !== undefined && branchUnavailable && (
+      {onBranch !== undefined && branchUnavailable && (
         <span id={reasonId} className={css.visuallyHidden}>{t('message.branchUnavailable')}</span>
       )}
       {clock === 'end' ? clockEl : null}

+ 5 - 12
packages/client/ui-conversation/src/client/chat/MessageItem.tsx

@@ -1,8 +1,8 @@
 // MessageItem: simple chat nodes — user and consumed-steering bubbles
-// (right-aligned, with clock + copy / branch IconActions; steering adds the
-// interjection caption that names it), pending steering (caption + copy only),
-// context injection, compaction marker, retry disclosure, and unknown-surface
-// JSON rows.
+// (right-aligned, with clock + copy IconActions; steering adds the
+// interjection caption that names it; branch lives only under assistant
+// answers), pending steering (caption + copy only), context injection,
+// compaction marker, retry disclosure, and unknown-surface JSON rows.
 
 import { memo, useEffect, useMemo, useState } from 'react'
 import type { ReactNode } from 'react'
@@ -27,10 +27,6 @@ export interface MessageItemProps {
     | TurnErrorNode
     | UnknownSurfaceNode
   retryActive?: boolean
-  /** Fork through this message's completed turn when eligible. */
-  onFork?: (seq: number) => void
-  /** The message is not the transcript tail of a completed turn. */
-  forkUnavailable?: boolean
   /** The owning view's locale seat, passed down as a plain prop. */
   t: ChatViewSlotProps['t']
 }
@@ -217,7 +213,6 @@ export function PendingSteeringBubble({ content, t }: {
         <MessageIconActions
           text={text}
           clock="start"
-          showBranch={false}
           className={css.actions}
           t={t}
         />
@@ -227,7 +222,7 @@ export function PendingSteeringBubble({ content, t }: {
 }
 
 export const MessageItem = memo(function MessageItem({
-  node, retryActive = false, onFork, forkUnavailable = false, t,
+  node, retryActive = false, t,
 }: MessageItemProps) {
   const truncated = (total: number): string => t('json.truncated', { total })
   switch (node.kind) {
@@ -243,8 +238,6 @@ export const MessageItem = memo(function MessageItem({
               text={text}
               time={node.time}
               clock="start"
-              onBranch={onFork === undefined ? undefined : () => { onFork(node.seq) }}
-              branchUnavailable={forkUnavailable}
               className={css.actions}
               t={t}
             />

+ 27 - 13
packages/client/ui-conversation/src/client/chat/chat-flow.ts

@@ -17,8 +17,14 @@ export type ChatFlowItem =
   | { kind: 'node'; key: string; node: ConversationNode }
   | { kind: 'tool-group'; key: string; results: readonly ToolResultNode[] }
 
-/** True when the node has model-visible text content worth IconActions chrome. */
-function hasContentText(blocks: readonly AssistantBlock[]): boolean {
+/**
+ * True when the node has model-visible text content worth IconActions chrome.
+ * Shared with {@link AssistantMarkdown}'s mount gate so ownership and mounting
+ * cannot diverge.
+ * @param blocks - assistant blocks of one finalized node.
+ * @returns Whether any text block carries non-blank content.
+ */
+export function hasContentText(blocks: readonly AssistantBlock[]): boolean {
   return blocks.some(block => block.kind === 'text' && block.text.trim() !== '')
 }
 
@@ -34,14 +40,20 @@ function rendersNothing(node: ConversationNode): boolean {
 
 /**
  * Seq set of assistants that own IconActions: the last content-text assistant
- * in each turn. Mid-turn narration (text before tools) stays chrome-free.
+ * of each *completed* turn. A turn without a `turn/end` in the window is still
+ * producing steps, so its latest narration is not the settled answer and owns
+ * nothing; mid-turn narration of a completed turn stays chrome-free too.
  * @param nodes - snapshot nodes (surface order).
+ * @param turnEnds - completed turn boundaries retained from the event window.
  * @returns Seq values ChatView may pass as `time` into AssistantMarkdown.
  */
-export function assistantActionsSeqs(nodes: readonly ConversationNode[]): ReadonlySet<number> {
+export function assistantActionsSeqs(
+  nodes: readonly ConversationNode[],
+  turnEnds: ReadonlyMap<number, number>,
+): ReadonlySet<number> {
   const lastByTurn = new Map<number, number>()
   for (const node of nodes) {
-    if (node.kind !== 'assistant' || !hasContentText(node.blocks)) continue
+    if (node.kind !== 'assistant' || !turnEnds.has(node.turn) || !hasContentText(node.blocks)) continue
     lastByTurn.set(node.turn, node.seq)
   }
   return new Set(lastByTurn.values())
@@ -63,15 +75,18 @@ export function runningTurnStartTime(
 }
 
 /**
- * Seq set of message rows that may fork: the last transcript node of a
- * completed turn, when that node owns message chrome. A later tool, reasoning,
- * error, or other transcript node leaves the earlier message's branch action
- * unavailable because the Host would include the whole turn.
+ * Seq set of assistant answers that may fork: the completed turn's transcript
+ * tail, when that tail is the turn's own content-text assistant. A later tool,
+ * reasoning, error, or other transcript node leaves the answer's branch action
+ * unavailable because the Host would include the whole turn. User and steering
+ * bubbles carry no branch action at all: a fork at their seq cuts at the same
+ * `turn/end` as the answer's, so the affordance lives only under the settled
+ * answer.
  * @param nodes - snapshot nodes in event order.
  * @param turnEnds - completed turn boundaries retained from the event window.
- * @returns Message seq values whose visible position matches the fork boundary.
+ * @returns Assistant seq values whose visible position matches the fork boundary.
  */
-export function messageBranchSeqs(
+export function assistantBranchSeqs(
   nodes: readonly ConversationNode[],
   turnEnds: ReadonlyMap<number, number>,
 ): ReadonlySet<number> {
@@ -86,8 +101,7 @@ export function messageBranchSeqs(
       tail = candidate
       nodeIndex++
     }
-    if (tail?.kind === 'user' || tail?.kind === 'steering'
-      || (tail?.kind === 'assistant' && tail.turn === turn && hasContentText(tail.blocks))) {
+    if (tail?.kind === 'assistant' && tail.turn === turn && hasContentText(tail.blocks)) {
       result.add(tail.seq)
     }
   }

+ 29 - 35
packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx

@@ -36,7 +36,7 @@ afterEach(() => {
 const t: MessageItemProps['t'] = makeTranslate(zh, commonZh)
 
 describe('MessageItem arms', () => {
-  it('user bubbles expose clock / copy / branch and no edit; copy writes the text', () => {
+  it('user bubbles expose clock / copy and neither branch nor edit; copy writes the text', () => {
     const writeText = vi.fn().mockResolvedValue(undefined)
     Object.defineProperty(navigator, 'clipboard', {
       configurable: true,
@@ -45,24 +45,20 @@ describe('MessageItem arms', () => {
     // Same-day clock: construct "today at 14:24" so the label stays `HH:mm`.
     const now = new Date()
     const time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 24).getTime()
-    const onFork = vi.fn()
     render(
       <MessageItem t={t} node={{
         kind: 'user', seq: 1, time,
         content: [{ type: 'text', text: 'hello bubble' }] as never,
         source: null,
       }}
-      onFork={onFork}
       />,
     )
     expect(screen.getByText('14:24')).toBeTruthy()
     expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
-    expect(screen.getByRole('button', { name: '在新对话中分支' })).toBeTruthy()
+    expect(screen.queryByRole('button', { name: '在新对话中分支' })).toBeNull()
     expect(screen.queryByRole('button', { name: '编辑' })).toBeNull()
     fireEvent.click(screen.getByRole('button', { name: '复制' }))
     expect(writeText).toHaveBeenCalledWith('hello bubble')
-    fireEvent.click(screen.getByRole('button', { name: '在新对话中分支' }))
-    expect(onFork).toHaveBeenCalledWith(1)
   })
 
   it('user copy falls back to execCommand when clipboard.writeText is unavailable', () => {
@@ -87,30 +83,6 @@ describe('MessageItem arms', () => {
     expect(exec).toHaveBeenCalledWith('copy')
   })
 
-  it('keeps an unavailable branch focusable and explains why without sending a fork', () => {
-    const onFork = vi.fn()
-    render(
-      <MessageItem t={t} node={{
-        kind: 'user', seq: 1, time: 1_000,
-        content: [{ type: 'text', text: 'open turn' }] as never,
-        source: null,
-      }}
-      onFork={onFork}
-      forkUnavailable
-      />,
-    )
-    const branch = screen.getByRole('button', { name: '在新对话中分支' }) as HTMLButtonElement
-    expect(branch.disabled).toBe(false)
-    expect(branch.getAttribute('aria-disabled')).toBe('true')
-    const reasonId = branch.getAttribute('aria-describedby')
-    expect(reasonId).not.toBeNull()
-    expect(document.getElementById(reasonId!)?.textContent).toBe('仅可从已完成轮次的最后一条消息分支')
-    fireEvent.click(branch)
-    expect(onFork).not.toHaveBeenCalled()
-    fireEvent.focus(branch)
-    expect(screen.getByRole('tooltip').textContent).toBe('仅可从已完成轮次的最后一条消息分支')
-  })
-
   it('user copy never claims success when the host rejects the write', async () => {
     Object.defineProperty(navigator, 'clipboard', {
       configurable: true,
@@ -212,19 +184,17 @@ describe('MessageItem arms', () => {
     expect(vi.getTimerCount()).toBe(0)
   })
 
-  it('consumed steering is captioned as an interjection and keeps copy and branch actions', () => {
+  it('consumed steering is captioned as an interjection and keeps copy without branch', () => {
     const writeText = vi.fn().mockResolvedValue(undefined)
     Object.defineProperty(navigator, 'clipboard', {
       configurable: true,
       value: { writeText },
     })
-    const fork = vi.fn()
     const view = render(
       <MessageItem t={t} node={{
         kind: 'steering', messageId: 'steer-message', seq: 2, time: 1_000, turn: 1, source: null,
         content: [{ type: 'text', text: 'steer!' }, { type: 'image', data: 'x' }] as never,
       } as never}
-      onFork={fork}
       />,
     )
     expect(view.getByText('插话')).toBeTruthy()
@@ -232,8 +202,7 @@ describe('MessageItem arms', () => {
     expect(view.getByText(/附加内容块/)).toBeTruthy()
     fireEvent.click(view.getByRole('button', { name: '复制' }))
     expect(writeText).toHaveBeenCalledWith('steer!')
-    fireEvent.click(view.getByRole('button', { name: '在新对话中分支' }))
-    expect(fork).toHaveBeenCalledWith(2)
+    expect(view.queryByRole('button', { name: '在新对话中分支' })).toBeNull()
   })
 
   it('context uses the Tool calls disclosure chrome and keeps its body collapsed by default', () => {
@@ -1002,6 +971,31 @@ describe('small branch tails', () => {
     expect(streaming.queryByText('14:24')).toBeNull()
   })
 
+  it('keeps an unavailable branch focusable and explains why without sending a fork', () => {
+    const onFork = vi.fn()
+    render(
+      <AssistantMarkdown
+        t={t}
+        blocks={[{ kind: 'text', text: 'answer before a trailing tool row' }]}
+        streaming={false}
+        time={1_000}
+        seq={1}
+        onFork={onFork}
+        forkUnavailable
+      />,
+    )
+    const branch = screen.getByRole('button', { name: '在新对话中分支' }) as HTMLButtonElement
+    expect(branch.disabled).toBe(false)
+    expect(branch.getAttribute('aria-disabled')).toBe('true')
+    const reasonId = branch.getAttribute('aria-describedby')
+    expect(reasonId).not.toBeNull()
+    expect(document.getElementById(reasonId!)?.textContent).toBe('仅可从已完成轮次的最后一条消息分支')
+    fireEvent.click(branch)
+    expect(onFork).not.toHaveBeenCalled()
+    fireEvent.focus(branch)
+    expect(screen.getByRole('tooltip').textContent).toBe('仅可从已完成轮次的最后一条消息分支')
+  })
+
   it('StatsLine omits the cache-hit segment when no input accounting exists at all', () => {
     // Cache hit is null only when all three prompt buckets are zero (pure
     // output accounting) — any billed input makes it a real 0%.

+ 55 - 26
packages/client/ui-conversation/tests/chat-view.spec.tsx

@@ -20,7 +20,7 @@ import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts
 import { createChatStore } from '../src/client/stores.ts'
 import { ChatView } from '../src/client/chat/ChatView.tsx'
 import { zh } from '../src/client/locales.ts'
-import { assistantActionsSeqs, deriveChatFlow, flowKeys, messageBranchSeqs, runningTurnStartTime } from '../src/client/chat/chat-flow.ts'
+import { assistantActionsSeqs, assistantBranchSeqs, deriveChatFlow, flowKeys, runningTurnStartTime } from '../src/client/chat/chat-flow.ts'
 import { formatRunDuration } from '../src/client/chat/message-chrome.ts'
 
 afterEach(() => {
@@ -225,12 +225,12 @@ describe('chat-flow derivation', () => {
     expect(flowKeys(deriveChatFlow([toolResult(3, 'a'), assistant(4, 'found'), toolResult(5, 'b')]))).toBe('g3|n4|g5')
   })
 
-  it('assistantActionsSeqs keeps only the last content assistant per turn', () => {
+  it('assistantActionsSeqs keeps only the last content assistant per completed turn', () => {
     const thinkOnly: AssistantMessageNode = {
       kind: 'assistant', seq: 3, time: 3_000, turn: 1, step: 2,
       blocks: [{ kind: 'reasoning', text: 'planning' }],
     }
-    const seqs = assistantActionsSeqs([
+    const nodes: ConversationNode[] = [
       user(1, 'hi'),
       assistant(2, 'looking', 1),
       thinkOnly,
@@ -238,8 +238,11 @@ describe('chat-flow derivation', () => {
       assistant(5, 'done', 1),
       user(6, 'again'),
       assistant(7, 'second turn', 2),
-    ])
-    expect([...seqs].sort((a, b) => a - b)).toEqual([5, 7])
+    ]
+    expect([...assistantActionsSeqs(nodes, new Map([[1, 5], [2, 7]]))].sort((a, b) => a - b)).toEqual([5, 7])
+    // Turn 2 is still producing steps: its latest narration owns nothing, and
+    // the settled turn 1 keeps its seat.
+    expect([...assistantActionsSeqs(nodes, new Map([[1, 5]]))]).toEqual([5])
   })
 
   it('runningTurnStartTime selects the latest turn/start without a turn/end', () => {
@@ -261,7 +264,7 @@ describe('chat-flow derivation', () => {
     expect(formatRunDuration(125_000, t)).toBe('2分05秒')
   })
 
-  it('messageBranchSeqs keeps only message rows at completed transcript tails', () => {
+  it('assistantBranchSeqs keeps only content-assistant tails; user/steering tails own no branch', () => {
     const interruptedThink: AssistantMessageNode = {
       kind: 'assistant', seq: 4.1, time: 4_100, turn: 1, step: 2,
       blocks: [{ kind: 'reasoning', text: 'bad path' }], interrupted: true,
@@ -276,8 +279,8 @@ describe('chat-flow derivation', () => {
       user(10, 'user-only tail'),
       user(13, 'steering tail'),
     ]
-    const seqs = messageBranchSeqs(nodes, new Map([[1, 5], [2, 8], [3, 11], [4, 14]]))
-    expect([...seqs]).toEqual([7, 10, 13])
+    const seqs = assistantBranchSeqs(nodes, new Map([[1, 5], [2, 8], [3, 11], [4, 14]]))
+    expect([...seqs]).toEqual([7])
   })
 })
 
@@ -401,21 +404,24 @@ describe('ChatView', () => {
     expect(view.getAllByText('interrupt now')).toHaveLength(1)
     expect(view.container.querySelector('[data-pending-steering]')).toBeNull()
     expect(view.getAllByText('插话')).toHaveLength(1)
-    expect(view.getAllByRole('button', { name: '复制' })).toHaveLength(2)
+    // Only the durable steering bubble: the turn is still running, so its
+    // assistant narration owns no footer yet, and a steering bubble never
+    // carries a branch action.
+    expect(view.getAllByRole('button', { name: '复制' })).toHaveLength(1)
     const durableBubble = view.getByText('interrupt now').closest('[class*="userRow"]') as HTMLElement
-    const unavailable = within(durableBubble).getByRole('button', { name: '在新对话中分支' })
-    expect(unavailable.getAttribute('aria-disabled')).toBe('true')
-    fireEvent.click(unavailable)
-    expect(h.forkAt).not.toHaveBeenCalled()
+    expect(within(durableBubble).queryByRole('button', { name: '在新对话中分支' })).toBeNull()
 
     act(() => {
       h.set({ running: false, turnEnds: new Map([[1, 3]]) })
     })
+    // The completed turn's transcript tail is the steering bubble, not the
+    // narration, so the assistant's branch action stays unavailable and the
+    // steering bubble still offers none.
     const branchButtons = view.getAllByRole('button', { name: '在新对话中分支' })
-    expect(branchButtons).toHaveLength(2)
-    expect(branchButtons.map(button => button.getAttribute('aria-disabled'))).toEqual(['true', null])
-    fireEvent.click(branchButtons[1]!)
-    expect(h.forkAt).toHaveBeenCalledWith(2)
+    expect(branchButtons).toHaveLength(1)
+    expect(branchButtons[0]!.getAttribute('aria-disabled')).toBe('true')
+    fireEvent.click(branchButtons[0]!)
+    expect(h.forkAt).not.toHaveBeenCalled()
   })
 
   it('keeps a later pending occurrence visible when it reuses a durable MessageId', () => {
@@ -518,11 +524,35 @@ describe('ChatView', () => {
       turnEnds: new Map([[1, 4], [2, 6]]),
     })
     const view = render(<h.ChatView {...h.props} />)
-    // Every message footer keeps branch visible; only completed assistant tails enable it.
+    // Branch renders only under assistant answers; user bubbles keep copy alone.
     expect(view.getAllByRole('button', { name: '复制' })).toHaveLength(4)
     const branchButtons = view.getAllByRole('button', { name: '在新对话中分支' })
-    expect(branchButtons).toHaveLength(4)
-    expect(branchButtons.map(button => button.getAttribute('aria-disabled'))).toEqual(['true', null, 'true', null])
+    expect(branchButtons).toHaveLength(2)
+    expect(branchButtons.map(button => button.getAttribute('aria-disabled'))).toEqual([null, null])
+  })
+
+  it('withholds assistant IconActions while the turn is still running', () => {
+    const h = makeHarness({
+      running: true,
+      runningCalls: [runningCall('a')],
+      nodes: [
+        user(1, 'first'),
+        assistant(2, 'previous answer', 1),
+        user(4, 'second'),
+        assistant(5, 'mid-turn text', 2),
+      ],
+      // Boundary seqs follow the log: a turn/end is strictly after its own nodes.
+      turnEnds: new Map([[1, 3]]),
+    })
+    const view = render(<h.ChatView {...h.props} />)
+    // 2 user + the settled turn-1 tail, which keeps its seat while a later
+    // turn runs; turn 2's narration stays chrome-free while its tool runs, so
+    // the footer never appears and then moves.
+    expect(view.getAllByRole('button', { name: '复制' })).toHaveLength(3)
+    expect(view.getByText('mid-turn text')).toBeTruthy()
+    // turn/end lands: the same node becomes the settled answer and takes the seat.
+    act(() => { h.set({ running: false, runningCalls: [], turnEnds: new Map([[1, 3], [2, 6]]) }) })
+    expect(view.getAllByRole('button', { name: '复制' })).toHaveLength(4)
   })
 
   it('the actions-owning assistant footer shows the turn run time', () => {
@@ -606,11 +636,11 @@ describe('ChatView', () => {
       turnEnds: new Map([[1, 3]]),
     })
     const view = render(<h.ChatView {...h.props} />)
+    // The user bubble offers no branch; the settled answer's is live.
     const buttons = view.getAllByRole('button', { name: '在新对话中分支' })
-    expect(buttons).toHaveLength(2)
-    expect(buttons.map(button => button.getAttribute('aria-disabled'))).toEqual(['true', null])
+    expect(buttons).toHaveLength(1)
+    expect(buttons[0]!.getAttribute('aria-disabled')).toBeNull()
     fireEvent.click(buttons[0]!)
-    fireEvent.click(buttons[1]!)
     expect(h.forkAt.mock.calls).toEqual([[2]])
   })
 
@@ -626,10 +656,9 @@ describe('ChatView', () => {
     const view = render(<h.ChatView {...h.props} />)
     expect(view.getAllByRole('button', { name: '复制' })).toHaveLength(2)
     const buttons = view.getAllByRole('button', { name: '在新对话中分支' })
-    expect(buttons).toHaveLength(2)
-    expect(buttons.every(button => button.getAttribute('aria-disabled') === 'true')).toBe(true)
+    expect(buttons).toHaveLength(1)
+    expect(buttons[0]!.getAttribute('aria-disabled')).toBe('true')
     fireEvent.click(buttons[0]!)
-    fireEvent.click(buttons[1]!)
     expect(h.forkAt).not.toHaveBeenCalled()
   })
 

+ 2 - 2
packages/client/ui-models/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/client/ui-models/README.md
-README.md: b55914197e472edec8a8b6d4d3e02036d1697728
-README.zh.md: ca93c3d5a2a85fffb22707f8389f1e979468e2ec
+README.md: 9d1fbdddd1ad9ec4c073dd1c0ca4ac7124c1b876
+README.zh.md: ff740bc6d1096901cbcc33772aff09deafeb53a4

Разница между файлами не показана из-за своего большого размера
+ 0 - 1
packages/client/ui-models/README.md


Разница между файлами не показана из-за своего большого размера
+ 0 - 1
packages/client/ui-models/README.zh.md


+ 31 - 0
packages/client/ui-models/src/client/ModelsSection.module.css

@@ -38,6 +38,13 @@
   color: var(--dsw-alias-state-warn-label);
 }
 
+.savedNotice {
+  margin: 0;
+  font-size: 12px;
+  line-height: 18px;
+  color: var(--dsw-alias-state-success-primary);
+}
+
 .rows {
   list-style: none;
   /* Extra air between the title/intro block and the first provider card. */
@@ -65,6 +72,13 @@
   gap: 10px;
 }
 
+.rowIdentity {
+  display: inline-flex;
+  align-items: center;
+  gap: 6px;
+  min-width: 0;
+}
+
 .rowName {
   font-size: 14px;
   line-height: 22px;
@@ -72,6 +86,23 @@
   color: var(--dsw-alias-label-primary);
 }
 
+.credentialDot {
+  box-sizing: border-box;
+  display: inline-block;
+  flex: none;
+  width: 8px;
+  height: 8px;
+  border-radius: 50%;
+}
+
+.credentialDotConfigured {
+  background: var(--dsw-alias-state-success-primary);
+}
+
+.credentialDotMissing {
+  background: var(--dsw-alias-state-error-primary);
+}
+
 .rowActions {
   display: inline-flex;
   align-items: center;

+ 166 - 55
packages/client/ui-models/src/client/ModelsSection.tsx

@@ -1,10 +1,11 @@
 /**
  * Models settings section: the provider rows joined from the configurable
  * directory, settings namespaces, and credential states, with one editor
- * card at a time. A whole-section provider without a configured key (the
- * unconfigured DeepSeek posture) renders as its open setup card instead of a
- * row; the add flow is a card carrying the dormant-provider select. Every
- * mutation writes through the wire, while a provider removal first requires
+ * card at a time. Rows expose only confirmed API-key state through accessible
+ * solid configured or missing dots. A whole-section provider without a
+ * configured key (the unconfigured DeepSeek posture) renders as its open setup
+ * card instead of a row; the add flow is a card carrying the dormant-provider
+ * select. Every mutation writes through the wire, while a provider removal first requires
  * confirmation; the page re-renders from pushed invalidations or the
  * post-apply reload.
  */
@@ -15,9 +16,9 @@ import type { IApiClient } from '@deepseek-ai/dsh-client-connection/client'
 import { Button, IconPlusOutline16, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
 import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-web-react'
 import { CustomProviderCard } from './CustomProviderCard.tsx'
-import { messageOf, protocolChoices } from './store.ts'
+import { deriveKeyRef, messageOf, protocolChoices } from './store.ts'
 import type { ModelsSettingsState, ModelsSettingsStore, ProviderRow } from './store.ts'
-import { ProviderEditor } from './ProviderEditor.tsx'
+import { ProviderEditor, type ProviderEditorProps } from './ProviderEditor.tsx'
 import type { en } from './locales.ts'
 import styles from './ModelsSection.module.css'
 
@@ -39,42 +40,73 @@ export interface ModelsSectionInjected {
  */
 export type ModelsSectionProps = Partial<ModelsSectionInjected>
 
-/** The editor target: an existing row or a dormant directory entry. */
-interface EditorTarget {
+/** Provider identity shared by row actions and confirmation copy. */
+export interface ProviderIdentity {
+  /** Stable provider route id. */
   provider: string
+  /** Human-facing provider name. */
   displayName: string
+}
+
+/** One existing row or dormant directory entry addressed by an editor action. */
+interface EditorTarget extends ProviderIdentity {
   settingsNs: string
   settingsPath: readonly string[]
+  /** Writable credential identified under this page's conventional reference. */
+  credentialRef?: string
+}
+
+/** Values that vary around the shared provider-editor rendering. */
+interface ProviderEditorRenderProps extends Pick<
+  ProviderEditorProps,
+  'namespace' | 'api' | 't' | 'readOnly' | 'onClose'
+> {
+  target: EditorTarget
+}
+
+/** Render an editor for either the setup posture or an expanded provider row. */
+function renderProviderEditor({ target, ...props }: ProviderEditorRenderProps): ReactNode {
+  return (
+    <ProviderEditor
+      provider={target.provider}
+      displayName={target.displayName}
+      settingsPath={target.settingsPath}
+      {...props}
+    />
+  )
 }
 
 /**
- * Remove one user-added provider profile by unsetting its path in the stored
- * user section, then reload. The removal names the profile rather than
- * rebuilding the section: this page only ever holds the redacted descriptor,
- * so a rebuilt section would drop every literal secret stored elsewhere in
- * the namespace along with the profile being removed.
- * @param api - settings wire face.
+ * Remove one user-added provider and its page-managed credential. Credential
+ * removal comes first so a second-step failure leaves the provider row visible
+ * and the whole operation safely retryable; both unsets are idempotent.
+ * The settings removal names the profile rather than rebuilding its redacted
+ * namespace, which would drop literal secrets stored elsewhere.
+ * @param api - settings and credential wire faces.
  * @param controller - the page store to refresh.
- * @param target - the provider's settings address.
+ * @param target - the provider's settings address and optional managed credential.
  * @returns the failure message, or undefined once the write and reload landed.
  */
 export async function removeProviderProfile(
-  api: Pick<IApiClient, 'settings'>,
+  api: Pick<IApiClient, 'settings' | 'credentials'>,
   controller: ModelsSettingsStore,
-  target: { settingsNs: string; settingsPath: readonly string[] },
+  target: { settingsNs: string; settingsPath: readonly string[]; credentialRef?: string },
 ): Promise<string | undefined> {
-  let response
   try {
-    response = await api.settings.mutate({
+    if (target.credentialRef !== undefined) {
+      const credential = await api.credentials.unset({ ref: target.credentialRef })
+      if (!credential.result.ok) return credential.result.error.message
+    }
+    const response = await api.settings.mutate({
       ns: target.settingsNs,
       ops: [{ op: 'unset', path: [...target.settingsPath] }],
     })
+    if (!response.result.ok) return response.result.error.message
   } catch (error) {
     // The transport rejected rather than answering; the caller must be able
-    // to say so instead of the row silently staying put.
+    // to retry the idempotent operation instead of the row silently staying.
     return messageOf(error)
   }
-  if (!response.result.ok) return response.result.error.message
   await controller.load()
   return undefined
 }
@@ -93,14 +125,33 @@ export function needsSetup(row: ProviderRow): boolean {
 }
 
 function targetOf(row: ProviderRow): EditorTarget {
+  const managedRef = deriveKeyRef(row.entry.provider)
+  const credentialRef = row.apiKeyEnv === managedRef
+    && row.credential?.configured === true
+    && row.credential.writable
+    ? managedRef
+    : undefined
   return {
     provider: row.entry.provider,
     displayName: row.entry.displayName,
     settingsNs: row.entry.settingsNs,
     settingsPath: row.entry.settingsPath,
+    ...credentialRef === undefined ? {} : { credentialRef },
   }
 }
 
+/** Stable visible and accessible identity for one provider target. */
+export function providerTargetLabel(target: ProviderIdentity): string {
+  return target.provider === target.displayName
+    ? target.provider
+    : `${target.displayName} (${target.provider})`
+}
+
+/** Replace the one provider placeholder in localized destructive-action copy. */
+export function providerCopy(template: string, target: ProviderIdentity): string {
+  return template.replace('{provider}', () => providerTargetLabel(target))
+}
+
 /**
  * Render the Models section content column.
  * @param props - slot-delivered injected dependencies.
@@ -119,28 +170,35 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
   const [adding, setAdding] = useState(false)
   const [deleteTarget, setDeleteTarget] = useState<EditorTarget | undefined>(undefined)
   const [deleting, setDeleting] = useState(false)
+  const [deleteFailure, setDeleteFailure] = useState<string | undefined>(undefined)
+  const [savedTarget, setSavedTarget] = useState<ProviderIdentity | undefined>(undefined)
   const [declaring, setDeclaring] = useState(false)
 
-  const closeEditor = (changed: boolean): void => {
+  const closeEditor = (changed: boolean, target: ProviderIdentity): void => {
     setEditing(undefined)
     setAdding(false)
     setDeclaring(false)
-    if (changed) void controller.load()
+    if (changed) {
+      setSavedTarget(target)
+      void controller.load()
+    }
   }
 
   const closeDelete = (): void => {
     if (deleting) return
     setDeleteTarget(undefined)
+    setDeleteFailure(undefined)
   }
 
   const confirmDelete = (): void => {
     /* v8 ignore next -- the action only renders with a target and is disabled while a deletion is pending */
     if (deleteTarget === undefined || deleting) return
     setDeleting(true)
+    setDeleteFailure(undefined)
     void removeProviderProfile(api, controller, deleteTarget)
       .then((failure) => {
         if (failure !== undefined) {
-          controller.fail(failure)
+          setDeleteFailure(failure)
           return
         }
         setDeleteTarget(undefined)
@@ -176,6 +234,13 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
       <h2 className={styles['title']}>{t('title')}</h2>
       <p className={styles['intro']}>{t('intro')}</p>
       {!state.writable && state.status === 'ready' ? <p className={styles['notice']}>{t('readOnly')}</p> : null}
+      {savedTarget === undefined
+        ? null
+        : (
+          <p className={styles['savedNotice']} role="status" aria-live="polite">
+            {providerCopy(t('savedProvider'), savedTarget)}
+          </p>
+        )}
       <ul className={styles['rows']}>
         {configured.map((row) => {
           const target = targetOf(row)
@@ -187,29 +252,54 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
             // setup card IS its presence on the page.
             return (
               <li key={row.entry.provider} className={styles['setupCard']}>
-                <ProviderEditor
-                  provider={target.provider}
-                  displayName={target.displayName}
-                  namespace={namespace}
-                  settingsPath={target.settingsPath}
-                  api={api}
-                  t={t}
-                  readOnly={!state.writable}
-                  onClose={closeEditor}
-                />
+                {renderProviderEditor({
+                  target,
+                  namespace,
+                  api,
+                  t,
+                  readOnly: !state.writable,
+                  onClose: (changed) => { closeEditor(changed, target) },
+                })}
               </li>
             )
           }
           const open = !adding && editing?.provider === row.entry.provider
+          const credentialConfigured = row.literalApiKeyConfigured || row.credential?.configured === true
+          const credentialMissing = !credentialConfigured
+            && row.apiKeyEnv !== undefined
+            && row.credential?.configured === false
           return (
             <li key={row.entry.provider} className={styles['rowCard']}>
               <div className={styles['rowHead']}>
-                <span className={styles['rowName']}>{row.entry.displayName}</span>
+                <span className={styles['rowIdentity']}>
+                  <span className={styles['rowName']}>{row.entry.displayName}</span>
+                  {credentialConfigured
+                    ? (
+                      <span
+                        className={`${styles['credentialDot']} ${styles['credentialDotConfigured']}`}
+                        role="img"
+                        aria-label={t('credentialConfigured')}
+                        title={t('credentialConfigured')}
+                      />
+                    )
+                    : credentialMissing
+                      ? (
+                        <span
+                          className={`${styles['credentialDot']} ${styles['credentialDotMissing']}`}
+                          role="img"
+                          aria-label={t('credentialMissing')}
+                          title={t('credentialMissing')}
+                        />
+                      )
+                      : null}
+                </span>
                 <span className={styles['rowActions']}>
                   <button
                     type="button"
                     className={styles['secondaryButton']}
+                    aria-label={providerCopy(t('editProvider'), target)}
                     onClick={() => {
+                      setSavedTarget(undefined)
                       // One card at a time: leaving `declaring` set would show
                       // the create card beside this editor, and closing either
                       // one discards the other's draft.
@@ -225,8 +315,13 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
                       <button
                         type="button"
                         className={styles['dangerButton']}
+                        aria-label={providerCopy(t('removeProvider'), target)}
                         disabled={!state.writable}
-                        onClick={() => { setDeleteTarget(target) }}
+                        onClick={() => {
+                          setSavedTarget(undefined)
+                          setDeleteFailure(undefined)
+                          setDeleteTarget(target)
+                        }}
                       >
                         {t('remove')}
                       </button>
@@ -235,18 +330,14 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
                 </span>
               </div>
               {open
-                ? (
-                  <ProviderEditor
-                    provider={target.provider}
-                    displayName={target.displayName}
-                    namespace={namespace}
-                    settingsPath={target.settingsPath}
-                    api={api}
-                    t={t}
-                    readOnly={!state.writable}
-                    onClose={closeEditor}
-                  />
-                )
+                ? renderProviderEditor({
+                  target,
+                  namespace,
+                  api,
+                  t,
+                  readOnly: !state.writable,
+                  onClose: (changed) => { closeEditor(changed, target) },
+                })
                 : null}
             </li>
           )
@@ -284,7 +375,7 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
                 api={api}
                 t={t}
                 readOnly={!state.writable}
-                onClose={closeEditor}
+                onClose={(changed) => { closeEditor(changed, addTarget) }}
               />
             </div>
           )
@@ -299,7 +390,10 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
                   api={api}
                   t={t}
                   readOnly={!state.writable}
-                  onClose={closeEditor}
+                  onClose={(changed) => {
+                    setDeclaring(false)
+                    if (changed) void controller.load()
+                  }}
                 />
               </div>
             )
@@ -317,6 +411,7 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
                     const first = addable[0]
                     /* v8 ignore next -- the button is disabled while nothing is addable */
                     if (first === undefined) return
+                    setSavedTarget(undefined)
                     setDeclaring(false)
                     setAdding(true)
                     setEditing(targetOf(first))
@@ -330,7 +425,12 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
                   type="button"
                   className={styles['addButton']}
                   disabled={protocols.length === 0 || !state.writable}
-                  onClick={() => { setAdding(false); setEditing(undefined); setDeclaring(true) }}
+                  onClick={() => {
+                    setSavedTarget(undefined)
+                    setAdding(false)
+                    setEditing(undefined)
+                    setDeclaring(true)
+                  }}
                 >
                   <IconPlusOutline16 size={14} />
                   {t('customAdd')}
@@ -341,9 +441,16 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
       <Modal
         open={deleteTarget !== undefined}
         onClose={closeDelete}
-        title={t('deleteTitle')}
+        title={deleteTarget === undefined ? '' : providerCopy(t('deleteTitle'), deleteTarget)}
         closeLabel={t('close')}
-        description={t('deleteDescription')}
+        description={deleteTarget === undefined
+          ? ''
+          : providerCopy(
+            deleteTarget.credentialRef === undefined
+              ? t('deleteDescription')
+              : t('deleteDescriptionWithCredential'),
+            deleteTarget,
+          )}
         className={styles['deleteDialog'] as string}
         footer={(
           <>
@@ -356,11 +463,15 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode {
               disabled={deleting}
               onClick={confirmDelete}
             >
-              {deleting ? t('deleting') : t('deleteConfirm')}
+              {deleteTarget === undefined
+                ? ''
+                : providerCopy(deleting ? t('deleting') : t('deleteConfirm'), deleteTarget)}
             </Button>
           </>
         )}
-      />
+      >
+        {deleteFailure === undefined ? null : <p className={styles['error']}>{deleteFailure}</p>}
+      </Modal>
     </div>
   )
 }

+ 33 - 16
packages/client/ui-models/src/client/ProviderEditor.tsx

@@ -3,7 +3,9 @@
  * field is a single write-only **API key** input (the page never asks for an
  * environment-variable name — a typed key stores through `credentials.set`
  * under the profile's reference, deriving `<ROUTE>_API_KEY` when the profile
- * has none, and the pi-ai profile records that derivation as `apiKeyEnv`);
+ * has none. The pi-ai profile records that derivation as `apiKeyEnv` only when
+ * a key is entered; a blank key materializes a reference-free profile for
+ * provider-native authentication);
  * the collapsed 自定义设置 area carries the per-family extras (`baseURL` for
  * both families, `reasoningEffort` for deepseek / `reasoning` for pi-ai, and
  * DeepSeek's id/name/context-window model catalog). Everything else stays
@@ -133,10 +135,13 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
   const [keyState, setKeyState] = useState<CredentialView | undefined>(undefined)
   const [busy, setBusy] = useState(false)
   const [failure, setFailure] = useState<string | undefined>(undefined)
-  // The revision this card opened at. A write carrying it is refused if
-  // anything else — another tab, an external edit of settings.yaml — moved the
-  // namespace meanwhile, instead of silently overwriting that change.
-  const [openedAt] = useState(() => namespace.revision)
+  // A settings success advances both retry baselines immediately. Keeping the
+  // derived fields in the draft prevents a pushed namespace refresh from
+  // turning them into deletions when the following credential write is retried.
+  const [committedOriginal, setCommittedOriginal] = useState<unknown>(
+    () => getPath(namespace.user, settingsPath),
+  )
+  const [expectedRevision, setExpectedRevision] = useState(() => namespace.revision)
   const root = useMemo(() => rehydrateSchema(namespace.schema), [namespace.schema])
   const node = useMemo(() => nodeAtPath(root, settingsPath), [root, settingsPath])
   const fallback = getPath(namespace.value, settingsPath)
@@ -194,11 +199,11 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
    */
   const applyOnce = async (): Promise<string | undefined> => {
     const ns = namespace.ns
-    const original = getPath(namespace.user, settingsPath)
-    // The pi-ai profile must name the reference the key stores under, so a
-    // dormant add (or a legacy profile without one) records the derivation.
+    const normalizedKey = keyDraft.trim()
+    // A pi-ai profile names the conventional reference only when this page is
+    // about to store a key. Otherwise the provider keeps its native auth path.
     const next = layout === 'pi-ai' && stringAt(draft, 'apiKeyEnv') === undefined
-      && stringAt(fallback, 'apiKeyEnv') === undefined
+      && stringAt(fallback, 'apiKeyEnv') === undefined && normalizedKey.length > 0
       ? setPath(draft, ['apiKeyEnv'], keyRef)
       : draft
     {
@@ -217,17 +222,26 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
       const sectionError = validateDraft(node, next)
       if (sectionError !== undefined) return sectionError
     }
-    const ops = pathOps(settingsPath, original, next)
+    const materializesNativeProfile = layout === 'pi-ai'
+      && fallback === undefined
+      && committedOriginal === undefined
+      && Object.keys(next).length === 0
+    const ops: SettingsPathOpView[] = materializesNativeProfile
+      ? [{ op: 'set', path: [...settingsPath], value: {} }]
+      : pathOps(settingsPath, committedOriginal, next)
     if (ops.length > 0) {
-      const response = await api.settings.mutate({ ns, ops, expectedRevision: openedAt })
+      const response = await api.settings.mutate({ ns, ops, expectedRevision })
       if (!response.result.ok) {
         return response.result.error.code === 'settings-conflict'
           ? t('conflict')
           : response.result.error.message
       }
+      setCommittedOriginal(getPath(response.result.value.user, settingsPath))
+      setExpectedRevision(response.result.value.revision)
+      setDraft(next)
     }
-    if (keyDraft.length > 0) {
-      const stored = await api.credentials.set({ ref: keyRef, value: keyDraft })
+    if (normalizedKey.length > 0) {
+      const stored = await api.credentials.set({ ref: keyRef, value: normalizedKey })
       if (!stored.result.ok) return stored.result.error.message
     }
     setKeyDraft('')
@@ -286,6 +300,11 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
     const models = modelDrafts(modelsOverridden ? customModels : inheritedModels())
     const defaultContextWindow = getPath(fallback, ['defaultContextWindow'])
     const defaultMaxTokens = getPath(fallback, ['maxTokens'])
+    const keyPlaceholder = keyLocked
+      ? t('keyEnvLocked')
+      : keyState?.configured === true
+        ? t('keyStored')
+        : family === 'pi-ai' ? t('keyPlaceholderNative') : t('keyPlaceholder')
     /** What both family editors take: the rows, whose layer owns them, and the two writes. */
     const catalogProps = {
       models,
@@ -306,9 +325,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
             type="password"
             autoComplete="off"
             value={keyDraft}
-            placeholder={keyLocked
-              ? t('keyEnvLocked')
-              : keyState?.configured === true ? t('keyStored') : t('keyPlaceholder')}
+            placeholder={keyPlaceholder}
             aria-label={t('keyInput')}
             disabled={disabled || keyLocked}
             onChange={(event) => { setKeyDraft(event.target.value) }}

+ 22 - 8
packages/client/ui-models/src/client/locales.ts

@@ -6,23 +6,30 @@ export const en = {
   title: 'Models',
   intro: 'Enter your API keys to use models from the following providers.',
   edit: 'Edit',
+  editProvider: 'Edit {provider}',
   remove: 'Delete',
-  deleteTitle: 'Delete model provider?',
-  deleteDescription: 'Deleting this model provider removes its configuration. You will not be able to use its models until you add the provider again.',
-  deleteConfirm: 'Delete provider',
-  deleting: 'Deleting provider…',
+  removeProvider: 'Delete {provider}',
+  deleteTitle: 'Delete {provider}?',
+  deleteDescription: 'Deleting {provider} removes its configuration. Any credential it uses is managed elsewhere and will be kept.',
+  deleteDescriptionWithCredential: 'Deleting {provider} removes its configuration and stored API key.',
+  deleteConfirm: 'Delete {provider}',
+  deleting: 'Deleting {provider}…',
   add: 'Add provider',
   provider: 'Provider',
   close: 'Close',
   cancel: 'Cancel',
   apply: 'Apply',
   applying: 'Applying…',
+  savedProvider: 'Saved {provider}.',
+  credentialConfigured: 'API key configured',
+  credentialMissing: 'API key missing',
   readOnly: 'The settings document is read-only in this deployment.',
   loadFailed: 'Loading the provider directory failed',
   conflict: 'Someone else changed these settings while this card was open. Close it and reopen to edit the current values.',
   retry: 'Retry',
   keyInput: 'API key',
   keyPlaceholder: 'Enter your API key',
+  keyPlaceholderNative: 'Enter an API key, or leave blank to use environment authentication',
   keyStored: 'Configured — enter a new value to replace',
   keyEnvLocked: 'Provided by the launch environment (read-only)',
   customized: 'Customized settings',
@@ -90,23 +97,30 @@ export const zh: typeof en = {
   title: '模型',
   intro: '填入各提供方的 API 密钥即可使用其模型。',
   edit: '编辑',
+  editProvider: '编辑 {provider}',
   remove: '删除',
-  deleteTitle: '删除模型提供方?',
-  deleteDescription: '删除此模型提供方会移除其配置。在重新添加前,你将无法继续使用其模型。',
-  deleteConfirm: '删除提供方',
-  deleting: '正在删除提供方…',
+  removeProvider: '删除 {provider}',
+  deleteTitle: '删除 {provider}?',
+  deleteDescription: '删除 {provider} 会移除其配置;其使用的凭证(如有)由其他位置管理,将会保留。',
+  deleteDescriptionWithCredential: '删除 {provider} 会移除其配置和存储的 API 密钥。',
+  deleteConfirm: '删除 {provider}',
+  deleting: '正在删除 {provider}…',
   add: '添加提供方',
   provider: '提供方',
   close: '关闭',
   cancel: '取消',
   apply: '保存',
   applying: '保存中…',
+  savedProvider: '已保存 {provider}。',
+  credentialConfigured: 'API 密钥已配置',
+  credentialMissing: 'API 密钥缺失',
   readOnly: '当前部署的设置文档为只读。',
   loadFailed: '加载提供方目录失败',
   conflict: '这张卡片打开期间,这些设置已被其他地方改动。请关闭后重新打开,在当前值上编辑。',
   retry: '重试',
   keyInput: 'API 密钥',
   keyPlaceholder: '输入 API 密钥',
+  keyPlaceholderNative: '输入 API 密钥,或留空使用环境认证',
   keyStored: '已配置——输入新值可替换',
   keyEnvLocked: '由启动环境提供(只读)',
   customized: '自定义设置',

+ 0 - 12
packages/client/ui-models/src/client/store.ts

@@ -125,18 +125,6 @@ export class ModelsSettingsStore {
    */
   constructor(private readonly api: Pick<IApiClient, 'settings' | 'credentials' | 'llm'>) {}
 
-  /**
-   * Surface a failure from an operation the page ran outside {@link load} —
-   * a row removal — on the same banner a load failure uses.
-   * @param message - the failure text to show.
-   */
-  fail(message: string): void {
-    this.store.update((s) => {
-      s.status = 'error'
-      s.error = message
-    })
-  }
-
   /**
    * Refresh the whole page snapshot: directory and namespaces in parallel,
    * then one batched credential describe over every referenced ref. A

+ 3 - 3
packages/client/ui-models/tests/apply.spec.ts

@@ -53,7 +53,7 @@ describe('ui-models apply', () => {
     expect(resolveSlotLabel(entry.options.label)).toBe('模型')
     const injected = (entry.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected)()
     expect(injected.t('nav')).toBe('模型')
-    expect(injected.t('deleteTitle')).toBe('删除模型提供方?')
+    expect(injected.t('deleteTitle')).toBe('删除 {provider}?')
     expect(typeof injected.controller.load).toBe('function')
     expect(typeof injected.useSnapshot).toBe('function')
     expect(injected.api).toBeDefined()
@@ -80,10 +80,10 @@ describe('ui-models apply', () => {
     b.locale.setLocale('en')
     expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('Models')
     const injected = b.slots.entries('settings.section')[0]!.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected
-    expect(injected().t('deleteTitle')).toBe('Delete model provider?')
+    expect(injected().t('deleteTitle')).toBe('Delete {provider}?')
     b.locale.setLocale('zh')
     expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('模型')
-    expect(injected().t('deleteTitle')).toBe('删除模型提供方?')
+    expect(injected().t('deleteTitle')).toBe('删除 {provider}?')
   })
 
   it('locale change while the slot is undeclared stays a no-op', async () => {

+ 183 - 35
packages/client/ui-models/tests/components.spec.tsx

@@ -5,7 +5,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
 import Schema from 'schemastery'
 import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
 import type { RpcResponse, SettingsNamespaceView } from '@deepseek-ai/dsh-client-connection/client'
-import { ModelsSection, needsSetup, removeProviderProfile } from '../src/client/ModelsSection.tsx'
+import {
+  ModelsSection, needsSetup, providerCopy, providerTargetLabel, removeProviderProfile,
+} from '../src/client/ModelsSection.tsx'
 import type { ModelsSectionInjected, ModelsSectionProps } from '../src/client/ModelsSection.tsx'
 import { pathOps } from '../src/client/ProviderEditor.tsx'
 import {
@@ -18,6 +20,8 @@ import { en } from '../src/client/locales.ts'
 afterEach(cleanup)
 
 const t: ModelsSectionInjected['t'] = key => en[key]
+const OPENAI_TARGET = { provider: 'openai', displayName: 'openai' }
+const openaiCopy = (template: string): string => providerCopy(template, OPENAI_TARGET)
 
 /** Open one row's capacity disclosure (1-based, as the labels read). */
 function expandRow(position: number): void {
@@ -136,11 +140,13 @@ function scriptedFace(overrides: {
   replace?: ReturnType<typeof vi.fn>
   mutate?: ReturnType<typeof vi.fn>
   set?: ReturnType<typeof vi.fn>
+  unset?: ReturnType<typeof vi.fn>
 } = {}) {
   const update = overrides.update ?? vi.fn(() => Promise.resolve(ok(wireNamespaces()[2])))
   const replace = overrides.replace ?? vi.fn(() => Promise.resolve(ok(wireNamespaces()[2])))
   const mutate = overrides.mutate ?? vi.fn(() => Promise.resolve(ok(wireNamespaces()[2])))
   const set = overrides.set ?? vi.fn(() => Promise.resolve(ok({})))
+  const unset = overrides.unset ?? vi.fn(() => Promise.resolve(ok({})))
   const face = {
     llm: {
       providers: vi.fn(() => Promise.resolve(ok({
@@ -170,16 +176,16 @@ function scriptedFace(overrides: {
         }])),
       }))),
       set,
-      unset: vi.fn(() => Promise.resolve(ok({}))),
+      unset,
     },
   }
-  return { face, update, replace, mutate, set }
+  return { face, update, replace, mutate, set, unset }
 }
 
 type WireFace = ConstructorParameters<typeof ModelsSettingsStore>[0]
 
 async function mountSection(overrides: Parameters<typeof scriptedFace>[0] = {}) {
-  const { face, update, replace, mutate, set } = scriptedFace(overrides)
+  const { face, update, replace, mutate, set, unset } = scriptedFace(overrides)
   const controller = new ModelsSettingsStore(face as unknown as WireFace)
   await controller.load()
   const injected: ModelsSectionInjected = {
@@ -189,7 +195,7 @@ async function mountSection(overrides: Parameters<typeof scriptedFace>[0] = {})
     t,
   }
   const view = render(<ModelsSection {...injected} />)
-  return { view, face, update, replace, mutate, set, controller }
+  return { view, face, update, replace, mutate, set, unset, controller }
 }
 
 describe('ModelsSection', () => {
@@ -207,9 +213,36 @@ describe('ModelsSection', () => {
     expect(screen.getByText('openai')).toBeTruthy()
     expect(screen.queryByText('Active')).toBeNull()
     expect(screen.queryByText('Inactive')).toBeNull()
+    const configured = screen.getByRole('img', { name: en.credentialConfigured })
+    expect(configured.getAttribute('title')).toBe(en.credentialConfigured)
+    expect(configured.className).toContain('credentialDotConfigured')
+    expect(configured.closest('li')?.textContent).toContain('openai')
+    expect(screen.queryByRole('img', { name: en.credentialMissing })).toBeNull()
     expect(screen.getByText(en.add)).toBeTruthy()
   })
 
+  it('marks only a confirmed missing reference and leaves native or unavailable state unmarked', async () => {
+    const { face } = scriptedFace()
+    face.credentials.describe.mockImplementation((payload: { refs: string[] }) => Promise.resolve(ok({
+      credentials: Object.fromEntries(payload.refs.map(ref => [ref, { configured: false, writable: true }])),
+    })))
+    const controller = new ModelsSettingsStore(face as unknown as WireFace)
+    await controller.load()
+    render(<ModelsSection
+      controller={controller}
+      useSnapshot={bindSnapshotSelector(controller.store)}
+      api={face as never}
+      t={t}
+    />)
+
+    const missing = screen.getByRole('img', { name: en.credentialMissing })
+    expect(missing.getAttribute('title')).toBe(en.credentialMissing)
+    expect(missing.className).toContain('credentialDotMissing')
+    expect(missing.closest('li')?.textContent).toContain('openai')
+    expect(screen.queryByRole('img', { name: en.credentialConfigured })).toBeNull()
+    expect(screen.getByText('zombie').closest('li')?.querySelector('[role="img"]')).toBeNull()
+  })
+
   it('turns the setup card into a row once the credential reports configured', async () => {
     const { face } = await mountSection()
     face.credentials.describe.mockImplementation((payload: { refs: string[] }) => Promise.resolve(ok({
@@ -254,6 +287,13 @@ describe('ModelsSection', () => {
     expect(deriveKeyRef('minimax-cn')).toBe('MINIMAX_CN_API_KEY')
   })
 
+  it('uses one stable provider identity in action copy', () => {
+    const target = { provider: 'deepseek-official', displayName: 'DeepSeek' }
+    expect(providerTargetLabel(target)).toBe('DeepSeek (deepseek-official)')
+    expect(providerCopy(en.deleteTitle, target)).toBe('Delete DeepSeek (deepseek-official)?')
+    expect(providerTargetLabel(OPENAI_TARGET)).toBe('openai')
+  })
+
   it('names only the fields the card can see, so an unseen secret survives', () => {
     // `before` is the REDACTED subtree: a stored literal apiKey is in neither
     // side, so no op mentions it and the seam leaves it alone.
@@ -268,11 +308,16 @@ describe('ModelsSection', () => {
   it('stores a typed key write-only from the setup card without touching settings', async () => {
     const { set, update, face } = await mountSection()
     const key = screen.getByLabelText<HTMLInputElement>(en.keyInput)
-    fireEvent.change(key, { target: { value: 'sk-live' } })
+    fireEvent.change(key, { target: { value: '  sk-live  ' } })
     fireEvent.click(screen.getByText(en.apply))
     await waitFor(() => { expect(set).toHaveBeenCalledWith({ ref: 'DEEPSEEK_API_KEY', value: 'sk-live' }) })
     expect(update).not.toHaveBeenCalled()
     await waitFor(() => { expect(face.settings.describe.mock.calls.length).toBeGreaterThan(1) })
+    expect((await screen.findByRole('status')).textContent).toBe(
+      providerCopy(en.savedProvider, { provider: 'deepseek-official', displayName: 'DeepSeek' }),
+    )
+    fireEvent.click(screen.getByText(en.add))
+    expect(screen.queryByRole('status')).toBeNull()
   })
 
   it('applies customized deepseek fields as path ops', async () => {
@@ -777,6 +822,7 @@ describe('ModelsSection', () => {
     expect((urls[1] as HTMLInputElement).placeholder).toBe(en.baseUrlDefault)
     const keys = screen.getAllByLabelText<HTMLInputElement>(en.keyInput)
     const addKey = keys[keys.length - 1] as HTMLInputElement
+    expect(addKey.placeholder).toBe(en.keyPlaceholderNative)
     fireEvent.change(addKey, { target: { value: 'sk-ant' } })
     fireEvent.click(screen.getAllByText(en.apply)[1] as HTMLElement)
     await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) })
@@ -788,6 +834,59 @@ describe('ModelsSection', () => {
     await waitFor(() => { expect(set).toHaveBeenCalledWith({ ref: 'ANTHROPIC_API_KEY', value: 'sk-ant' }) })
   })
 
+  it('keeps pi-ai provider-native authentication when no key is entered', async () => {
+    const { mutate, set } = await mountSection()
+    fireEvent.click(screen.getByText(en.add))
+    await screen.findByLabelText(en.provider)
+    fireEvent.click(screen.getAllByText(en.apply)[1] as HTMLElement)
+    await waitFor(() => { expect(mutate).toHaveBeenCalledOnce() })
+    expect(mutate.mock.calls[0]?.[0]).toEqual({
+      ns: 'llm-pi-ai',
+      ops: [{ op: 'set', path: ['providers', 'anthropic'], value: {} }],
+      expectedRevision: 0,
+    })
+    expect(set).not.toHaveBeenCalled()
+  })
+
+  it('retries only the credential after refreshed settings already committed', async () => {
+    const committed = wireNamespaces()[2]!
+    const afterSettings: SettingsNamespaceView = {
+      ...committed,
+      value: { providers: {
+        ...(committed.value as { providers: object }).providers,
+        anthropic: { apiKeyEnv: 'ANTHROPIC_API_KEY' },
+      } },
+      user: { providers: {
+        ...(committed.user as { providers: object }).providers,
+        anthropic: { apiKeyEnv: 'ANTHROPIC_API_KEY' },
+      } },
+      revision: 1,
+    }
+    const mutate = vi.fn(() => Promise.resolve(ok(afterSettings)))
+    const set = vi.fn()
+      .mockResolvedValueOnce(fail('credential store unavailable', 'credential-rejected'))
+      .mockResolvedValueOnce(ok({}))
+    const { face, controller } = await mountSection({ mutate, set })
+    fireEvent.click(screen.getByText(en.add))
+    await screen.findByLabelText(en.provider)
+    const keys = screen.getAllByLabelText<HTMLInputElement>(en.keyInput)
+    fireEvent.change(keys[keys.length - 1] as HTMLInputElement, { target: { value: 'sk-ant' } })
+    fireEvent.click(screen.getAllByText(en.apply)[1] as HTMLElement)
+    await screen.findByText('credential store unavailable')
+    expect(mutate).toHaveBeenCalledOnce()
+    face.settings.describe.mockResolvedValue(ok({
+      writable: true,
+      hasDocument: false,
+      namespaces: wireNamespaces().map(namespace => namespace.ns === 'llm-pi-ai' ? afterSettings : namespace),
+    }))
+    await act(async () => { await controller.load() })
+    expect(controller.store.getSnapshot().namespaces.get('llm-pi-ai')?.revision).toBe(1)
+    fireEvent.click(screen.getAllByText(en.apply)[1] as HTMLElement)
+    await waitFor(() => { expect(set).toHaveBeenCalledTimes(2) })
+    expect(mutate).toHaveBeenCalledOnce()
+    expect(set).toHaveBeenLastCalledWith({ ref: 'ANTHROPIC_API_KEY', value: 'sk-ant' })
+  })
+
   it('switches the add card target and degrades unknown or broken targets loudly', async () => {
     await mountSection()
     fireEvent.click(screen.getByText(en.add))
@@ -876,6 +975,7 @@ describe('ModelsSection', () => {
     fireEvent.change(key, { target: { value: 'sk-live' } })
     fireEvent.click(screen.getByText(en.apply))
     await screen.findByText(/shadowed by the read-only environment/)
+    expect(screen.queryByRole('status')).toBeNull()
   })
 
   it('locks the key input when the launch environment provides the credential', async () => {
@@ -898,34 +998,37 @@ describe('ModelsSection', () => {
     fireEvent.click(screen.getAllByText(en.edit)[0] as HTMLElement)
     const keys = await screen.findAllByLabelText<HTMLInputElement>(en.keyInput)
     const editorKey = keys[keys.length - 1] as HTMLInputElement
-    expect(editorKey.placeholder).toBe(en.keyPlaceholder)
+    expect(editorKey.placeholder).toBe(en.keyPlaceholderNative)
     fireEvent.change(editorKey, { target: { value: 'sk-live' } })
     fireEvent.click(screen.getAllByText(en.apply)[1] as HTMLElement)
     await waitFor(() => { expect(set).toHaveBeenCalledTimes(1) })
   })
 
   it('requires confirmation before removing a user-added provider', async () => {
-    const { replace, mutate } = await mountSection()
-    fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement)
-    const dialog = screen.getByRole('dialog', { name: en.deleteTitle })
-    expect(dialog.textContent).toContain(en.deleteDescription)
+    const { replace, mutate, unset } = await mountSection()
+    fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.removeProvider) }))
+    const dialog = screen.getByRole('dialog', { name: openaiCopy(en.deleteTitle) })
+    expect(dialog.textContent).toContain(openaiCopy(en.deleteDescriptionWithCredential))
     expect(document.activeElement).toBe(within(dialog).getByRole('button', { name: en.cancel }))
+    expect(unset).not.toHaveBeenCalled()
     expect(mutate).not.toHaveBeenCalled()
     fireEvent.click(within(dialog).getByRole('button', { name: en.cancel }))
-    expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull()
+    expect(screen.queryByRole('dialog', { name: openaiCopy(en.deleteTitle) })).toBeNull()
     expect(mutate).not.toHaveBeenCalled()
 
-    fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement)
-    fireEvent.click(within(screen.getByRole('dialog', { name: en.deleteTitle }))
+    fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.removeProvider) }))
+    fireEvent.click(within(screen.getByRole('dialog', { name: openaiCopy(en.deleteTitle) }))
       .getByRole('button', { name: en.close }))
-    expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull()
+    expect(screen.queryByRole('dialog', { name: openaiCopy(en.deleteTitle) })).toBeNull()
     expect(mutate).not.toHaveBeenCalled()
 
-    fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement)
-    fireEvent.click(within(screen.getByRole('dialog', { name: en.deleteTitle }))
-      .getByRole('button', { name: en.deleteConfirm }))
+    fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.removeProvider) }))
+    fireEvent.click(within(screen.getByRole('dialog', { name: openaiCopy(en.deleteTitle) }))
+      .getByRole('button', { name: openaiCopy(en.deleteConfirm) }))
+    await waitFor(() => { expect(unset).toHaveBeenCalledWith({ ref: 'OPENAI_API_KEY' }) })
     await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) })
-    expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull()
+    expect(unset.mock.invocationCallOrder[0]).toBeLessThan(mutate.mock.invocationCallOrder[0] as number)
+    expect(screen.queryByRole('dialog', { name: openaiCopy(en.deleteTitle) })).toBeNull()
     expect(replace).not.toHaveBeenCalled()
     expect(mutate.mock.calls[0]?.[0]).toEqual({
       ns: 'llm-pi-ai',
@@ -939,20 +1042,22 @@ describe('ModelsSection', () => {
       resolveRemoval = resolve
     }))
     await mountSection({ mutate })
-    fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement)
-    const dialog = screen.getByRole('dialog', { name: en.deleteTitle })
-    const confirm = within(dialog).getByRole<HTMLButtonElement>('button', { name: en.deleteConfirm })
+    fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.removeProvider) }))
+    const dialog = screen.getByRole('dialog', { name: openaiCopy(en.deleteTitle) })
+    const confirm = within(dialog).getByRole<HTMLButtonElement>('button', { name: openaiCopy(en.deleteConfirm) })
     fireEvent.click(confirm)
     fireEvent.click(confirm)
-    expect(mutate).toHaveBeenCalledOnce()
+    await waitFor(() => { expect(mutate).toHaveBeenCalledOnce() })
     expect(confirm.disabled).toBe(true)
     expect(within(dialog).getByRole<HTMLButtonElement>('button', { name: en.cancel }).disabled).toBe(true)
-    expect(within(dialog).getByRole('button', { name: en.deleting })).toBe(confirm)
+    expect(within(dialog).getByRole('button', { name: openaiCopy(en.deleting) })).toBe(confirm)
     fireEvent.click(within(dialog).getByRole('button', { name: en.close }))
-    expect(screen.getByRole('dialog', { name: en.deleteTitle })).toBe(dialog)
+    expect(screen.getByRole('dialog', { name: openaiCopy(en.deleteTitle) })).toBe(dialog)
     expect(mutate).toHaveBeenCalledOnce()
     await act(async () => { resolveRemoval(ok(wireNamespaces()[2]!)) })
-    await waitFor(() => { expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull() })
+    await waitFor(() => {
+      expect(screen.queryByRole('dialog', { name: openaiCopy(en.deleteTitle) })).toBeNull()
+    })
   })
 
   it('renders the load failure with a retry control', async () => {
@@ -1057,15 +1162,58 @@ describe('ModelsSection', () => {
     expect(controller.store.getSnapshot().rows).toBe(before)
   })
 
-  it('shows a failed removal on the page banner, including a non-Error rejection', async () => {
-    // The whole click path: the row's Remove button, the transport rejecting
-    // with a non-Error value, and the store surfacing it where a load failure
-    // would appear — rather than the row silently staying put.
-    await mountSection({ mutate: vi.fn(() => Promise.reject(new Error('the host refused'))) })
-    fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement)
-    fireEvent.click(within(screen.getByRole('dialog', { name: en.deleteTitle }))
-      .getByRole('button', { name: en.deleteConfirm }))
-    await screen.findByText(`${en.loadFailed}: the host refused`)
+  it('keeps a failed identified deletion recoverable in its confirmation dialog', async () => {
+    const mutate = vi.fn()
+      .mockResolvedValueOnce(fail('the host refused'))
+      .mockResolvedValueOnce(ok(wireNamespaces()[2]!))
+    const { unset } = await mountSection({ mutate })
+    fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.removeProvider) }))
+    const dialog = screen.getByRole('dialog', { name: openaiCopy(en.deleteTitle) })
+    const confirm = within(dialog).getByRole('button', { name: openaiCopy(en.deleteConfirm) })
+    fireEvent.click(confirm)
+    await within(dialog).findByText('the host refused')
+    expect(screen.getByRole('dialog', { name: openaiCopy(en.deleteTitle) })).toBe(dialog)
+    expect(unset).toHaveBeenCalledOnce()
+    expect(mutate).toHaveBeenCalledOnce()
+
+    fireEvent.click(confirm)
+    await waitFor(() => { expect(unset).toHaveBeenCalledTimes(2) })
+    await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(2) })
+    await waitFor(() => {
+      expect(screen.queryByRole('dialog', { name: openaiCopy(en.deleteTitle) })).toBeNull()
+    })
+  })
+
+  it('retains credentials that are not identified as page-managed', async () => {
+    const { unset, mutate } = await mountSection()
+    const target = { provider: 'zombie', displayName: 'zombie' }
+    fireEvent.click(screen.getByRole('button', { name: providerCopy(en.removeProvider, target) }))
+    const dialog = screen.getByRole('dialog', { name: providerCopy(en.deleteTitle, target) })
+    expect(dialog.textContent).toContain(providerCopy(en.deleteDescription, target))
+    fireEvent.click(within(dialog).getByRole('button', { name: providerCopy(en.deleteConfirm, target) }))
+    await waitFor(() => { expect(mutate).toHaveBeenCalledOnce() })
+    expect(unset).not.toHaveBeenCalled()
+    expect(mutate.mock.calls[0]?.[0]).toEqual({
+      ns: 'llm-pi-ai',
+      ops: [{ op: 'unset', path: ['providers', 'zombie'] }],
+    })
+  })
+
+  it('does not remove provider settings when its managed credential removal is refused', async () => {
+    const { face, controller, mutate } = await mountSection({
+      unset: vi.fn(() => Promise.resolve(fail('credential is read-only', 'credential-rejected'))),
+    })
+    const failure = await removeProviderProfile(
+      face as unknown as Parameters<typeof removeProviderProfile>[0],
+      controller,
+      {
+        settingsNs: 'llm-pi-ai',
+        settingsPath: ['providers', 'openai'],
+        credentialRef: 'OPENAI_API_KEY',
+      },
+    )
+    expect(failure).toBe('credential is read-only')
+    expect(mutate).not.toHaveBeenCalled()
   })
 
   it('reports a transport rejection instead of failing the removal silently', async () => {

+ 17 - 1
packages/client/ui-models/tests/provider-form.spec.tsx

@@ -142,7 +142,7 @@ async function mountSection(options: Parameters<typeof scriptedFace>[0] = {}) {
     t,
   }
   render(<ModelsSection {...injected} />)
-  return scripted
+  return { ...scripted, controller }
 }
 
 /** Open the editor of one configured row and expand its customized fold. */
@@ -862,4 +862,20 @@ describe('hand-declared providers', () => {
     await waitFor(() => { expect(screen.queryByText(en.customTitle)).toBeNull() })
     expect(screen.getByRole('button', { name: en.customAdd })).toBeTruthy()
   })
+
+  it('reloads the section after creating a hand-declared provider', async () => {
+    const { controller, mutate } = await mountSection()
+    const load = vi.spyOn(controller, 'load')
+
+    fireEvent.click(screen.getByRole('button', { name: en.customAdd }))
+    fireEvent.change(screen.getByLabelText(en.customRoute), { target: { value: 'acme' } })
+    fireEvent.change(screen.getByLabelText(en.baseUrl), { target: { value: 'https://acme.test/v1' } })
+    fireEvent.click(screen.getByRole('button', { name: en.addModel }))
+    fireEvent.change(screen.getByLabelText(`${en.modelId} 1`), { target: { value: 'm' } })
+    fireEvent.click(screen.getByText(en.create))
+
+    await waitFor(() => { expect(mutate).toHaveBeenCalledOnce() })
+    await waitFor(() => { expect(load).toHaveBeenCalledOnce() })
+    expect(screen.queryByText(en.customTitle)).toBeNull()
+  })
 })

+ 2 - 2
packages/code-runtime/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/code-runtime/README.md
-README.md: 2d32a05071efdfa05c336211196bb769ed5a5fc7
-README.zh.md: 62c9a395ac3cf2b5cd55455ab5a273a1e276f6b7
+README.md: f20a287419b94b1a9dc1d8da7303fc4d3032cfd3
+README.zh.md: f5cd4c9949f2bd7a7d6d7cd078144910712a3819

Некоторые файлы не были показаны из-за большого количества измененных файлов