Merge origin/master into feat/cua-bundle-id-consent

This commit is contained in:
creatixchu committed 2026-10-26 12:31:36 +08:00
commit 886df319bc
500 files changed
+12976 -3314

No files matched your search

@@ -27,14 +27,14 @@
en: d5d0d6a57a4fa581
zh: 265973b157f957d9
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller:
en: e338ac27490a380f
zh: 12600011ec742e5b
en: f432480a52414d56
zh: 15a3f175b69cdb53
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/activation-policy:
en: 534dcc62a26d305e
zh: 03d64abc0a46bbec
en: 03e24cdee8519a92
zh: 82dc02eb26d7d7f4
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/session-journal:
en: bb710f8cf35f2028
zh: aae2cfb8cd848069
en: 4de2965717900b96
zh: 1d129003824fa6bd
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/session-live-control:
en: a11d627cd68650c3
zh: 9aff565b9f712853
@@ -139,11 +139,11 @@ If a page request is canceled with its physical carrier generation, the journal
`packages/api/session-controller` provides Host `ctx.sessionController` and the generated `ctx.remote.session` namespace.
It owns Session list, search, create, selectModel, rename, fork, prompt, attachment, updateQueue, cancel, page, follow, and control. The Host-generation model catalog is exposed separately through `session/modelCatalog` because it is not Session-specific.
It owns Session list, search, create, selectModel, rename, fork, prompt, attachment, updateQueue, cancel, `events`, the deprecated `page`, `follow`, `control`, plus `observeEvent`, `projections`, `observeProjections`, `state`, `observeState`, and `wait`. The Host-generation model catalog is exposed separately through `session/modelCatalog` because it is not Session-specific.
The package separates agent, commands, control, history, and list controllers internally, but Session identity resolution, activation policy, subagent ownership, and Remote error projection have one public owner.
Other Host Remote namespaces reuse the same identity rules through `ctx.sessionController.inspect()` or `resolveAgent()`; they do not retain a second Session resolver.
Other Host Remote namespaces reuse the same resume-capable identity rules through `ctx.sessionController.resolveAgent()`; they do not retain a second Session resolver.
#### Activation policy
@@ -157,7 +157,8 @@ Each method explicitly selects a cold inspection, live-only lookup, or resume-ca
| `session.page(address)` | attached Session or persistence log | Never resumes an Agent |
| `session.follow(address)` | one live or prepared observation carrying the opening page and projections | Publishes the snapshot first, then promotes an ordinary cold Session once in the background |
| `session.control()` | current attached Agents, pending registry, and process-local registries | Baseline and reconnect do not resume an Agent |
| `session.attachment`, fork source read | authorized durable Session data | A read does not resume an Agent |
| Fork source read | authorized durable Session data | A read does not resume an Agent |
| `session.attachment` | attachment store under the [image access rule](2026-10-23-store-scoped-image-reads.md) | A read does not resume an Agent |
| `session.updateQueue` | live Agent or ordinary persisted Session | Resumes an ordinary cold Session before mutating its Inbox |
| `session.cancel` | only the current live Agent | Does not resume vanished state |
| `models`, `selectModel`, `rename`, `prompt` | command resolves the target Session | Resumes only when the method explicitly permits it |
@@ -173,9 +174,9 @@ Reading titles, lists, and projections does not require an Agent. An observation
#### Session journal
`session.page` returns a history window clipped on message boundaries with contiguous internal sequence numbers. Every request must carry an explicit `throughSeq`; this value comes from the corresponding `session.follow` generation's opening cursor and fixes the read at the same log cut. A tail page without `beforeSeq` must end exactly at `throughSeq`, where `-1` denotes an empty log. `beforeSeq` only selects an older page before that cut and cannot replace the synchronization cursor. `maxMessages` limits user/assistant message count without dropping chunks, tools, or state events between those messages.
`session.events` returns a history window clipped on message boundaries with contiguous internal sequence numbers. `throughSeq` is optional: when omitted, the read selects the observed log end and returns it as the page's inclusive `cursor`; a supplied value fixes the read at that cut. A page without `beforeSeq` ends exactly at the selected cut, where `-1` denotes an empty log. `beforeSeq` only selects an older page before that cut and cannot replace the synchronization cursor. `maxMessages` limits user/assistant message count without dropping chunks, tools, or state events between those messages. The deprecated `session.page` entry returns the same type.
The tail page also carries a projection baseline no later than `throughSeq`; older pages carry only historical entries. The Client merges pages and subsequent live control updates by projection watermark.
A page carries only its records, `hasMore`, and inclusive `cursor`; a projection baseline comes from a follow opening snapshot or the control stream, never from a page. The Client merges pages and subsequent live control updates by projection watermark.
Ordinary Sessions and direct subagents use one `SessionAddress` protocol. A direct-subagent address carries parent Session, child Session, and mode; a cold Host read verifies durable ownership and descriptor rather than authorizing access from the child id alone.
@@ -139,11 +139,11 @@ repair 期间旧 window 保持可读;page 与期间积累的 live entries 拼
`packages/api/session-controller` 提供 Host `ctx.sessionController` 与生成的 `ctx.remote.session` namespace。
它拥有 Session list、search、create、selectModel、rename、fork、prompt、attachment、updateQueue、cancel、page、follow 与 control。Host generation 的 model catalog 通过独立的 `session/modelCatalog` 公开,因为它不属于特定 Session。
它拥有 Session list、search、create、selectModel、rename、fork、prompt、attachment、updateQueue、cancel、`events`、已弃用的 `page`、`follow`、`control`,以及 `observeEvent`、`projections`、`observeProjections`、`state`、`observeState` 与 `wait`。Host generation 的 model catalog 通过独立的 `session/modelCatalog` 公开,因为它不属于特定 Session。
包内的 agent、commands、control、history 与 list controller 分开实现,但 Session 身份解析、激活策略、subagent ownership 和 Remote 错误投影只有一个公开 owner。
其他 Host Remote namespace 通过 `ctx.sessionController.inspect()` 或 `resolveAgent()` 复用同一身份规则,不保留第二份 Session resolver。
其他 Host Remote namespace 通过 `ctx.sessionController.resolveAgent()` 复用同一套允许恢复 Session 的身份规则,不保留第二份 Session resolver。
#### 激活策略
@@ -157,7 +157,8 @@ Session Remote 方法传递 `SessionId` 或 `SessionAddress`,不靠参数类
| `session.page(address)` | attached Session 或 persistence 日志 | 永不恢复 Agent |
| `session.follow(address)` | 一份携带 opening page 与 projection 的 live 或 prepared observation | 先发布 snapshot,再在后台把普通冷 Session 提升一次 |
| `session.control()` | 当前 attached Agent、pending registry 与进程内 registry | baseline 与重连不恢复 Agent |
| `session.attachment`、fork 源读取 | 已授权的持久 Session 数据 | 读取不恢复 Agent |
| Fork 源读取 | 已授权的持久 Session 数据 | 读取不恢复 Agent |
| `session.attachment` | 按[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)读取附件存储 | 读取不恢复 Agent |
| `session.updateQueue` | live Agent 或普通持久 Session | 修改 Inbox 前恢复普通冷 Session |
| `session.cancel` | 仅命中当前 live Agent | 不为已消失状态恢复 Agent |
| `models`、`selectModel`、`rename`、`prompt` | 命令解析目标 Session | 仅按方法约定显式恢复 |
@@ -173,9 +174,9 @@ Session Remote 方法传递 `SessionId` 或 `SessionAddress`,不靠参数类
#### Session 日志
`session.page` 返回一段按消息边界裁剪、内部 seq 连续的历史窗口。每个请求必须显式携带 `throughSeq`;该值来自对应 `session.follow` generation 的 opening cursor,并把本次读取固定在同一个日志切点。无 `beforeSeq` 的 tail page 必须精确结束于 `throughSeq`,其中 `-1` 表示空日志;`beforeSeq` 只选择该切点之前的更早页面,不能替代同步 cursor。`maxMessages` 限制 user/assistant 消息数,不丢弃这些消息之间的 chunk、tool 或状态事件。
`session.events` 返回一段按消息边界裁剪、内部 seq 连续的历史窗口。`throughSeq` 可省略:省略时选取观察到的日志末尾,并把该切点作为页面的 inclusive `cursor` 返回;显式提供时把本次读取固定在该切点。无 `beforeSeq` 的 page 精确结束于所选切点,其中 `-1` 表示空日志;`beforeSeq` 只选择该切点之前的更早页面,不能替代同步 cursor。`maxMessages` 限制 user/assistant 消息数,不丢弃这些消息之间的 chunk、tool 或状态事件。已弃用的 `session.page` 入口返回同一类型。
tail page 同时携带不晚于 `throughSeq` 的 projection baseline;旧页只携带历史 entries。Client 以 projection watermark 合并 page 与后续 live control 更新。
page 只携带记录、`hasMore` 和 inclusive `cursor`;projection baseline 来自 follow 的开场快照或 control 流,不来自 page。Client 以 projection watermark 合并 page 与后续 live control 更新。
普通 Session 与 direct subagent 使用同一个 `SessionAddress` 协议。direct subagent 地址同时携带父 Session、子 Session 与 mode,Host 冷读时验证持久 ownership 和 descriptor,不能只凭 child id 越权读取。
@@ -51,8 +51,8 @@
en: 51f99cfca9c4c808
zh: ce95bab241d306f7
/agent-note-client-derived-presentation-from-raw-session-tool-events/host-design:
en: 16fd2b3e545ede21
zh: 4d28f52132495441
en: d5e5d1376dc42558
zh: c2f302b2a5d1de39
/agent-note-client-derived-presentation-from-raw-session-tool-events/host-design/performance-constraints:
en: 102b14e3eb9367ff
zh: d391099dbc41db24
@@ -195,9 +195,9 @@ The Client narrows `meta` locally at runtime. Renaming `presentationMeta` to mor
## Host Design
After obtaining source events, `SessionHistoryController.page()` performs only pagination and the existing projection-baseline calculation. Attached Sessions use the projection registry snapshot; detached Sessions use its restore path over the inspected log. History does not mount a preset to change the registered projection set.
After obtaining source events, `HistoryController.history()` performs only pagination and requests projections only for a subagent address that needs descriptor validation. Attached Sessions use the projection registry snapshot; detached Sessions use its restore path over the inspected log. History does not mount a preset to change the registered projection set.
`SessionHistoryController.follow()` retains listener-first setup, opening cursors, gap-free replay, live buffering, cancellation, and teardown. It maintains no additional state for tool events.
`WebController.follow()` retains listener-first setup, opening cursors, gap-free replay, live buffering, cancellation, and teardown. It maintains no additional state for tool events.
The controller has no `presenterScopeFor()`, `viewFor()`, `backscanArgs()`, `parseToolCall()`, or `jsonView()` path. Page state contains no presenter scope or argument resolver; follow state contains no `openCalls`, `fallbackEvents`, or presentation argument resolver. Each page/follow event is wrapped only as `{event}` while addressing, ownership, cursor, sequence, and projection logic remains intact.
@@ -195,9 +195,9 @@ Client 对 `meta` 做局部运行时收窄。是否把 `presentationMeta` 改名
## Host 端设计
`SessionHistoryController.page()` 在取得 source events 后只执行分页与现有 projection baseline 计算。attached Session 使用 projection registry snapshot;detached Session 使用该 registry 对 inspected log 的 restore 路径。history 不通过挂载 preset 改变已注册的 projection 集合。
`HistoryController.history()` 在取得 source events 后只执行分页,并且只有需要校验 descriptor 的 subagent 地址才请求投影。attached Session 使用 projection registry snapshot;detached Session 使用该 registry 对 inspected log 的 restore 路径。history 不通过挂载 preset 改变已注册的 projection 集合。
`SessionHistoryController.follow()` 保留 listener-first、opening cursor、gap-free replay、live buffering、取消和 teardown;它不为工具事件维护额外状态。
`WebController.follow()` 保留 listener-first、opening cursor、gap-free replay、live buffering、取消和 teardown;它不为工具事件维护额外状态。
Controller 不存在 `presenterScopeFor()`、`viewFor()`、`backscanArgs()`、`parseToolCall()` 或 `jsonView()` 路径。page state 不含 presenter scope 或参数 resolver;follow state 不含 `openCalls`、`fallbackEvents` 或 presentation 参数 resolver。每个 page/follow event 只包装成 `{event}`,地址、ownership、cursor、seq 与 projection 逻辑保持完整。
@@ -15,17 +15,17 @@
en: 480284ae1a6ce210
zh: d42c72ada9f019f8
/agent-note-session-observations-and-projection-owned-client-state/decision/observation-is-the-point-read-unit:
en: fac92f8547482a49
zh: 60240c47fbe4611f
en: 283136ae36512767
zh: e342b446c77ae300
/agent-note-session-observations-and-projection-owned-client-state/decision/source-resolution-and-lifetime:
en: e550ae9892474276
zh: fb6a2d9e91ebd4d9
en: bced4b90cb03525d
zh: b0c1ca4bf1064f89
/agent-note-session-observations-and-projection-owned-client-state/decision/projection-execution-boundary:
en: 148de86941b90f41
zh: c065a8e96e28b9d7
en: b3b235fa0250868a
zh: 0bb5eedf14cdafee
/agent-note-session-observations-and-projection-owned-client-state/decision/read-audiences:
en: 888f62659f4d868d
zh: e74491e8c85046ee
en: e394e9480340f69c
zh: 7eea994ee9fa380d
/agent-note-session-observations-and-projection-owned-client-state/decision/replayable-client-facts-are-projection-owned:
en: efded09f0cd30a8e
zh: 5e16580a39ff3359
@@ -48,11 +48,11 @@
en: 8d699dfc22ab5c5f
zh: 8dcd9fc6bd1594db
/agent-note-session-observations-and-projection-owned-client-state/verification:
en: df17217023668428
zh: 88f7da4deffc6bf9
en: 29f364d1031b7d85
zh: 2b193ceb52fb0406
/agent-note-session-observations-and-projection-owned-client-state/alternatives-considered:
en: a25138b4298cda16
zh: 92799a9bd8867d47
en: 90574351058d5d8c
zh: 6aa514cf47495ed2
/agent-note-session-observations-and-projection-owned-client-state/consequences:
en: e1f8bd8fa68de603
zh: 5afcd06f2611bc1e
@@ -24,7 +24,7 @@ The two ownership rules meet at the observation's projection snapshot. Lightweig
flowchart LR
List["list / search"] --> Corpus["SessionQuery corpus"]
Follow["follow"] --> Observe["observeSession"]
Page["page / attachment / fork"] --> Observe
Page["page / fork"] --> Observe
Subagent["subagent list / continuation"] --> Observe
Corpus --> Cache["projection cache hints"]
Cache --> ClientList["Client Session list"]
@@ -46,7 +46,7 @@ flowchart LR
`SessionQueryEngine.observeSession(sessionId, options)` returns a disposable `SessionObservation` containing one source kind, header, contiguous event prefix, cursor, optional projection snapshot, and the durable revision for a prepared source. An attached Session wins. Otherwise the reader's own prepared cache — keyed by `stat().revision` and pinned by observation leases — serves the cold Session, sharing one persistence read (`open(id, 'read')` + `read`) across concurrent observations, including an in-flight cold load.
Every owner disposes its observation. `retain()` creates another lease over the same cut, which lets `session.follow` publish a snapshot and then transfer that exact prepared source to background Agent promotion without rereading the log. A live Session that appears during cold resolution wins before publication; a disappeared live source is retried as cold.
Every owner disposes its observation. `retain()` creates another lease over the same cut, which lets `session.follow` transfer that exact prepared source to background Agent promotion before delivering the snapshot, without rereading the log. A live Session that appears during cold resolution wins before publication; a disappeared live source is retried as cold.
### Source resolution and lifetime
@@ -56,7 +56,7 @@ Live preference is checked both before and after a cold borrow. The second check
Persistence absence maps to Session-not-found only after no attached Session exists. Durable corruption, source-identity conflict, cancellation, and operational persistence failure remain distinct `SessionQueryError` outcomes so API owners can preserve their own public error vocabulary without duplicating source detection.
The observation owns no mutation authority. Its event array is an immutable prefix, and its prepared Session remains unpublished. Promotion is an explicit ownership transfer performed by the Session Controller after it has emitted the opening snapshot; other readers cannot turn an observation into a live Agent.
The observation owns no mutation authority. Its event array is an immutable prefix, and its prepared Session remains unpublished. Promotion is an explicit ownership transfer the Session Controller starts once the opening is computed, before delivering it; other readers cannot turn an observation into a live Agent.
Projection work is deliberately `all | none`. `all` computes every registered projection at the observation's event cursor; `none` leaves projection state untouched. There is no per-key preparation state, `projectionKeys` mode, or cached `viewedState`/`viewedValue` layer. A publisher may filter the completed values for an audience, but the underlying observation is never partly projected.
@@ -72,7 +72,7 @@ The registry owns fold state; each domain owns its `init`, `apply`, `view`, sche
Corpus listing remains a separate lightweight operation. `listSessions()` returns live-preferred headers without materializing every log. Session list first uses live projection state or durable projection-cache rows. Subagent discovery reads parent-catalog projections through exact observations. Session list may take one complete observation for an individually stored artifact within its configured small-log limit when cached metadata cannot establish whether it is blank; a large or unreadable cache miss remains visible with unknown hints.
`session.follow` publishes a required opening snapshot containing header, cursor, the initial event window, and a complete projection baseline. Reconnect replaces the previous generation from another complete snapshot. `session.page` is reserved for older-history reads and gap repair. Observation-only reads never activate an Agent; only an ordinary follow may retain its prepared observation and request promotion after the opening snapshot has been delivered.
`session.follow` publishes a required opening snapshot containing header, cursor, the initial event window, and a complete projection baseline. Reconnect replaces the previous generation from another complete snapshot. `session.page` supports current or fixed-cut history reads, older-history reads, and gap repair. Observation-only reads never activate an Agent; only an activation-enabled ordinary Follow may retain its prepared observation and request promotion once the opening snapshot is computed, before it is delivered. The [snapshot and subscription decision](2026-10-21-session-history-stream-and-snapshot.md) defines the Controller composition and passive subscription semantics.
### Read audiences
@@ -82,9 +82,10 @@ Each public operation chooses one query and projection policy. The choice is par
|---|---|---|---|
| `session.list` | Corpus headers, live state, and cached rows; bounded small-log fallback | Partial hints, or one full small-log observation | Never |
| `session.search` | Corpus authorization plus the configured search provider | None for result listing | Never |
| `session.follow` | One exact observation | All, carried in the opening snapshot | Ordinary cold Session only, after snapshot delivery |
| `session.follow` | One exact observation | All, carried in the opening snapshot | Only with `activate: true`, for an ordinary cold Session once the opening is computed, before delivery |
| `session.page` | One exact observation | None, except projection-backed subagent authorization | Never |
| Attachment and fork source | One exact observation | None unless authorization requires it | Never for the source |
| Fork source | One exact observation | None unless authorization requires it | Never for the source |
| Attachment | Direct store read under the [image access rule](2026-10-23-store-scoped-image-reads.md) | None | Never |
| Subagent list and continuation | Parent-catalog observations for listing; target observations for continuation | All; listing consumes catalog values, continuation consumes identity and inherited values | Never for listing; continuation follows its explicit command semantics |
### Replayable Client facts are projection-owned
@@ -171,7 +172,7 @@ These rules apply to new Session-derived Client state even when a direct event s
## Verification
Persistence and SessionQuery tests pin shared cold loading, cancellation, live-source races, retained observations, disposal, and all-or-none projection calculation. Session Controller and Gateway tests pin snapshot-first opening, replacement reconnect, older-page reads, gap repair, list-cache hints, bounded small-log fallback, and promotion after snapshot delivery.
Persistence and SessionQuery tests pin shared cold loading, cancellation, live-source races, retained observations, disposal, and all-or-none projection calculation. Session Controller and Gateway tests pin snapshot-first opening, replacement reconnect, older-page reads, gap repair, list-cache hints, bounded small-log fallback, and promotion once the opening is computed.
Client tests pin higher-sequence-wins projection storage, title updates, model catalog and selection readiness, preset roster refresh and Session-specific selection, and subagent loading without transient offline presentation. Subagent tests pin parent-catalog order, recursive traversal, branch diagnostics, cancellation, fork isolation, and no Agent activation during listing.
@@ -179,7 +180,7 @@ Client tests pin higher-sequence-wins projection storage, title updates, model c
**Keep source resolution in each consumer.** Rejected because every caller would continue to implement its own live race, persistence error mapping, preparation lifetime, cancellation, and projection cut, allowing both duplicate work and inconsistent results.
**Activate an Agent for every exact read.** Rejected because list, history, attachment, search, and subagent inspection are read operations. Activation loads plugins and changes process state, and it has no natural retirement point for pagination or catalog reads.
**Activate an Agent for every exact read.** Rejected because list, history, search, and subagent inspection are read operations. Activation loads plugins and changes process state, and it has no natural retirement point for pagination or catalog reads.
**Prepare only requested projection keys.** Rejected because a partially projected Session creates another lifecycle state that every cache, restore, plugin-registration, and caller path must track. Projection units are pure and few; computing all registered units for an exact observation is simpler than maintaining `O(E*k)` partial state instead of `O(E*P)` complete state.
@@ -24,7 +24,7 @@ Session 精确读取使用可保留的 `SessionObservation`,向 Client 暴露
flowchart LR
List["list / search"] --> Corpus["SessionQuery corpus"]
Follow["follow"] --> Observe["observeSession"]
Page["page / attachment / fork"] --> Observe
Page["page / fork"] --> Observe
Subagent["subagent list / continuation"] --> Observe
Corpus --> Cache["projection cache hints"]
Cache --> ClientList["Client Session list"]
@@ -46,7 +46,7 @@ flowchart LR
`SessionQueryEngine.observeSession(sessionId, options)` 返回可 dispose(资源释放)的 `SessionObservation`,其中包含同一份 source kind、header、连续事件前缀、cursor、可选 projection snapshot,以及 prepared source 的持久化 revision。已挂载 Session 优先;否则由读取方自己的 prepared cache——以 `stat().revision` 为键、由 observation lease 固定——提供冷 Session,让并发 observation 共享同一次持久化读取(`open(id, 'read')` + `read`),包括尚未完成的冷加载。
每个 owner 都会 dispose 自己的 observation。`retain()` 为同一切面创建另一份 lease,使 `session.follow` 能够先发布 snapshot,再把完全相同的 prepared source 转交给后台 Agent promotion,而无需重读日志。冷解析期间出现的 live Session 会在发布前胜出;已经消失的 live source 会按 cold source 重试。
每个 owner 都会 dispose 自己的 observation。`retain()` 为同一切面创建另一份 lease,使 `session.follow` 能把完全相同的 prepared source 转交给后台 Agent promotion,并在交付 snapshot 前启动它,而无需重读日志。冷解析期间出现的 live Session 会在发布前胜出;已经消失的 live source 会按 cold source 重试。
### 数据源解析与生命周期
@@ -56,7 +56,7 @@ flowchart LR
只有在不存在已挂载 Session 后,persistence absence 才映射为 Session-not-found。持久数据损坏、source identity 冲突、取消和 persistence 操作失败分别保留不同的 `SessionQueryError`,API owner 因而可以维持自身公开错误词汇,而不用重复数据源判定。
Observation 不拥有任何 mutation 权限。其事件数组是不可变前缀,prepared Session 保持未发布。Promotion 是 Session Controller 在 opening snapshot 发出后执行的显式 ownership transfer;其他读方不能把 observation 变成 live Agent。
Observation 不拥有任何 mutation 权限。其事件数组是不可变前缀,prepared Session 保持未发布。Promotion 是 Session Controller 在 opening 计算完成后、交付前启动的显式 ownership transfer;其他读方不能把 observation 变成 live Agent。
Projection 工作明确只有 `all | none` 两种模式。`all` 在 observation 的事件 cursor 上计算所有已注册 projection;`none` 完全不触碰 projection 状态。系统不存在按 key preparation 的状态、`projectionKeys` 模式或额外的 `viewedState`/`viewedValue` cache。发布方可以按 audience 筛选已完成的值,但底层 observation 不会处于只算完部分 projection 的状态。
@@ -72,7 +72,7 @@ Registry 拥有 fold state;各领域拥有自己的 `init`、`apply`、`view`
语料库 list 仍是独立的轻量操作。`listSessions()` 返回 live-preferred header,而不物化每份日志。Session list 先读取 live projection 状态或持久 projection-cache row。Subagent 发现通过精确 observation 读取父目录 projection。当 cache 无法判断 Session 是否为空,且该 Session 拥有的独立产物未超过配置的小日志限制时,Session list 可以执行一次完整 observation;大型或不可读的 cache miss 仍以 hints 未知但 row 可见的方式返回。
`session.follow` 发布必需的 opening snapshot,其中包含 header、cursor、首个事件窗口和完整 projection baseline。重连使用另一份完整 snapshot 替换上一 generation。`session.page` 仅用于旧历史读取与 gap repair。只读 observation 不激活 Agent;只有普通 follow 可以保留 prepared observation,并在 opening snapshot 已交付后请求 promotion。
`session.follow` 发布必需的 opening snapshot,包含 header、cursor、初始事件窗口与完整 projection baseline。重连通过另一份完整快照替换之前的 generation。`session.page` 支持当前或固定切点的历史读取、旧历史分页及缺口修复。只读 Observation 不激活 Agent;只有显式启用激活的普通 Follow 可以在开场计算完成后、交付之前 retain prepared observation 并请求提升。[快照与订阅决策](2026-10-21-session-history-stream-and-snapshot.zh.md)定义 Controller 组合和纯订阅语义。
### 读取 audience
@@ -82,9 +82,10 @@ Registry 拥有 fold state;各领域拥有自己的 `init`、`apply`、`view`
|---|---|---|---|
| `session.list` | Corpus header、live state 和 cached row;有界小日志 fallback | 部分 hints,或一次完整小日志 observation | 从不 |
| `session.search` | Corpus 鉴权加已配置 search provider | 结果列表不计算 | 从不 |
| `session.follow` | 一份精确 observation | 全算,并由 opening snapshot 携带 | 仅普通 cold Session,且在 snapshot 交付后 |
| `session.follow` | 一份精确 observation | 全算,并由 opening snapshot 携带 | 仅 `activate: true` 的普通 cold Session,且在开场计算完成后、交付前 |
| `session.page` | 一份精确 observation | 不计算,但 projection-backed subagent 鉴权除外 | 从不 |
| Attachment 与 fork source | 一份精确 observation | 鉴权不要求时不计算 | source 从不激活 |
| Fork source | 一份精确 observation | 鉴权不要求时不计算 | source 从不激活 |
| Attachment | 按[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)直接读取存储 | 不计算 | 从不 |
| Subagent list 与 continuation | Listing 观察父目录;continuation 观察目标 | 全算;listing 消费目录值,continuation 消费身份与继承值 | Listing 从不;continuation 遵循显式命令语义 |
### 可回放的 Client 事实归 projection 所有
@@ -171,7 +172,7 @@ Client 本地交互状态也继续留在本地:loading 和 error 状态、打
## 验证
Persistence 与 SessionQuery 测试固定共享冷加载、取消、live-source race、retained observation、dispose 和 all-or-none projection 计算。Session Controller 与 Gateway 测试固定 snapshot-first opening、replacement reconnect、旧分页读取、gap repair、list-cache hints、小日志有界 fallback,以及 snapshot 交付后的 promotion。
Persistence 与 SessionQuery 测试固定共享冷加载、取消、live-source race、retained observation、dispose 和 all-or-none projection 计算。Session Controller 与 Gateway 测试固定 snapshot-first opening、replacement reconnect、旧分页读取、gap repair、list-cache hints、小日志有界 fallback,以及开场计算完成后的 promotion。
Client 测试固定 higher-sequence-wins projection store、title 更新、model catalog 与 selection readiness、preset roster refresh 与 Session 专属选择,以及不会短暂展示离线状态的 subagent loading。Subagent 测试固定父目录顺序、递归遍历、分支诊断、取消、fork 隔离,以及 listing 期间不激活 Agent。
@@ -179,7 +180,7 @@ Client 测试固定 higher-sequence-wins projection store、title 更新、model
**由各消费方继续解析数据源。** 否决,因为每个调用方都需要重复实现 live race、persistence error mapping、preparation lifetime、cancellation 和 projection cut,既会重复工作,也会产生不一致结果。
**每次精确读取都激活 Agent。** 否决,因为 list、history、attachment、search 与 subagent inspection 都是读取操作。Activation 会加载插件并改变进程状态,也没有适合分页或 catalog 读取的自然退出点。
**每次精确读取都激活 Agent。** 否决,因为 list、history、search 与 subagent inspection 都是读取操作。Activation 会加载插件并改变进程状态,也没有适合分页或 catalog 读取的自然退出点。
**只 prepare 被请求的 projection key。** 否决,因为只完成部分 projection 的 Session 会增加一种生命周期状态,所有 cache、restore、plugin registration 和调用路径都必须追踪它。Projection unit 数量少且为纯函数;精确 observation 计算全部已注册 unit,比为了 `O(E*k)` 而维护部分状态、取代 `O(E*P)` 完整状态更简单。
@@ -30,8 +30,8 @@
en: 9d2d50cb76754b74
zh: 9ceed3652475f18d
/agent-note-historical-session-reads-prepare-before-write-publication/decision/follow-and-agent-promotion:
en: 692c29db3e7ab07e
zh: 7da0cfdbc80f407d
en: 46da45b9b63e7298
zh: 3d55099479a80bd9
/agent-note-historical-session-reads-prepare-before-write-publication/problem-to-solution-mapping:
en: e067e187cd4d0a8c
zh: b0c79b635a637296
@@ -102,7 +102,7 @@ No external caller can append before the handle exists. `append`, `flush`, and `
### Follow and Agent promotion
`session.follow` opens history through the read path, restores the Session and projections, emits the opening snapshot, and then starts Agent promotion. Agent resume uses write open, so it waits for publication before the Agent accepts a new turn. History visibility and write readiness are separate timing points without introducing an unpublished append state.
`session.follow` opens history through the read path, restores the Session and projections, starts Agent promotion from the separately retained Observation when the caller requests activation, and then delivers the opening snapshot. Agent resume uses write open, so it waits for publication before the Agent accepts a new turn. History visibility and write readiness are separate timing points without introducing an unpublished append state.
## Problem-to-solution mapping
@@ -102,7 +102,7 @@ Handle 返回前,外部 caller 无法 append。因此 `append`、`flush` 与 `
### Follow 与 Agent promotion
`session.follow` 通过 read path 打开历史、恢复 Session 与 projections、发出 opening snapshot,然后启动 Agent promotion。Agent resume 使用 write open,因此会在 Agent 接收新一轮对话前等待 publication。历史可见与写入就绪成为两个明确时间点,同时不引入 unpublished append state。
`session.follow` 通过 read path 打开历史、恢复 Session 与 projections,在调用方请求激活时先用单独 retain 的 Observation 启动 Agent promotion,再交付 opening snapshot。Agent resume 使用 write open,因此会在 Agent 接收新一轮对话前等待 publication。历史可见与写入就绪成为两个明确时间点,同时不引入 unpublished append state。
## 问题与方案对照
@@ -39,8 +39,8 @@
en: ef015f605f7b00ab
zh: eee9c79faebf3dff
/agent-note-workspace-file-service/alternatives-considered:
en: 8eee658526db4465
zh: 4a655accf6a5c08a
en: c750d88e0e746a99
zh: 9e904ad4172fda49
/agent-note-workspace-file-service/consequences:
en: 246bb7aed62f6c9b
zh: debf6d4129ee477b
@@ -117,7 +117,7 @@ The [resource model](2026-09-05-client-resource-model.md) owns `ctx.resources`,
**Serving navigable workspace documents.** Rejected on origin grounds; the [binary transfer](2026-09-17-workspace-file-binary-transfer.md) returns multipart data while HTML remains isolated in a Blob iframe.
**Log-reachable or workspace-contained authorization for file reads.** The one precedent that sends file content over the wire, command attachments, authorizes only files that appear in the session log. That excludes typed paths, while workspace containment excludes readable files elsewhere on the Session backend. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) instead makes the backend's read decision authoritative and keeps containment only for workspace-shaped operations.
**Log-reachable or workspace-contained authorization for file reads.** Requiring a Session-log reference excludes typed paths, while workspace containment excludes readable files elsewhere on the Session backend. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) makes the backend's read decision authoritative and keeps containment only for workspace-shaped operations. Image attachment reads separately follow the [store-level access rule](2026-10-23-store-scoped-image-reads.md).
**Whole-file read and slice for the byte window.** The interim form of `readBytes` read the file from its start to the window's end through `readBytes(target, signal, offset + length)` and sliced. It cannot read a window of a file longer than that end — the seam refuses such a file as too large — so no window could ever report `eof: false`, which contradicts the reason the method exists. Rejected in favour of the `readByteRange` seam, whose bound is the window.
@@ -117,7 +117,7 @@ Client 导出向 `ctx.resources` 注册一个 `ResourceProvider<'file'>`,存
**提供可导航的工作区文档。** 因源隔离问题不采用;[二进制传输](2026-09-17-workspace-file-binary-transfer.zh.md)返回 multipart 数据,HTML 仍隔离在 Blob iframe 中。
**文件读取采用“日志可达”或工作区包含授权。** 唯一把文件内容送过线路的先例——命令附件——只授权出现在会话日志里的文件,这会排除手输路径;工作区包含则会排除 Session 后端其他位置的可读文件。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)改为以后端读取决策为准,只对工作区形态的操作保留包含限制。
**文件读取采用“日志可达”或工作区包含授权。** 要求 Session 日志引用会排除手输路径;工作区包含则会排除 Session 后端其他位置的可读文件。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)以后端读取决策为准,只对工作区形态的操作保留包含限制。图片附件读取另行遵循[存储范围的访问规则](2026-10-23-store-scoped-image-reads.zh.md)。
**为字节窗口整文件读取再切片。** `readBytes` 的临时形态经 `readBytes(target, signal, offset + length)` 从文件开头读到窗口末端再切片。它读不了比该末端更长的文件的窗口——seam 会以过大拒绝这样的文件——因此没有任何窗口能报告 `eof: false`,与该方法存在的理由相悖。被否,改为以窗口为界的 `readByteRange` seam。
@@ -15,8 +15,8 @@
en: eced414858f08ef9
zh: 40639593b0d5bb6f
/agent-note-fatal-diagnostics-and-desktop-crash-reports/relationship-to-the-desktop-logging-design:
en: 7dc438912d10574a
zh: 07d05f9f17043d67
en: ca4a912437c7b02e
zh: 2c7953ce5e8c196f
/agent-note-fatal-diagnostics-and-desktop-crash-reports/testing:
en: 864a8e71e3b3378b
zh: a71807db24d9409c
@@ -32,7 +32,7 @@ This partially supersedes the [native Desktop fatal recovery](2026-09-15-desktop
## Relationship to the Desktop logging design
The Desktop local logging design (a Worker-owned rolling JSONL log with a closed event vocabulary, redaction, and rate limits) is a continuous-log design and remains future work. It stated that Host stderr and renderer console output are never persisted and that errors reach the log only as fixed categories. This decision carves out one exception: the one-time crash report of a fatal failure keeps the raw error and the retained stderr and console tails, because that raw content is what both field diagnoses needed and the report is bounded (the error section is cut at 256 KiB, the Host diagnostic at 64 KiB, the renderer console tail at 64 KiB), local, owner-only, and written only when the application is already showing its fatal dialog. The dialog names the file so a user knows what they would be sharing. The continuous-log privacy posture is unchanged for anything that is not a crash report.
Desktop continuously persists a bounded plugin-management journal with whitelisted facts, two rotating segments and a bounded write queue; its budgets and failure guarantees belong to the [Desktop README](../../../../apps/desktop/README.md). It excludes raw installation specs, error text and package-manager output. The broader Worker-owned continuous log remains deferred. Fatal crash reports independently retain raw errors and bounded stderr and renderer-console tails because these contain the field-diagnosis evidence; files are local and owner-only where supported. An isolated Worker appends bounded management history after the basic report is saved, preserving access to the basic report when collection fails or is still running. Recent operations provide context, not causal attribution.
## Testing
@@ -32,7 +32,7 @@ macOS 上,启动审计把一组 Web 客户端行列为 `import failed (see con
## 与 Desktop 日志体系设计的关系
Desktop 本地日志设计(Worker 独占写入的滚动 JSONL 日志、封闭事件词汇、脱敏与限流)是持续日志设计,仍是未来工作。它规定 Host stderr 与渲染进程 console 输出永不持久化、错误只以固定分类进入日志。本决定划出一个例外:致命失败的一次性崩溃报告保留原始错误以及保留的 stderr 与 console 尾部,因为两次现场定位需要的正是这些原始内容,而报告有界(error 段截至 256 KiB、Host 诊断 64 KiB、渲染进程 console 尾部 64 KiB)、本地、仅所有者可读,且只在应用已经弹出致命对话框时写入。对话框标明文件名,用户知道自己会分享什么。任何非崩溃报告的内容仍遵循持续日志的隐私姿态。
Desktop 持续保存有界的插件管理日志,使用事实白名单、两个轮换文件段和有界写入队列;预算及失败保障由 [Desktop README](../../../../apps/desktop/README.zh.md) 定义。日志不包含原始安装 spec、错误文本或包管理器输出。更广泛的 Worker 独占持续日志仍属延期工作。致命崩溃报告独立保留原始错误以及有界的 stderr 和渲染进程 console 尾部,因为这些内容包含现场定位证据;文件保存在本地,并在平台支持时仅所有者可读。独立 Worker 在基本报告保存后追加有界管理历史,收集失败或尚未结束时仍可获取基本报告。近期操作提供上下文,不构成因果归因。
## Testing
@@ -9,11 +9,11 @@
en: e42db40b879fdbf4
zh: 6017da9c4da17835
/agent-note-node-ptc-execution-modes-and-in-memory-state/decision:
en: d2d08c54c6520f02
zh: 520a9b3421ff5c65
en: 7b5808a31493ac1e
zh: 8d9c698c41dbf18e
/agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered:
en: 396157a9fc293198
zh: a061f05b4423e26f
/agent-note-node-ptc-execution-modes-and-in-memory-state/consequences:
en: 9b9172f4aafe907f
zh: 022a6bd52d7caf05
en: 56fa39e2958afdff
zh: d04f539437d0c00d
@@ -12,7 +12,7 @@ Interactive automation retains application objects, imported modules and helper
The existing `@deepseek-ai/dsh-ptc-runtime-node` plugin selects its execution mode through `executionMode`. The default `per-call` mode starts a fresh process under the configured file policy. Opt-in `persistent-in-memory` mode keeps a Node REPL process per explicit, object-identity state owner. Both modes provide the same `ctx.ptcRuntime` service. PTC uses the live Agent as owner and awaits release during its context disposal. Changing the configuration reloads the provider and releases its processes. The [sandboxed Node decision](2026-09-11-sandboxed-node-ptc-runtime.md) owns per-call confinement; the [PTC foundation](../feature/2026-06-15-ptc.md) owns tool dispatch and logged model requests.
Mode names describe state retention rather than a process implementation or source syntax. `per-call` retains state for one invocation; `persistent-in-memory` retains it across invocations until the process or owner ends. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation.
The `per-call` and `persistent-in-memory` names describe their fixed state-retention policies: one invocation or across invocations until the process or owner ends. The [Script evaluation decision](2026-10-20-ptc-script-evaluation-and-retention.md) extends these modes with independently configured syntax and retention. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation.
One npm package and one plugin entry keep existing installation and loading paths stable. Communication, binding proxies, JSON encoding and output limits remain package-local modules. The Node provider delegates retained process ownership to an internal execution object, which registers no additional Cordis service. Per-call and in-memory execution keep their distinct lifecycle rules. `programFormat` describes source evaluation independently of retention: a REPL need not retain state. The runtime owns syntax, completion and retention instructions through `executionInstructions`; tools own call arguments, SDK declarations and image attachment. Workflow uses `programFormat` to wrap its program and refuses restricted file policies when the selected runtime cannot enforce them.
@@ -34,4 +34,4 @@ A realm inside the Harness process shares process lifetime with model code and c
Selecting `persistent-in-memory` retains execution state; the [permission decision](2026-10-08-persistent-ptc-sandbox.md) defines its file restrictions. Nested tools keep their normal authorization and logging. Memory and native handles may disappear without a Harness restart. The model must recover from reference or resource errors; the runtime never retries a program automatically.
An idle owner retains a process with no expiration timer. Callers release owners explicitly; ownerless service calls use temporary processes. Programs use REPL statements and a final expression rather than top-level return, and calls for one retained owner cannot overlap. Tool schemas and program guidance follow the selected mode.
An idle owner retains a process with no expiration timer. Callers release owners explicitly; ownerless service calls use temporary processes. The `persistent-in-memory` mode uses REPL statements and a final expression rather than top-level return, and calls for one retained owner cannot overlap. Tool schemas and program guidance follow the selected mode.
@@ -12,7 +12,7 @@ Status: implemented
现有 `@deepseek-ai/dsh-ptc-runtime-node` 插件通过 `executionMode` 选择执行模式。默认的 `per-call` 模式按配置的文件策略启动新进程。显式启用的 `persistent-in-memory` 模式为每个以对象身份标识的状态所有者保留一个 Node REPL 进程。两种模式都提供同一个 `ctx.ptcRuntime` 服务。PTC 使用存活的 Agent 作为所有者,在其上下文销毁时等待释放。修改配置会重载提供方并释放其进程。[Node 沙箱决策](2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责逐次执行的文件约束,[PTC 基础决策](../feature/2026-06-15-ptc.zh.md)负责工具分派与模型请求日志。
模式名称描述状态保留方式,不绑定进程实现或代码语法。`per-call` 只为一次调用保留状态;`persistent-in-memory` 跨调用保留状态,直到进程或所有者结束。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。
`per-call` 和 `persistent-in-memory` 名称描述各自固定的状态保留策略:只保留一次调用,或跨调用保留至进程或所有者结束。[Script 求值决策](2026-10-20-ptc-script-evaluation-and-retention.zh.md)在这两种模式之外增加独立配置的语法与保留方式。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。
一个 npm 包和一个插件入口保持现有安装与加载路径稳定。通信、绑定代理、JSON 编码和输出限制继续作为包内模块复用。Node 提供方将保留进程的所有权交给内部执行对象,该对象不注册额外的 Cordis 服务。逐次执行和内存保留各自管理不同的生命周期。`programFormat` 描述代码求值形式,与状态保留独立:REPL 不必跨调用保留状态。运行时通过 `executionInstructions` 负责语法、完成值和状态保留指引;工具层负责调用参数、SDK 声明和图片附加。工作流根据 `programFormat` 包装程序;所选运行时无法执行受限文件策略时,工作流拒绝执行。
@@ -34,4 +34,4 @@ Harness 进程内的独立执行上下文与模型代码共享进程生命周期
选择 `persistent-in-memory` 会保留执行状态;[权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)定义其文件限制。嵌套工具仍遵循原有授权和日志规则。即使 Harness 没有重启,内存和原生句柄也可能丢失。模型需要从引用或资源错误中恢复,运行时不会自动重试程序。
空闲所有者保留一个没有过期计时器的进程。调用方显式释放所有者,没有所有者的服务调用使用临时进程。程序使用 REPL 语句和末尾表达式,不支持顶层 return;同一保留所有者的调用不能重叠。工具 schema 和程序指引跟随所选模式。
空闲所有者保留一个没有过期计时器的进程。调用方显式释放所有者,没有所有者的服务调用使用临时进程。`persistent-in-memory` 模式使用 REPL 语句和末尾表达式,不支持顶层 return;同一保留所有者的调用不能重叠。工具 schema 和程序指引跟随所选模式。
@@ -36,8 +36,8 @@
en: d50ae22978165c57
zh: 8c1fcfb7dc2d3367
/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/endpoint-resources:
en: 056a141b31270cba
zh: 3f6caafb3a13c192
en: 582f5f527ecc58c8
zh: 4a4b68361de2dcf0
/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/roles-bindings-and-policies-deepseek-ai-dsh-api-remote-access:
en: e57f396239ea9f56
zh: ddb26278b1521ceb
@@ -241,7 +241,7 @@ The table lists the endpoints #3854 viewers use and where their resources come f
| `llm/listProviders` | `global` | no resource | no |
| `commands/list` | session: `args.agentId` (the Agent lookup's wire field) | Agent lookup `resource: 'session'` | no |
| `goals/get` | session: `args.agentId` | Agent lookup `resource: 'session'` | no |
| `session/attachment` | session: `args.request.sessionId` | default resolver | no |
| `session/attachment` | session: `args.request.sessionId` | default resolver | no: a grant on one Session permits reads from the whole attachment store |
| `skills/list` | session: `args.request.sessionId` | default resolver | no |
| `session/fork` | session: `args.request.sessionId` | default resolver | no |
| `session/prompt` | session: `args.request.sessionId` | default resolver | no |
@@ -251,6 +251,8 @@ The table lists the endpoints #3854 viewers use and where their resources come f
| `session/follow` | same as above | default resolver | no |
| `remoteAccess/follow` | `global` | no resource; remote-access allows it for every principal | no |
For `session/attachment`, `sessionId` identifies the resource for the Gateway check; it does not constrain which image may be read. Once that check permits the call, an image may belong to another Session or no Session, and the handler does not check whether the supplied Session exists. Policy authors must treat this action as access to the whole attachment store, as defined by the [image access rule](2026-10-23-store-scoped-image-reads.md).
A subagent address reads the child transcript, so its resource is the child Session. A Client rereads the projections of known Sessions after a reconnect, including the parent of a subagent Session; a reader without a grant on that parent has its projection read refused. Whether a grant on a parent Session covers its subagent children is the policy's decision, that is, whether it gives a binding for the child Session; the generic layer derives no parent resource.
Methods that need no non-owner access declare nothing, and a method no role lists is refused. The request fields of subagent `prompt` are `parentSessionId` / `childSessionId`, so automatic resolution finds no Session and resolves it to `global`; it must therefore stay out of every `global` role. `session/search` filters its hits per Session inside the method. `subagents/list` is not a Remote endpoint (`SubagentRuntime.list()` carries no `@Remote`).
@@ -241,7 +241,7 @@ export function RemoteScope<This extends object, Args extends unknown[], Result>
| `llm/listProviders` | `global` | 无资源 | 否 |
| `commands/list` | session:`args.agentId`(Agent lookup 的 wire 字段) | Agent lookup `resource: 'session'` | 否 |
| `goals/get` | session:`args.agentId` | Agent lookup `resource: 'session'` | 否 |
| `session/attachment` | session:`args.request.sessionId` | 默认 resolver | 否 |
| `session/attachment` | session:`args.request.sessionId` | 默认 resolver | 否:一条 Session 上的授权允许读取整个附件存储 |
| `skills/list` | session:`args.request.sessionId` | 默认 resolver | 否 |
| `session/fork` | session:`args.request.sessionId` | 默认 resolver | 否 |
| `session/prompt` | session:`args.request.sessionId` | 默认 resolver | 否 |
@@ -251,6 +251,8 @@ export function RemoteScope<This extends object, Args extends unknown[], Result>
| `session/follow` | 同上 | 默认 resolver | 否 |
| `remoteAccess/follow` | `global` | 无资源;remote-access 对任何 principal 放行 | 否 |
对于 `session/attachment`,`sessionId` 指定 Gateway 检查的资源,不限制可读取哪张图片。该检查放行后,图片可以属于其他 Session 或不属于任何 Session,处理函数也不检查请求中的 Session 是否存在。policy 作者必须把此 action 视为整个附件存储的读取权限,具体规则见[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)。
subagent 地址读取的是子会话转录,因此其资源是子会话。Client 在重连后会重新读取已知会话的 projections,其中包括 subagent 会话的父会话;没有该父会话授权的读者,其 projection 读取被拒。父会话的授权是否覆盖其 subagent 子会话由 policy 决定,即是否为子会话给出 binding;通用层不推导父资源。
不需要非 owner 访问的方法不做任何声明,没有 role 列出它即被拒。subagent `prompt` 的请求字段为 `parentSessionId` / `childSessionId`,自动解析不到会话,解析为 `global`,因此不得放进任何 `global` 级 role;`session/search` 在方法内按会话逐项过滤命中。`subagents/list` 不是 Remote 端点(`SubagentRuntime.list()` 未标 `@Remote`)。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-10-20-ptc-script-evaluation-and-retention.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.md
/agent-note-ptc-script-evaluation-and-state-retention:
en: e222c8cda4cee561
zh: 9e624e5643ad2984
/agent-note-ptc-script-evaluation-and-state-retention/problem:
en: 2da844a2a4e1903b
zh: 3b74ba7c1bcdae89
/agent-note-ptc-script-evaluation-and-state-retention/decision:
en: 4beff8714f1d1555
zh: a22019a90989eb66
/agent-note-ptc-script-evaluation-and-state-retention/alternatives-considered:
en: 8ee3f3c7e04b4f25
zh: ac604fa8debcfebf
/agent-note-ptc-script-evaluation-and-state-retention/consequences:
en: 64b7d3a5d247d82b
zh: 6f94d6b37f1ea4c1
@@ -0,0 +1,33 @@
# Agent Note: PTC Script evaluation and state retention
Status: implemented
English | [中文](2026-10-20-ptc-script-evaluation-and-retention.zh.md)
## Problem
Program syntax and memory lifetime answer different questions. A consumer may need Script declarations and completion values while requiring either a fresh environment or retained references. Inferring memory lifetime from REPL syntax prevents that choice.
## Decision
The Node provider adds `executionMode: vm-script` and a separate `scriptPersistence` option, defaulting to false. `PtcRuntime.programFormat` describes accepted syntax; `retainsState` describes owner-scoped memory. Consumers use the latter for persistence controls and guidance. Existing `per-call` and `persistent-in-memory` configurations retain their meanings and defaults.
This extends the mode-naming decision in [best-effort persistent PTC](2026-09-23-best-effort-persistent-ptc.md), whose ownership, non-durability and recovery decisions remain active. The Node provider selects its evaluator once and shares managed process mechanisms across temporary and retained lifetimes. AsyncFunction, REPL and Script remain separate evaluator implementations, so process reuse does not define syntax.
VM Script uses a separate realm inside the managed child process. Top-level await uses the Node.js v26.6.0 REPL transform, with Acorn and acorn-walk supplying parsing and traversal. Detection precedes native compilation because non-strict Script can compile `await` as an identifier. The adapted visitors traverse computed method keys without entering method bodies. The source retains upstream attribution and license; the [package reference](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) owns declaration and realm limitations.
## Alternatives considered
**Replace existing modes with Script.** This would change async-function return syntax and REPL declaration behavior for existing consumers. An additional mode preserves those choices while exposing Script semantics.
**Encode syntax and retention in every mode name.** Separate names for fresh and retained Script would repeat syntax choices and encourage consumers to infer persistence from the format. One Script mode and an explicit retention option keep each fact separately observable.
**Use native Script without await conversion.** Native Script cannot evaluate top-level await. Parsing only after native compilation fails also misses valid programs where `await` compiles as an identifier. The Node transform supplies retained declarations and completion handling while keeping its known semantic tradeoffs explicit.
**Own a generic AST walker.** A local walker duplicates traversal provided by acorn-walk and must independently track new Acorn nodes. The maintained walker removes that implementation; only the evaluation-specific visitors remain local.
## Consequences
Script state is best-effort process memory, with the same explicit owner release and sandbox invalidation rules as retained REPL execution. It is neither serialized nor reconstructed by rerunning earlier programs. An uncaught callback exception or unhandled rejection terminates the Script process; programs must await asynchronous work.
The published format union now includes `script`, and custom retained providers must report `retainsState`. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.md) describes consumer migration. Source deployments need the evaluator modules and Acorn packages; private process bundles include those dependencies.
@@ -0,0 +1,33 @@
# Agent Note: PTC Script 求值与状态保留
Status: implemented
[English](2026-10-20-ptc-script-evaluation-and-retention.md) | 中文
## 问题
程序语法和内存生命周期回答不同的问题。消费者可能需要 Script 声明和完成值,同时要求全新环境或保留引用。根据 REPL 语法推断内存生命周期会阻碍这种选择。
## 决策
Node 提供方增加 `executionMode: vm-script` 和独立的 `scriptPersistence` 选项,后者默认为 false。`PtcRuntime.programFormat` 描述接受的语法,`retainsState` 描述按所有者保留的内存。消费者通过后者提供持久化控制和指引。已有 `per-call` 和 `persistent-in-memory` 配置保留原有含义与默认值。
本决策扩展[尽力保留 PTC 状态](2026-09-23-best-effort-persistent-ptc.zh.md)中的模式命名决策;其中的所有权、非持久存储及恢复决策仍然有效。Node 提供方一次性选择求值器,并在临时和保留生命周期之间共用受管进程机制。AsyncFunction、REPL 和 Script 仍是独立的求值器实现,进程复用不决定语法。
VM Script 在受管子进程内使用独立 realm。顶层 await 使用 Node.js v26.6.0 REPL 转换,由 Acorn 和 acorn-walk 提供解析与遍历。在原生编译之前检测 await,因为非严格 Script 可以将 `await` 编译为标识符。适配后的 visitor 遍历方法的计算属性名,但不进入方法体。源码保留上游署名和许可;[包参考](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)负责声明与 realm 限制。
## 考虑过的替代方案
**用 Script 替换已有模式。** 这会改变现有消费者的异步函数返回语法和 REPL 声明行为。增加模式可在提供 Script 语义的同时保留已有选择。
**在每个模式名称中同时编码语法与保留方式。** 为全新和保留状态的 Script 分别命名,会重复语法选项,并鼓励消费者根据格式推断持久化。一个 Script 模式加显式保留选项,让两项事实可以分别观测。
**仅使用原生 Script,不转换 await。** 原生 Script 无法求值顶层 await。只在原生编译失败后解析,也会漏掉将 `await` 编译为标识符的有效程序。Node 转换提供声明保留和完成值处理,同时明确其已知语义取舍。
**自行维护通用 AST 遍历器。** 局部遍历器重复 acorn-walk 已提供的遍历功能,还必须独立跟踪新增 Acorn 节点。使用维护中的遍历器可以删除这部分实现,只保留与求值相关的局部 visitor。
## 影响
Script 状态是尽力保留的进程内存,遵循与保留 REPL 相同的显式所有者释放和沙箱失效规则。状态不会序列化,也不会通过重新执行旧程序重建。未捕获的回调异常或未处理的 Promise 拒绝会终止 Script 进程;程序必须等待异步工作。
公开格式联合类型现包含 `script`,自定义保留状态的提供方必须报告 `retainsState`。[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.zh.md)说明消费者迁移。源码部署需要求值器模块和 Acorn 包,私有进程 bundle 包含这些依赖。
@@ -0,0 +1,28 @@
# Bilingual-pair consistency record for 2026-10-21-session-history-stream-and-snapshot.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation:
en: 0c9a7bc6591feb16
zh: 3606a2c1caffd36f
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/problem:
en: ac1583e7ae1377f8
zh: c60bdbda9ee89144
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision:
en: 45c63df5dac389eb
zh: d72a5bcb94de22f1
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/reads-and-subscriptions:
en: 38df4f3c4fba2cc9
zh: a34f3376faf26f0c
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/follow-ordering-and-ownership:
en: 352ff87a3e9cd110
zh: 4ac6366cecfc08a3
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/state-and-wait:
en: a87c7427582e6b03
zh: b28d2a73b36eb27f
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/alternatives-considered:
en: c5fb06ab9df9e7ad
zh: b20adf151018111c
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/consequences:
en: dc1da262b4911a31
zh: 2a4e503696fc477b
@@ -0,0 +1,59 @@
# Agent Note: Session snapshots, passive subscriptions, and Web aggregation
Status: implemented
English | [中文](2026-10-21-session-history-stream-and-snapshot.zh.md)
## Problem
A point read, an event subscription, and a Web conversation opening have different lifetimes. Combining them inside one history controller makes passive observation perform unnecessary reads and gives each aggregate its own acquisition logic. Reading before subscribing also creates a gap that requires another read to repair. The APIs need independent operations that can compose without losing events or duplicating ownership.
## Decision
`SessionController` is the single Session Remote Service. It owns ordinary `HistoryController`, `StateController`, and `WebController` instances, not three additional Cordis Services or Remote namespaces. The implementation separates six operations: history snapshot and observation, projection snapshot and observation, and state snapshot and observation. Follow and Wait compose those capabilities for their callers; the existing `page` entry forwards to the history reader.
### Reads and subscriptions
History reads return chronological records, `hasMore`, and an inclusive cursor. An omitted `throughSeq` selects the observed log end; `beforeSeq` selects older records without changing that read cut. Projection reads return exact sequenced values, sequence-free cache hints when migration is required, or null when the Session is absent. Live projection reads avoid persistence metadata access.
`usingObservation({ sessionId, projection }, signal, callback?)` acquires the existing disposable SessionObservation. A callback borrows it until the callback settles; without a callback the caller owns disposal. Ordinary history, state, and Wait output reads do not request projections. Follow, exact projection reads, and subagent history descriptor validation request them. No read activates an Agent implicitly.
`observeEvent` and `observeProjections` install listeners without acquiring an Observation. Their initial `ready` confirms subscription, not a snapshot cursor, existence, parent-child validity, or Agent readiness. History establishes continuity from its first received event; projection updates replace individual keys and may share a sequence number. `observeState` instead begins with a complete state read and coalesces later Session and Agent invalidations.
History, history observation, and Follow accept Address requests; projection and state operations accept Session IDs. All internal readers and listeners use Session IDs. History and Follow validate Address against their opening Observation at the Controller layer, including the existing subagent descriptor rules. Pure history observation does not acquire a read for entity validation. Gateway resource authorization remains independent: the registered Session resolver extracts the target ID from the request before access is decided.
### Follow ordering and ownership
Follow installs history and optional assistant listeners first, then acquires one projected Observation. It captures the assistant baseline and binding-local arrival ordinal synchronously, sets both cuts, publishes the opening snapshot, and consumes the shared output queue. History notifications at or before the snapshot cursor and assistant notifications at or before the ordinal are discarded at consumption. Later notifications remain ordered without a second history read, background merge pumps, or a tail repair introduced by the opening itself.
`session/created` contributes constructor seed events through the same history buffer. The adapter retains the supplied Session and its captured end position, then reads that in-memory prefix when consumed; it does not acquire another Observation. Each binding owns its subscriptions; a shared output queue belongs to Follow rather than to either listener.
Follow activates only when the caller passes `activate: true`; the Web Client does so explicitly. Background promotion starts once the opening is computed and before it is delivered, and does not promise Agent readiness. Ordinary promotion reuses the existing Agent controller and receives a separately retained Observation. Either Follow releases its opening Observation once the opening is computed, before yielding it; activation continues on the separately retained lease, so the cold entry's reference count drops to that lease alone. Subagent Sessions do not use ordinary promotion.
### State and Wait
State contains the event cursor, active and running flags, the complete readable queue or null, and pending-input kinds. It exposes neither a header nor an internal revision. Gateway owns unsettled Remote events; State samples their detached metadata and classifies approval, question, or other input without copying a request registry.
Wait evaluates complete states, confirms active-Agent quiescence with `whenIdle`, and rejects stale observations using listener-local revisions and Agent/Session identity checks. Session and Agent events wake reads immediately; while waiting, a one-second recheck detects pending input that produces no such event. This avoids adding a Gateway change event, at the cost of polling and bounded sampling delay rather than instantaneous notification. `observeState` does not poll, so pending-only changes need another state invalidation to become visible there.
Wait returns idle, input-required, or timeout with the last state it accepted and bounded assistant output. Output contains only `assistant/message` records in `(afterSeq, state.cursor]`, newest first, and reports truncation only when another eligible record exists. The caller's cancellation signal controls that output read independently of the expired wait deadline. A wait that accepts no state before its deadline fails instead of inventing a state.
## Alternatives considered
**Read history, then subscribe and repair the gap.** Subscription-before-read already captures opening-time increments. A second read adds acquisition and replay obligations without improving that ordering.
**Give pure subscriptions an Observation or ready cursor.** These values conflate subscription readiness with an independently selected read cut. Callers that need both subscribe and buffer first, then read and discard covered increments.
**Keep separate Remote Services for the implementation controllers.** The classes divide behavior, not external service identity. One Session Service owns their composition, resource policy, and Remote entry points.
**Have Gateway interpret pending input or emit Session status.** Gateway only owns Remote event transport and unsettled-event metadata. State owns classification; Wait's periodic sampling avoids adding a transport notification solely for Session waiting.
**Merge assistant and history with independent asynchronous pumps.** One caller-owned buffer retains cross-source arrival order without extra pump cancellation or queue ownership. Snapshot construction and per-binding buffering retain distinct lifetimes.
## Consequences
The standard reads and Web aggregate share one Observation acquisition path, while pure subscriptions remain read-free. The old combined History controller is removed; still-used pagination, validation, and wire helpers remain at their original path. Cancellation, consumer termination, failed opening reads, and Context disposal release subscriptions and owned leases without cancelling Agent execution.
The [Observation decision](2026-08-25-session-observations-and-projection-owned-client-state.md) remains the authority for exact read cuts and projection derivation. The [history and Remote transport decision](2026-08-18-session-history-and-event-transport.md) retains ownership of Client reconnection and transport lifetimes. This decision refines Session API composition rather than replacing either broader decision.
The migrated history, cold-read, and transport tests exercise the new classes, including cursor overlap, assistant ordinal cuts, sequence gaps, subagent validation, and teardown. Slow consumers can still retain queued notifications; silent dropping is not a supported recovery strategy. Independent completion-acknowledged activation is not implemented by these reads or by Follow's background activation option.
@@ -0,0 +1,59 @@
# Agent Note: Session 快照、纯订阅与 Web 聚合
Status: implemented
[English](2026-10-21-session-history-stream-and-snapshot.md) | 中文
## Problem
定点读取、事件订阅和 Web 会话开场具有不同的生命周期。把它们合并在同一个历史控制器中,会使被动观察执行不必要的读取,并让每个聚合各自维护获取数据的逻辑。先读后订阅还会产生需要再次读取来修复的缺口。接口需要相互独立的操作,使组合既不丢事件,也不重复资源所有权。
## Decision
`SessionController` 是唯一的 Session Remote Service。它持有普通的 `HistoryController`、`StateController` 和 `WebController` 实例,而不是额外的三个 Cordis Service 或 Remote namespace。实现分离六个操作:历史快照与观察、投影快照与观察、状态快照与观察。Follow 和 Wait 为调用方组合这些能力;已有的 `page` 入口转发到历史读取器。
### 读取与订阅
历史读取返回时间正序的记录、`hasMore` 和包含末项的游标。省略 `throughSeq` 时选择观察到的日志末尾;`beforeSeq` 只选择更早的记录,不改变读取点位。投影读取返回精确的有序值、需要迁移时无序号的缓存提示,或在 Session 不存在时返回 null。live 投影读取不访问持久化元信息。
`usingObservation({ sessionId, projection }, signal, callback?)` 获取已有的可释放 SessionObservation。有回调时租约借给回调直到其结束;无回调时由调用方释放。普通历史、状态及 Wait 输出读取不请求投影。Follow、精确投影读取和子会话历史 descriptor 校验请求投影。读取不会隐式激活 Agent。
`observeEvent` 和 `observeProjections` 安装监听而不获取 Observation。首个 `ready` 确认订阅生效,不代表快照游标、实体存在、父子关系有效或 Agent 就绪。历史从首个收到的事件建立连续性;投影更新替换单个键,多个更新可以共享序号。`observeState` 则从完整状态读取开始,并合并后续 Session 和 Agent 失效通知。
历史、历史观察和 Follow 接收 Address 请求;投影和状态操作接收 Session ID。所有内部读取器和监听器都使用 Session ID。History 和 Follow 在 Controller 层以开场 Observation 校验 Address,包括已有的子会话 descriptor 规则。纯历史观察不为实体校验获取读取。Gateway 资源授权与之独立:注册的 Session 解析器在访问判定前从请求提取目标 ID。
### Follow 顺序与所有权
Follow 先安装历史和可选 assistant 监听,再获取一份带投影的 Observation。它同步捕获 assistant 基线和绑定局部的到达序号,设置两种截断点,发布开场快照,然后消费共享输出队列。消费时丢弃序号不超过快照游标的历史通知,以及到达序号不超过截断点的 assistant 通知。后续通知保持顺序,无需第二次历史读取、后台合并任务,或由开场自身引入的尾部修复。
`session/created` 经同一历史缓冲提供构造期种子事件。适配器保留收到的 Session 及捕获的末尾位置,在消费时读取对应内存前缀,不获取另一份 Observation。每个绑定拥有自己的订阅;共享输出队列属于 Follow,而不是任一监听器。
只有调用方传入 `activate: true` 时 Follow 才激活;Web Client 显式传入该参数。后台提升在开场计算完成后、交付之前启动,不承诺 Agent 已就绪。普通提升复用已有 Agent controller,并接收单独 retain 的 Observation。两种 Follow 都在开场计算完成后、交付前释放开场 Observation;激活则继续使用单独 retain 的租约,因此冷 entry 的引用计数只剩那一份。子会话不走普通提升。
### 状态与 Wait
State 包含事件游标、active 与 running 标志、完整可读队列或 null,以及待输入种类。它不暴露 header 或内部 revision。Gateway 拥有未结算的 Remote 事件;State 采样独立元数据,将输入分类为 approval、question 或 other,不复制请求注册表。
Wait 判断完整状态,通过 `whenIdle` 确认活跃 Agent 已静止,并通过监听器局部 revision 和 Agent/Session 身份检查拒绝过时观察。Session 和 Agent 事件立即唤醒读取;等待期间每秒重查一次,检测没有产生上述事件的待输入请求。这避免新增 Gateway change 事件,代价是轮询和采样延迟,而非即时通知。`observeState` 不轮询,因此仅有 pending 变化时,需要另一项状态失效通知才会显示更新。
Wait 返回 idle、input-required 或 timeout,以及最后一次被接受的状态和有界 assistant 输出。输出仅包含 `(afterSeq, state.cursor]` 内从新到旧的 `assistant/message` 记录,只有存在另一条符合条件的记录时才报告截断。输出读取使用调用方的取消信号,不受已过期的等待截止信号控制。截止前没有任何状态通过校验的 wait 会失败,不构造虚假的状态。
## Alternatives considered
**先读历史,再订阅并修复缺口。** 先订阅后读取已经捕获开场期间的增量。第二次读取增加资源获取和重放责任,却不改善这个顺序。
**给纯订阅提供 Observation 或 ready 游标。** 这会混淆订阅就绪和独立选取的读取点位。需要两者的调用方先订阅并缓冲,再读取并丢弃已覆盖增量。
**为各实现 Controller 保留独立 Remote Service。** 这些类划分行为,而不是外部服务身份。一个 Session Service 拥有其组合、资源策略和 Remote 入口。
**让 Gateway 解释待输入状态或发送 Session status。** Gateway 只拥有 Remote 事件传输和未结算事件元数据。State 拥有分类;Wait 定期采样,避免仅为 Session 等待增加传输通知。
**用独立异步任务合并 assistant 与历史。** 调用方拥有的单个缓冲保留跨来源到达顺序,不引入额外任务取消或队列所有权。快照构造和各绑定缓冲仍保留不同生命周期。
## Consequences
标准读取和 Web 聚合共享同一 Observation 获取路径,纯订阅不读取数据。旧的合并 History controller 已删除;仍使用的分页、校验和 wire 辅助函数留在原路径。取消、消费者结束、开场读取失败和 Context 释放都会释放订阅及拥有的租约,而不取消 Agent 执行。
[Observation 决策](2026-08-25-session-observations-and-projection-owned-client-state.zh.md)仍拥有精确读取点位和投影派生规则。[历史与 Remote 传输决策](2026-08-18-session-history-and-event-transport.zh.md)继续拥有 Client 重连和传输生命周期。本决策细化 Session API 组合,而不取代上述更广泛的决策。
迁移后的历史、冷读取和传输测试覆盖新类,包括游标重叠、assistant 到达序号截断、序号缺口、子会话校验和释放。慢消费者仍可能积累队列通知;静默丢弃不是支持的恢复策略。这些读取以及 Follow 的后台激活选项均未实现独立的、确认完成后返回的激活接口。
@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-10-23-store-scoped-image-reads.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.md
/agent-note-image-reads-use-attachment-store-access:
en: 31c8a0d9016d99af
zh: 05db308dec85db67
/agent-note-image-reads-use-attachment-store-access/problem:
en: ff8886cfa4634163
zh: 46dfdd50638b64c2
/agent-note-image-reads-use-attachment-store-access/decision:
en: 439a3277ee3b169d
zh: c9f1e10254850844
/agent-note-image-reads-use-attachment-store-access/alternatives-considered:
en: 0c7a8319c0c91dc2
zh: 6b7b58b142839571
/agent-note-image-reads-use-attachment-store-access/consequences:
en: a46c3d951077ec7d
zh: 30a0cc5bcb681a21
/agent-note-image-reads-use-attachment-store-access/verification:
en: 89603b3a4c3e12df
zh: f1b01d166f399f87
@@ -0,0 +1,52 @@
# Agent Note: Image reads use attachment-store access
Status: implemented
English | [中文](2026-10-23-store-scoped-image-reads.zh.md)
## Problem
Historical image loading read the requesting Session and searched its event content for every uncached attachment. The search established that the Session referenced the image; it did not locate the bytes, whose storage path already follows from the content-addressed ID. This added work proportional to history length to each image read. The reported loading delay also involved uploads; this finding alone does not identify all of that delay.
## Decision
Session membership is not an image-access restriction. After connection authentication and Gateway permission checks authorize `session/attachment`, every caller may read any image in the same attachment store using a complete `ImageAttachmentRef`, including objects referenced only by other Sessions or not referenced at all. The request retains `sessionId` for the existing Session resource permission check. After that check passes, the handler does not require that Session to exist and does not return `session/not-found` solely because it is absent. No identity receives a separate history-scanning path.
The Client already holds the message's complete image reference and sends it as `attachment` beside `sessionId`. Session Controller delegates directly to the existing `AttachmentStore.readImage(ref)`. Its local provider validates the canonical ID, derives the path within its object directory, verifies SHA-256, and compares the actual format, byte length, width, and height with the supplied reference. A missing, unreadable, corrupt, or mismatched object rejects the operation. No Session history is needed to recover the reference.
The response preserves the supplied reference. Its optional `name` and `originalDimensions` are caller-supplied display information and are not verified against the stored object. The Client's existing historical-image cache continues to own per-Session results and object URLs; the Host adds no image-byte cache.
This rule narrows the readers covered by [Session observations](2026-08-25-session-observations-and-projection-owned-client-state.md) and the [history transport activation policy](2026-08-18-session-history-and-event-transport.md). [Workspace file reads](2026-09-05-workspace-files-service.md) keep their own filesystem authorization.
## Alternatives considered
**Keep a Session-to-image map or projection.** An index removes repeated scans but preserves an access restriction the product does not require, adding derivation, lifetime, and invalidation work.
**Issue signed image tickets.** Tickets add issuance and validation state for the same unnecessary Session-membership restriction.
**Optimize only owner reads.** That gives identities different image-access semantics and leaves the scan cost for permitted non-owner callers without a product requirement.
## Consequences
Knowing a valid image reference and having permission to invoke the endpoint for the supplied Session resource permits reading that object across Sessions. The local ID is the SHA-256 of normalized bytes. For known PNG, JPEG, or WebP bytes that admission preserves unchanged, a caller can calculate the ID, derive the format, byte length, and dimensions, and use an authorized read to test whether the object exists. The required reference fields need not come from a Session log.
Image isolation requires separate Host instances with separate `DSH_HOME` directories. The shipped composition uses one attachment store per Host and does not select a store by Session. Authentication, Gateway action/resource checks, fixed storage paths, digest verification, and explicit failures remain required.
Image reads no longer depend on history length or Session materialization. File reading, integrity verification, encoding, and transport still cost time; this change makes no claim about upload or model inference latency. Existing Session data and fork references need no migration.
## Verification
The read-path invariant is zero Session-history queries or traversal for attachment reads. Coverage must distinguish a permitted cross-Session image read from a denied Gateway call and exercise valid references, invalid IDs, mismatched intrinsic metadata, preserved optional display fields, missing and corrupt objects, old history pages, and inherited fork images. Performance evidence must separate historical scanning, storage work, and transport rather than attribute the entire reported delay to the scan.
The diagnostic is [`image-read.perf.ts`](../../../../packages/api/session-controller/tests/image-read.perf.ts), compiled by its [tsdown configuration](../../../../packages/api/session-controller/tests/image-read.perf.config.ts). The baseline worker pairs the pre-change controller with `{ sessionId, attachmentId: ref.attachmentId }`; the candidate worker pairs the current controller with `{ sessionId, attachment: ref }`. Both use the same image fixtures, workload, and output checks, and run against the same built Local store with `readImage(ref)` verification. From the candidate checkout root, compile and run:
```sh
pnpm exec tsdown --config-loader native --config packages/api/session-controller/tests/image-read.perf.config.ts
(cd packages/api/session-controller && node --expose-gc .dsh-build/image-read/image-read.perf.js --expect-no-history)
```
Run the separately compiled baseline worker without `--expect-no-history`; its diagnostic request must match the baseline controller's ID-only request fields. The baseline negative control adds `--sample typical --expect-no-history` and must fail because that implementation queries and traverses history. The parent process runs each workload in five fresh child processes, each with a loaded Session and a first uncached read of every image. Images are deterministic synthetic 1024 × 768 PNGs; the two workloads contain 120 turns, 960 events, and 8 images, or 2,000 turns, 16,000 events, and 32 images. Fixture writes can leave the operating system's file cache warm.
`controllerMs` covers the direct controller call through base64 return. `storeMs` includes file I/O, SHA-256, and header verification; `snapshotMs` measures history snapshot acquisition separately. `scanAndDispatchMs` is the time before store entry minus `snapshotMs`, so it includes dispatch overhead and is not an isolated scan timer. JSON serialization and loopback HTTP transfer are separate measurements over retained responses. `requestJsonBytes` and `idOnlyRequestJsonBytes` compare serialized request lengths; they do not measure request transmission time. Cold Session restoration, Gateway processing, browser rendering, remote-network latency, upload, and model inference are excluded. PR #7021 records the worker revisions and before/after results under these limits.
The memory endpoints run GC after fixture setup and after all image responses. The Session, admitted image references, and every base64 response remain reachable at the second endpoint. These retained endpoints include setup-owned objects, and peak RSS is cumulative from process start, including fixture generation. They do not measure image-request memory in isolation or impose a retained-memory budget.
@@ -0,0 +1,52 @@
# Agent Note: 图片读取使用附件存储访问权限
Status: implemented
[English](2026-10-23-store-scoped-image-reads.md) | 中文
## Problem
历史图片加载会为每个未缓存的附件读取请求中的 Session,并搜索其事件内容。搜索用于确认 Session 引用了图片;它不负责定位字节,存储路径已经能由内容寻址 ID 推导。每次读图因此增加了与历史长度成正比的工作。用户反馈的加载延迟还涉及上传;这项发现本身不能确定全部延迟的来源。
## Decision
Session 关联不构成图片访问限制。连接身份认证和 Gateway 权限检查允许调用 `session/attachment` 后,任何调用者都可以通过完整的 `ImageAttachmentRef` 读取同一附件存储中的任意图片,包括仅被其他 Session 引用或未被任何 Session 引用的对象。请求保留 `sessionId`,供现有 Session 资源权限检查使用。该检查通过后,处理函数不要求该 Session 存在,也不会仅因其不存在而返回 `session/not-found`。所有身份使用相同的读图路径。
Client 已经持有消息中的完整图片引用,将其作为 `attachment` 与 `sessionId` 一起发送。Session Controller 直接调用已有的 `AttachmentStore.readImage(ref)`。本地提供方校验规范 ID,在自己的对象目录内推导路径,校验 SHA-256,并把实际格式、字节数、宽度和高度与传入引用比对。对象缺失、不可读、损坏或与引用不符时,操作失败。取得引用无需查询 Session 历史。
响应保留传入引用。可选的 `name` 和 `originalDimensions` 是调用方提交的显示信息,不根据存储对象校验。Client 现有的历史图片缓存继续按 Session 管理结果和对象 URL;Host 不增加图片字节缓存。
该规则缩小了 [Session observation](2026-08-25-session-observations-and-projection-owned-client-state.zh.md) 与[历史传输激活策略](2026-08-18-session-history-and-event-transport.zh.md)涵盖的读取范围。[工作区文件读取](2026-09-05-workspace-files-service.zh.md)保留自己的文件系统授权。
## Alternatives considered
**保留 Session 到图片的 Map 或 projection。** 索引可以消除重复扫描,但保留了产品不需要的访问限制,并增加派生、生命周期和失效处理。
**签发图片签名票据。** 票据为同一项不需要的 Session 关联限制增加签发和验证状态。
**只优化 owner 的读取。** 这会让不同身份使用不同的图片访问规则,并让获准调用的非 owner 继续承担扫描成本,没有相应产品需求。
## Consequences
调用方知道有效图片引用,且有权为请求中的 Session 资源调用该接口,就可以跨 Session 读取对象。本地 ID 是规范化字节的 SHA-256。对于准入时原样保留的已知 PNG、JPEG 或 WebP 字节,调用方可以计算 ID,取得格式、字节数和尺寸,并通过获准的读取请求探测对象是否存在。这些必需的引用字段不一定来自 Session 日志。
图片隔离需要独立 Host 实例及各自的 `DSH_HOME` 目录。随附组合在每个 Host 中使用一个附件存储,不会按 Session 选择存储。身份认证、Gateway 操作与资源检查、固定存储路径、摘要校验和明确失败仍是必需的。
图片读取不再依赖历史长度或 Session 物化。文件读取、完整性校验、编码和传输仍有耗时;本次改动不说明上传或模型推理延迟已得到改善。已有 Session 数据和 fork 引用无需迁移。
## Verification
附件读取不得查询或遍历 Session 历史。验证必须区分获准的跨 Session 图片读取与被 Gateway 拒绝的调用,并覆盖正常引用、无效 ID、固有元数据不符、可选显示字段原样保留、缺失和损坏的对象、旧历史页以及 fork 继承图片。性能证据必须区分历史扫描、存储操作和传输,不能把用户反馈的全部延迟归因于扫描。
诊断脚本是 [`image-read.perf.ts`](../../../../packages/api/session-controller/tests/image-read.perf.ts),通过配套的 [tsdown 配置](../../../../packages/api/session-controller/tests/image-read.perf.config.ts)编译。基线 worker 使用改动前的控制器与 `{ sessionId, attachmentId: ref.attachmentId }`;候选 worker 使用当前控制器与 `{ sessionId, attachment: ref }`。两者使用相同图片 fixture、工作量和输出校验,并通过同一套已构建的 Local store 执行 `readImage(ref)` 校验。在候选检出目录的根目录编译并运行:
```sh
pnpm exec tsdown --config-loader native --config packages/api/session-controller/tests/image-read.perf.config.ts
(cd packages/api/session-controller && node --expose-gc .dsh-build/image-read/image-read.perf.js --expect-no-history)
```
运行单独编译的基线 worker 时不带 `--expect-no-history`;诊断请求必须匹配基线控制器仅接收 ID 的请求字段。基线负对照加上 `--sample typical --expect-no-history`,该实现会查询和遍历历史,因此负对照必须失败。父进程为每种工作量运行五个新子进程,每个子进程使用已加载的 Session,并对每张图片执行第一次未缓存读取。图片是确定性合成的 1024 × 768 PNG;两种工作量分别为 120 轮、960 个事件、8 张图片,以及 2,000 轮、16,000 个事件、32 张图片。fixture 写入可能已经预热操作系统的文件缓存。
`controllerMs` 覆盖从直接调用控制器到返回 base64 的时间。`storeMs` 包含文件 I/O、SHA-256 和文件头校验;`snapshotMs` 单独测量取得历史快照的时间。`scanAndDispatchMs` 是进入存储前的时间减去 `snapshotMs`,因此也包含分派开销,不是独立的扫描计时。JSON 序列化和本机回环 HTTP 传输使用保留的响应单独测量。`requestJsonBytes` 与 `idOnlyRequestJsonBytes` 比较序列化后的请求长度,不测量请求传输时间。冷 Session 恢复、Gateway 处理、浏览器渲染、远端网络延迟、上传和模型推理均不在测量范围内。PR #7021 记录 worker 修订,以及在这些限制下测得的修改前后结果。
内存端点在 fixture 准备完成后,以及所有图片响应完成后执行 GC。第二个端点仍保留 Session、已准入的图片引用和每个 base64 响应。这两个保留内存端点包含准备阶段拥有的对象,峰值 RSS 则从进程启动累计,包含 fixture 生成。它们不单独测量图片请求内存,也不规定保留内存预算。
@@ -0,0 +1,37 @@
# Bilingual-pair consistency record for 2026-10-21-floating-window-edge-recovery.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.md
/agent-note-spring-based-edge-recovery-for-floating-dock-panels:
en: 73438e22c1bef8d3
zh: 5f817eb06259f8ef
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/problem:
en: c3b007f5cce80d8b
zh: c08b07f7e71eaa5f
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision:
en: f88f165ca80a57b8
zh: 98559f2239b03445
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/legal-region-and-displayed-position:
en: 6dea90dc406eacf5
zh: 6ecae0fdad78c855
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/drag-with-resistance:
en: 5214241925b52bc3
zh: bbd66dc72c03f960
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/release-and-spring:
en: ba2b5a3b4923d585
zh: 99544462a464ac50
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/reduced-motion:
en: 7e29bf1c45b5386d
zh: c913a2ce6d1722d1
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/change-scope:
en: 6459103379aefe41
zh: 501dee08a977b6a0
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/testing:
en: da3b2b6781aa99f3
zh: 37e49fa22f72fb84
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/alternatives-considered:
en: 3d901f0f5e270e29
zh: c1fb89b567ea3c70
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/consequences:
en: 360bd69c918f23fe
zh: 48642fd59ad3279b
@@ -0,0 +1,106 @@
# Agent Note: Spring-based edge recovery for floating dock panels
Status: implemented
English | [中文](2026-10-21-floating-window-edge-recovery.zh.md)
## Problem
The dock kit's floating panels are the client's floating windows. `FloatLayer` and the retained `DockLayout` renderer draw them in viewport coordinates through one shared gesture hook, `useFloatGestures`, and the right Sidebar embeds them, so the same panels run in the Web client and inside the Desktop window. Their drag followed the pointer one to one with only a top floor (`--dsh-dockkit-float-top`, which keeps the header below the Windows caption). A panel could therefore be dragged past the left, right or bottom edge until its header was out of reach; a viewport that shrank left a panel outside it; and the creation cascade could place a new panel outside a small viewport. The required behavior is that a panel pushed past an edge visibly resists, and on release is pulled back inside with spring physics instead of being stopped by a wall or left outside.
The reference implementation examined, Claude Desktop, has no portable edge-recovery rule: its Electron fallback corrects an off-screen window once, without animation, on the right and bottom edges only. The behavior had to be designed, not ported.
The change keeps these obligations: a panel header is always reachable; one gesture still records at most one history entry; reduced motion is honored; the persisted Sidebar layout format and every embedder stay unchanged; and the motion is deterministic enough to test without a real browser clock.
## Decision
The behavior lives entirely in `packages/client/ui-dockkit`, inside `useFloatGestures` and the pure engine helpers it calls. Both float renderers take their rectangles from that hook through `rectOf`, so Web and Desktop share the behavior, and no embedder, shell or persisted format changed. The rule extends the floating panels of [right Sidebar docking](2026-09-04-right-sidebar-docking-infrastructure.md) and the fixed-position floating frames of the [retained tab layout](../architecture/2026-09-20-sidebar-retained-tab-layout.md); it supersedes neither note.
### Legal region and displayed position
The legal region of a panel is the viewport (`window.innerWidth` by `window.innerHeight`) with the existing top floor: the Windows caption height plus 20 px when `data-windows-titlebar` is set (20 px in native fullscreen), otherwise 0. `floatBounds` reads only these values and the root's attributes, so starting a gesture forces no layout. `legalFloatRect` projects a rectangle into the region per axis; when a panel is wider or taller than the region it is drawn at the region's size on that axis, so its header controls and its resize corner stay on screen; the stored size is unchanged.
A panel draws at its stored rectangle projected into the viewport. The stored rectangle is never rewritten for the viewport: a shrinking window pushes the panel in without recording an operation, and a growing window returns it toward its stored position. The hook re-reads the bounds at every press and on every window `resize` event, and a gesture in progress uses the new bounds. Persisted layouts that hold off-screen rectangles display inside the viewport without migration.
At rest a panel publishes its rectangle to the `.float` rule as CSS variables through `floatStyle`, and the rule clamps its position and size into the viewport (`100vw` by `100dvh`, which follows `window.innerHeight` as the hook does) and below the caption floor once more; an oversized panel takes the viewport's size there as it does in `legalFloatRect`. A bounds reading the hook has not refreshed, such as one taken before a fullscreen change settles, therefore still leaves the panel inside. A gesture or a return writes its position and size inline, outside the clamp.
### Drag with resistance
A move computes the desired rectangle from the gesture's start rectangle and the pointer travel, then `resistedRect` splits it per axis into the legal projection and the overflow `o` beyond it and draws it at `legal + sign(o) * K * |o| / (K + |o|)` with `K = FLOAT_RESISTANCE = 120` px. The mapping applies on all four edges, including above the top floor, is continuous, has slope 1 at the edge, and approaches `K`:
| pointer overflow (px) | panel displacement past the edge (px) | share of the overflow |
|---|---|---|
| 10 | 9.2 | 92.3% |
| 40 | 30.0 | 75.0% |
| 120 | 60.0 | 50.0% |
| 400 | 92.3 | 23.1% |
A resize clamps the bottom-right corner to the region through `boundedResize` and keeps `FLOAT_MIN_SIZE`; resizing has no resistance, because a corner that lags the pointer reads as a broken handle.
### Release and spring
A release records the legal rectangle: `moveFloat` or `resizeFloat` when it differs from the legal rectangle at the press, otherwise only the raise a click records. A click on a panel drawn projected therefore keeps its stored rectangle. A move or resize therefore records only legal rectangles, and undo restores the pre-gesture position in one step. Panel creation (the drop rectangle of `floatTab` and the cascade) can still store a rectangle outside the viewport; the projection draws it inside. When the panel was drawn outside the legal region, the hook keeps a preview and springs it from where it was drawn to the recorded rectangle, then clears the preview. A release inside the region animates nothing.
The spring in `engine/spring.ts` is underdamped, because its bounce goes inward and is always legal: response 0.32 s and damping ratio 0.72. An overflowing axis starts with the velocity of the drawn panel over the last 100 ms of the drag, so the speed is continuous across the release; it is capped at `SPRING_MAX_VELOCITY` (1500 px/s), and `launchVelocity` caps its outward part at `omega0 * (K - d)` for a drawn overflow `d`. A fling past the edge travels further before it turns back, and because the spring carries an offset `d` with speed `v` at most `d + 0.46 * v / omega0` from its target, the whole return stays within `K` of the edge. An axis that did not overflow keeps still. Per axis the update is:
```
a = -omega0^2 * (x - target) - 2 * zeta * omega0 * v
v = v + a * h
x = x + v * h
```
`stepSpring` integrates in equal substeps of at most `h = 1/480 s`, so the motion does not depend on the frame rate. One `requestAnimationFrame` loop in the hook clamps a frame to 64 ms, ends at the target when a frame gap exceeds 250 ms or 900 ms have passed, and otherwise stops when each axis is within 1 px of the target and slower than 60 px/s. From rest, a 200 px overflow settles in 367 ms with an inward overshoot within one percentage point of the analytic bound `exp(-pi * zeta / sqrt(1 - zeta^2)) = 3.8%`. The integrator is pure and takes `dt`, so the engine keeps its rule of reading no clock.
A press on the grip or the corner during a return cancels it and picks the panel up where it is drawn. A move does so through `unresistedRect`: it inverts the resistance, so zero pointer travel draws the same rectangle. A resize keeps the drawn origin and caps only the corner by the viewport; its release records the legal rectangle and springs the origin inside, as does a resize whose viewport shrank past its origin. Either way a release in place resumes the return without recording a second operation. One hook runs at most one return. A window resize ends a running return at its recorded rectangle, a press on another panel ends it at its target, a change of the panel's record that does not project to the target (an undo, a dock, a close) ends it at the new record on the next frame, and unmounting cancels the pending frame.
### Reduced motion
When `matchMedia('(prefers-reduced-motion: reduce)')` matches, a move clamps to the legal region with no resistance, and release records the legal rectangle with no animation. Environments without `matchMedia` report no preference. The rule only removes motion; it never removes the legality correction.
### Change scope
The change touches one package, `@deepseek-ai/dsh-client-ui-dockkit`, and leaves its exports and `DockIntents` unchanged; the `TabRenderer` contract now states when the kit reuses a body.
| File | Change |
|---|---|
| `packages/client/ui-dockkit/src/engine/geometry.ts` | `FloatBounds`, `FLOAT_RESISTANCE`, `legalFloatRect`, `resistedRect`, `unresistedRect`, `boundedResize` |
| `packages/client/ui-dockkit/src/engine/spring.ts` | the pure spring integrator, its rest predicate `springSettled`, `launchVelocity` and its timing limits |
| `packages/client/ui-dockkit/src/components/FloatLayer.tsx` | `useFloatGestures`: viewport projection, resistance, release spring, drawn-velocity sampling, reduced motion, frame loop and cancellation; `rectOf` and `floatStyle` for both renderers |
| `packages/client/ui-dockkit/src/components/TabLayout.tsx` | draws the hook's displayed rectangle through `floatStyle` |
| `packages/client/ui-dockkit/src/components/TabBody.tsx` | the memoized body every layout (`FloatLayer`, `TabLayout`, `TabPanel`) draws |
| `packages/client/ui-dockkit/src/contract/adapter.ts` | when `TabRenderer` is called again |
| `packages/client/ui-dockkit/src/components/dockkit.module.css` | the resting clamp of position and size on `.float` |
| `packages/client/ui-dockkit/README.md` pair | the edge rule beside the float renderer description |
| `apps/web/tests/sidebar-right.e2e.ts` | a browser case for the resistance and the return |
`ui-sidebar-right` and its persisted layout schema, the `apps/web` source, `apps/desktop`, the shared primitives and the theme are untouched. No dependency was added.
## Testing
`tests/float-bounds.client.spec.ts` covers the projection (inside, each edge, corner, the top floor, an oversized panel), the resistance (the table values, slope 1 at the edge, monotone growth bounded by `K`, independent axes), its inverse and its cap, the bounded resize, and the legal size kept by the resistance and its inverse. `tests/spring.client.spec.ts` covers settling inside the deadline, the overshoot bound, frame-rate independence at 30, 60 and 120 Hz, the effect of release velocity, determinism, and the launch cap keeping every return within `K`. `tests/app-region-styles.client.spec.ts` pins the resting clamp in the stylesheet.
`tests/float-recovery.client.spec.tsx` renders `FloatLayer` over a live controller with hand-driven frames and clock: the resisted preview past an edge, exactly one legal `moveFloat` per release and the spring to it with an inward overshoot, undo in one step, fling against slow push, a fast fling staying within `K`, a drag above the top floor, no animation for a release inside, a push that ends at the stored position, a press mid-return picking the panel up without a jump, the stall snap, the deadline, a body not re-rendered through a drag and its return but re-rendered for a new renderer, a corner press during a return picking the panel up where it is drawn and a resize from there springing in, a resize whose viewport shrank past its origin recording a legal rectangle, with no animation under reduced motion, the 20 px floor on a Windows root without a published caption height, a return yielding to an undo, a close and a press on another panel, unmount cancellation, both reduced-motion answers, the viewport projection on shrink and growth without any intent, a click on a projected panel recording nothing, a window resize during a gesture bounding its release, a resize ending a return, and an off-screen stored rectangle drawn inside. `tests/tab-layout.client.spec.tsx` adds that a float drag re-renders no docked or floating body until the renderer changes, and `components.client.spec.tsx` the same for a `DockSurface` divider drag. The existing `FloatLayer` and `TabLayout` specs still pass with their position assertions read from the resting variables, including the rule that starting a gesture forces no layout read; every changed source file is fully covered. `apps/web/tests/sidebar-right.e2e.ts` drags a Sidebar float past the right and bottom edges in Chromium, checks that the drawn panel stays within 120 px beyond them, waits for the release to settle flush against both edges, then publishes a resting rectangle far outside and larger than the viewport and checks that the stylesheet alone draws it exactly over the viewport.
## Alternatives considered
**Hard clamp at the edge.** Stopping the panel at the viewport edge is the cheapest correct rule, but it feels like hitting a wall and gives no sense of the boundary before contact. It remains as the reduced-motion path.
**Clamp during the drag and rebound on release.** Clamping the drag at the edge and converting the outward pointer speed into an inward bounce keeps every frame inside the viewport. It hides how far the user pushed, so the bounce has no visible cause; the resistance shows the push and still bounds the overflow at 120 px.
**Eased tween on release.** A fixed 240-300 ms ease-out from the released position is predictable, but it carries no velocity, so a fling and a slow push return identically, and a press during it either jumps or restarts. The spring keeps velocity continuous and is interruptible.
**Store the off-screen position and correct it later.** Recording the released rectangle and fixing it on the next render would persist off-screen positions and make undo restore them. Recording the legal rectangle keeps one history entry per gesture with a legal value.
**Rewrite stored rectangles when the viewport shrinks.** Moving panels through operations on resize would add history entries the user never made and change persisted layouts on every window resize. Projecting at render achieves the visible result without either, at the cost of the elastic return described below.
**Native always-on-top OS window.** A real Electron floating window could float above other applications, but only on Desktop; the Web client cannot do it at all, and native frameless dragging gives no per-frame control, so the resistance would be impossible and the spring could only start after release. It is a separate product decision with its own window, IPC and platform work, and this decision does not preclude it.
**Animation library dependency.** A spring library would replace a pure integrator of a few dozen lines and its tests with a new dependency in a statically linked package. The integrator also has to be clock-free for the engine's deterministic tests.
**A shared primitive in `ui-primitives`.** Placing the hook in the primitives package would widen the change to a second package with no second consumer. It can move there when another floating surface needs it.
## Consequences
Floating panels can no longer be lost off screen, in either client, and a push past an edge reads as a pull back rather than a wall. History, persistence and every embedder are unaffected, and the motion is covered by deterministic tests instead of manual checks.
A drag and the spring update the preview through React state, so the layout re-renders on every frame, for up to 900 ms after release as well. Every layout draws tab bodies through `TabBody`, which is memoized on the renderer and the tab record, so such a frame re-renders only the panel frames and headers (the header still calls `renderTabTitle`), never the tab bodies; writing a transform on the panel element directly is the fallback if the remaining cost measures as a problem. A panel pushed in by a shrinking window returns toward its stored position when the window grows, which a user who expects it to stay where it was pushed may find surprising. Content inside a panel, such as a webview, can observe up to 900 ms of motion after release. The constants are tuned for a mouse or trackpad; touch input works through the same pointer events but remains untuned.
@@ -0,0 +1,106 @@
# Agent Note: 悬浮停靠面板的弹簧式边界收回
Status: implemented
[English](2026-10-21-floating-window-edge-recovery.md) | 中文
## 问题
dock kit 的悬浮面板就是客户端里的悬浮窗。`FloatLayer` 与保留式 `DockLayout` 渲染器通过同一个手势 hook `useFloatGestures` 以视口坐标绘制它们,右侧 Sidebar 嵌入了它们,因此同一套面板既运行在 Web 客户端中,也运行在 Desktop 窗口内。它们的拖拽过去一比一跟随指针,只有一个顶部下限(`--dsh-dockkit-float-top`,让标题栏保持在 Windows 标题栏之下)。因此面板可以被拖过左、右或下边界,直到标题栏够不着;视口缩小会把面板留在外面;新建面板的级联位置也可能落在小视口之外。期望行为是:面板被推过边界时可见地受到阻力,松手后以弹簧物理被拉回视口内,而不是像撞墙一样被挡住或被留在外面。
所考察的参考实现 Claude Desktop 没有可移植的边界收回规则:它的 Electron 回退只对屏幕外窗口做一次无动画修正,且只修正右边界和下边界。该行为必须被设计,而不是移植。
变更维持以下义务:面板标题栏始终可达;一个手势仍然最多记录一条历史;遵循减弱动态效果;Sidebar 的持久化布局格式与所有嵌入方保持不变;运动足够确定,无需真实浏览器时钟即可测试。
## 决定
该行为完全位于 `packages/client/ui-dockkit` 内,在 `useFloatGestures` 及其调用的纯 engine 辅助函数中实现。两个悬浮渲染器都通过 `rectOf` 从该 hook 取得矩形,因此 Web 与 Desktop 共享该行为,任何嵌入方、壳或持久化格式都没有改变。该规则扩展了 [右侧 Sidebar 停靠](2026-09-04-right-sidebar-docking-infrastructure.zh.md) 的悬浮面板与 [保留式标签布局](../architecture/2026-09-20-sidebar-retained-tab-layout.zh.md) 的固定定位悬浮框,不取代其中任何一篇。
### 合法区域与显示位置
面板的合法区域是视口(`window.innerWidth` × `window.innerHeight`)加上既有的顶部下限:设置了 `data-windows-titlebar` 时为 Windows 标题栏高度加 20 px(原生全屏时为 20 px),否则为 0。`floatBounds` 只读取这些值和根元素属性,因此开始手势不会触发布局。`legalFloatRect` 逐轴把矩形投影进该区域;面板比区域更宽或更高时,在该轴上按区域尺寸绘制,使标题栏控件和缩放角留在屏幕上;存储的尺寸不变。
面板绘制在其存储矩形投影到视口后的位置。存储矩形从不因视口而被改写:窗口缩小时面板被推入且不记录操作,窗口变大时面板朝存储位置回移。hook 在每次按下和每次窗口 `resize` 事件时重新读取区域,进行中的手势使用新区域。包含屏幕外矩形的持久化布局无需迁移即在视口内显示。
静止时面板通过 `floatStyle` 把矩形以 CSS 变量发布给 `.float` 规则,该规则再次把它的位置和尺寸钳制在视口(`100vw` × `100dvh`;`dvh` 与 hook 读取的 `window.innerHeight` 一致)内并保持在标题栏下限之下;超尺寸面板在这里同样按视口尺寸绘制,与 `legalFloatRect` 一致。因此即使 hook 读到的区域尚未刷新(例如全屏切换完成前读取的值),面板仍在视口内。手势或回弹把位置和尺寸写在行内样式中,不受该钳制。
### 带阻力的拖拽
移动时由手势起始矩形和指针位移计算期望矩形,然后 `resistedRect` 逐轴把它拆分为合法投影与超出它的溢出量 `o`,并绘制在 `legal + sign(o) * K * |o| / (K + |o|)`,其中 `K = FLOAT_RESISTANCE = 120` px。该映射作用于全部四条边,包括顶部下限之上,连续、在边界处斜率为 1、渐近于 `K`:
| 指针溢出(px) | 面板越过边界的位移(px) | 占溢出的比例 |
|---|---|---|
| 10 | 9.2 | 92.3% |
| 40 | 30.0 | 75.0% |
| 120 | 60.0 | 50.0% |
| 400 | 92.3 | 23.1% |
缩放通过 `boundedResize` 把右下角钳制在区域内并保持 `FLOAT_MIN_SIZE`;缩放不加阻力,因为落后于指针的角看起来像坏掉的手柄。
### 松手与弹簧
松手时记录合法矩形:与按下时的合法矩形不同时记录 `moveFloat` 或 `resizeFloat`,否则只记录点击会记录的提升。因此单击以投影绘制的面板会保留其存储矩形。因此移动或缩放只记录合法矩形,撤销一步即可恢复手势前的位置。创建面板(`floatTab` 的落点矩形与级联)仍可能存储视口外的矩形,由投影把它绘制在视口内。若面板绘制在合法区域之外,hook 保留预览,用弹簧把它从绘制位置带到记录的矩形,然后清除预览。在区域内松手不播放动画。
`engine/spring.ts` 中的弹簧是欠阻尼的,因为它的回弹朝向内侧,始终合法:响应时间 0.32 s、阻尼比 0.72。溢出的轴以拖拽最后 100 ms 内绘制面板的速度起步,因此速度在松手前后连续;该速度上限为 `SPRING_MAX_VELOCITY`(1500 px/s),且对绘制溢出量 `d`,`launchVelocity` 把其向外分量限制在 `omega0 * (K - d)` 以内。甩过边界的面板会先走得更远再折返;由于弹簧从偏移 `d`、速度 `v` 出发时距目标至多 `d + 0.46 * v / omega0`,整条回弹轨迹都不超出边界 `K`。没有溢出的轴保持不动。每轴更新为:
```
a = -omega0^2 * (x - target) - 2 * zeta * omega0 * v
v = v + a * h
x = x + v * h
```
`stepSpring` 以等长且不超过 `h = 1/480 s` 的子步积分,因此运动与帧率无关。hook 中唯一的 `requestAnimationFrame` 循环把单帧钳制到 64 ms,帧间隔超过 250 ms 或已过 900 ms 时直接停在目标,否则在每轴距目标 1 px 内且慢于 60 px/s 时停止。从静止开始,200 px 溢出在 367 ms 内稳定,向内过冲与解析上限 `exp(-pi * zeta / sqrt(1 - zeta^2)) = 3.8%` 相差不超过一个百分点。积分器是纯函数并接收 `dt`,因此 engine 保持不读取时钟的规则。
回弹期间按下抓手或右下角会取消回弹,并从绘制位置接住面板。移动通过 `unresistedRect` 做到这一点:它反演阻力,因此零指针位移绘制同一矩形。缩放保留绘制时的原点,只用视口约束右下角;松手时记录合法矩形并用弹簧把原点收回视口,手势中视口缩到原点以内的缩放也是如此。两种情况下原地松手都会恢复回弹且不记录第二次操作。一个 hook 最多运行一个回弹。窗口缩放会让进行中的回弹停在记录的矩形;按下另一个面板会让它停在目标;面板记录的变化若不再投影到目标(撤销、停靠、关闭),会在下一帧让它停在新记录;卸载会取消待处理的帧。
### 减弱动态效果
`matchMedia('(prefers-reduced-motion: reduce)')` 匹配时,移动钳制在合法区域内且无阻力,松手时记录合法矩形且不播放动画。没有 `matchMedia` 的环境视为无偏好。该规则只移除运动,从不移除合法性修正。
### 改动范围
变更只涉及一个包 `@deepseek-ai/dsh-client-ui-dockkit`,其导出与 `DockIntents` 保持不变;`TabRenderer` 的约定写明了套件何时复用标签页内容。
| 文件 | 变更 |
|---|---|
| `packages/client/ui-dockkit/src/engine/geometry.ts` | `FloatBounds`、`FLOAT_RESISTANCE`、`legalFloatRect`、`resistedRect`、`unresistedRect`、`boundedResize` |
| `packages/client/ui-dockkit/src/engine/spring.ts` | 纯弹簧积分器、静止判定函数 `springSettled`、`launchVelocity` 与时间上限 |
| `packages/client/ui-dockkit/src/components/FloatLayer.tsx` | `useFloatGestures`:视口投影、阻力、松手弹簧、绘制速度采样、减弱动态效果、帧循环与取消;供两个渲染器使用的 `rectOf` 与 `floatStyle` |
| `packages/client/ui-dockkit/src/components/TabLayout.tsx` | 通过 `floatStyle` 绘制 hook 给出的显示矩形 |
| `packages/client/ui-dockkit/src/components/TabBody.tsx` | 各布局(`FloatLayer`、`TabLayout`、`TabPanel`)共用的 memo 化标签页内容 |
| `packages/client/ui-dockkit/src/contract/adapter.ts` | `TabRenderer` 何时被再次调用 |
| `packages/client/ui-dockkit/src/components/dockkit.module.css` | `.float` 上位置与尺寸的静止钳制 |
| `packages/client/ui-dockkit/README.md` 对 | 在悬浮渲染器说明旁补充边界规则 |
| `apps/web/tests/sidebar-right.e2e.ts` | 覆盖阻力与回弹的浏览器用例 |
`ui-sidebar-right` 及其持久化布局 schema、`apps/web` 源码、`apps/desktop`、共享基础组件与主题均未改动。没有新增依赖。
## 测试
`tests/float-bounds.client.spec.ts` 覆盖投影(内部、每条边、角、顶部下限、超尺寸面板)、阻力(表中数值、边界处斜率为 1、以 `K` 为上界的单调增长、各轴独立)、其反演与上限,受限缩放,以及阻力与其反演都保持合法尺寸。`tests/spring.client.spec.ts` 覆盖在截止时间内稳定、过冲上限、30/60/120 Hz 下与帧率无关、松手速度的作用、确定性,以及启动速度上限让每条回弹都不超出 `K`。`tests/app-region-styles.client.spec.ts` 固定样式表中的静止钳制。
`tests/float-recovery.client.spec.tsx` 在活的控制器上渲染 `FloatLayer`,帧与时钟由测试手动推进:越过边界时带阻力的预览、每次松手恰好一次合法的 `moveFloat` 以及带向内过冲的弹回、一步撤销、甩出与慢推的对比、快速甩出不超出 `K`、拖过顶部下限、区域内松手不播放动画、推到存储位置的手势、回弹中按下接住面板且不跳变、停顿直接跳转、截止时间、拖拽与回弹期间不重渲染标签页内容而换新渲染函数后重渲染、回弹中按下右下角从绘制位置接住面板、从那里缩放后弹回、手势中视口缩到缩放原点以内时记录合法矩形且减弱动态效果下不播放动画、未发布标题栏高度的 Windows 根元素仍保持 20 px 下限、回弹让位于撤销、关闭与按下另一个面板、卸载取消、两种减弱动态效果答复、视口缩小与变大时的投影且不调用任何 intent、单击投影面板不记录任何操作、手势中窗口缩放约束其松手结果、缩放结束回弹,以及屏幕外存储矩形在视口内绘制。`tests/tab-layout.client.spec.tsx` 新增:悬浮面板拖拽期间停靠与悬浮的标签页内容都不重渲染,直到渲染函数改变;`components.client.spec.tsx` 对 `DockSurface` 拖动分隔条做同样的检查。既有的 `FloatLayer` 与 `TabLayout` 测试在位置断言改为读取静止变量后通过,包括开始手势不做布局读取这一规则;每个改动的源文件都被完全覆盖。`apps/web/tests/sidebar-right.e2e.ts` 在 Chromium 中把 Sidebar 悬浮面板拖过右边界和下边界,检查绘制的面板越过两边均不超过 120 px,等待松手后面板贴合两条边静止,再发布一个远在视口外且大于视口的静止矩形,检查仅靠样式表就把它恰好绘制成覆盖整个视口。
## 考虑过的替代方案
**在边界处硬钳制。** 在视口边界停住面板是成本最低的正确规则,但手感像撞墙,接触之前也感觉不到边界。它保留为减弱动态效果的路径。
**拖拽中钳制、松手时回弹。** 在边界处钳制拖拽,并把向外的指针速度转换为向内的回弹,能让每一帧都留在视口内。但它隐藏了用户推了多远,回弹因此没有可见的起因;阻力显示了推动,同时把溢出限制在 120 px 内。
**松手后的缓动补间。** 从松手位置开始的固定 240–300 ms 缓出补间可预测,但不携带速度,因此甩出与慢推的返回完全相同,补间中按下要么跳变要么重启。弹簧保持速度连续且可打断。
**存储屏幕外位置并在之后修正。** 记录松手矩形、在下一次渲染时修正,会持久化屏幕外位置,并让撤销恢复它们。记录合法矩形则保持每个手势一条历史且值合法。
**视口缩小时改写存储矩形。** 在缩放时通过操作移动面板会增加用户从未做过的历史条目,并在每次窗口缩放时改变持久化布局。渲染时投影无需二者即可得到可见结果,代价是下文描述的弹性返回。
**原生始终置顶 OS 窗口。** 真正的 Electron 悬浮窗可以浮在其他应用之上,但只在 Desktop 上可行;Web 客户端完全无法做到,而且原生无边框拖拽不提供逐帧控制,因此阻力无法实现,弹簧只能在松手后启动。它是一个独立的产品决策,有自己的窗口、IPC 与平台工作,本决定不排斥它。
**动画库依赖。** 弹簧库会用一个静态链接包里的新依赖替换几十行的纯积分器及其测试。积分器还必须不依赖时钟,才能用于 engine 的确定性测试。
**放进 `ui-primitives` 的共享基础组件。** 把 hook 放进基础组件包会把改动扩大到第二个包,而没有第二个使用方。等另一个悬浮界面需要它时再迁移。
## 后果
悬浮面板在两个客户端中都不会再丢失到屏幕外,推过边界读起来是被拉回而不是撞墙。历史、持久化与所有嵌入方不受影响,运动由确定性测试而非手动检查覆盖。
拖拽与弹簧都通过 React state 更新预览,因此布局每帧都会重渲染,松手后最多还会持续 900 ms。各布局都通过 `TabBody` 绘制标签页内容,它以渲染函数和标签记录为键做了 memo,因此这样的一帧只重渲染面板框与标题栏(标题栏仍会调用 `renderTabTitle`),从不重渲染标签页内容;如果剩余成本经测量构成问题,退路是直接在面板元素上写 transform。被缩小窗口推入的面板会在窗口变大时朝存储位置回移,期望它留在被推到位置的用户可能会感到意外。面板内的内容(例如 webview)在松手后可能观察到最多 900 ms 的运动。常量针对鼠标或触控板调优;触控输入经由同样的 pointer 事件可用,但仍未调优。
+3
View File
@@ -13,3 +13,6 @@ docs/persistence-schema.json linguist-generated=true
docs/persistence-changes/*.schema.json linguist-generated=true
docs/persistence-changes/releases/*.schema.json linguist-generated=true
docs/persistence-changes/historical-formats/*.schema.json linguist-generated=true
# Unified patch blank context lines require their leading space.
patches/*.patch whitespace=-blank-at-eol
+2
View File
@@ -4,4 +4,6 @@ Run jobs on Windows runners (`windows-*` labels) under native `pwsh`. Native Win
The manual [Windows packaging workflow](workflows/windows-package.yml) uses the dedicated self-hosted Windows x64 label `dsh-win-package-trial` under native `pwsh`; preserve this routing separately from the automatic CI lanes.
The merge checks run from three workflows named `Policy`, which run on `pull_request_target` so their definitions come from master, and call the `deepseek-harness-check` action directly: `pr-check-on-head-branch.yml` on pull-request updates gives `Policy / Master Change` and `Policy / Pre-Merge Check`, `pr-check-after-approve.yml` on pull-request updates and submitted or dismissed reviews gives `Policy / Approve Check` and `Policy / Reviewer Evaluate`, and `pr-check-on-base-branch.yml` on master pushes re-runs the head-branch checks as `Policy / Recheck`. Branch rules require those check names, so keep the job names and the workflow name. Each check reads its mode from a repository variable: `MERGE_POLICY_MASTER_DIFF`, `MERGE_POLICY_PRE_MERGE`, `MERGE_POLICY_HEAD_DIFF`, and `MERGE_POLICY_REVIEW`, each `off` (skip), `report` (run without failing the job), or `block` (fail the job); a missing value or an unknown one counts as `report`. `Policy / Pre-Merge Check` merges the commit `Policy / Master Change` reports, so it runs only after that job and stays off while `MERGE_POLICY_MASTER_DIFF` is `off`.
The manual Desktop publication workflow selects a successful package run and attempt, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job.
@@ -0,0 +1,94 @@
name: Policy
on:
pull_request_target:
branches: [master]
types: [opened, synchronize, reopened, ready_for_review]
pull_request_review:
types: [submitted, dismissed]
permissions:
contents: read
pull-requests: read
concurrency:
group: pr-check-after-approve-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
approve:
name: Approve Check
# Each check runs only while its repository variable is neither empty nor `off`; otherwise the job is skipped.
if: ${{ vars.MERGE_POLICY_HEAD_DIFF != '' && vars.MERGE_POLICY_HEAD_DIFF != 'off' }}
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
pull-requests: read
steps:
# The head checkout is only the Git repository the check fetches into; it needs no files and runs no code.
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
filter: blob:none
sparse-checkout: README.md
sparse-checkout-cone-mode: false
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
- uses: deepseek-harness/deepseek-harness-check@master
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_HEAD_DIFF }}
with:
check: head-diff
base-branch: ${{ github.event.pull_request.base.ref }}
head-sha: ${{ github.event.pull_request.head.sha }}
pr-number: ${{ github.event.pull_request.number }}
pr-author: ${{ github.event.pull_request.user.login }}
review:
name: Reviewer Evaluate
if: ${{ vars.MERGE_POLICY_REVIEW != '' && vars.MERGE_POLICY_REVIEW != 'off' }}
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
pull-requests: read
# The check posts its verdict as a check run of its own.
checks: write
steps:
# The head checkout is only the Git repository the check fetches into; it needs no files and runs no code.
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
filter: blob:none
sparse-checkout: README.md
sparse-checkout-cone-mode: false
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
# The check app's token makes the review check run its own row instead of joining this workflow's suite.
- id: token
continue-on-error: true
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1
with:
client-id: ${{ vars.DSH_APPROVAL_APP_CLIENT_ID }}
private-key: ${{ secrets.DSH_APPROVAL_APP_PRIVATE_KEY }}
owner: deepseek-harness
repositories: deepseek-harness
permission-checks: write
- uses: deepseek-harness/deepseek-harness-check@master
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_REVIEW }}
CHECK_TOKEN: ${{ steps.token.outputs.token }}
with:
check: review
base-branch: ${{ github.event.pull_request.base.ref }}
head-sha: ${{ github.event.pull_request.head.sha }}
pr-number: ${{ github.event.pull_request.number }}
pr-author: ${{ github.event.pull_request.user.login }}
@@ -0,0 +1,30 @@
name: Policy
on:
push:
branches: [master]
workflow_dispatch:
permissions: {}
concurrency:
group: pr-check-on-base-branch-${{ github.ref_name }}
jobs:
recheck:
name: Recheck
# Re-runs the head-branch checks, so it follows their variables.
if: ${{ vars.MERGE_POLICY_MASTER_DIFF != '' && vars.MERGE_POLICY_MASTER_DIFF != 'off' || vars.MERGE_POLICY_PRE_MERGE != '' && vars.MERGE_POLICY_PRE_MERGE != 'off' }}
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
actions: write
contents: read
pull-requests: read
steps:
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
- uses: deepseek-harness/deepseek-harness-check@master
with:
check: recheck
base-branch: ${{ github.ref_name }}
recheck-label-token: ${{ secrets.DSH_RECHECK_LABEL_TOKEN }}
@@ -0,0 +1,84 @@
name: Policy
on:
pull_request_target:
branches: [master]
types: [opened, synchronize, reopened, ready_for_review, review_requested, auto_merge_enabled, labeled]
permissions:
contents: read
concurrency:
group: pr-check-on-head-branch-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
master:
name: Master Change
# Each check runs only while its repository variable is neither empty nor `off`; otherwise the job is skipped.
if: ${{ vars.MERGE_POLICY_MASTER_DIFF != '' && vars.MERGE_POLICY_MASTER_DIFF != 'off' && !github.event.pull_request.draft }}
runs-on: ubuntu-latest
timeout-minutes: 15
outputs:
base_sha: ${{ steps.check.outputs.base_sha }}
since: ${{ steps.check.outputs.since }}
steps:
# The head checkout is only the Git repository the check fetches into; it needs no files and runs no code.
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
filter: blob:none
sparse-checkout: README.md
sparse-checkout-cone-mode: false
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
- id: check
uses: deepseek-harness/deepseek-harness-check@master
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_MASTER_DIFF }}
with:
check: master-diff
base-branch: ${{ github.event.pull_request.base.ref }}
head-sha: ${{ github.event.pull_request.head.sha }}
pre-merge:
name: Pre-Merge Check
needs: master
if: ${{ vars.MERGE_POLICY_PRE_MERGE != '' && vars.MERGE_POLICY_PRE_MERGE != 'off' && needs.master.result == 'success' }}
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 60
# This job installs and compiles the pull request: it reads contents only and receives no secret.
permissions:
contents: read
steps:
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
- name: Merge the checked base-branch commit
env:
BASE_SHA: ${{ needs.master.outputs.base_sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
SINCE: ${{ needs.master.outputs.since }}
run: |
[[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$SINCE" =~ ^[0-9]+$ ]] || { echo "::error::the master diff check reported no base commit"; exit 1; }
git fetch --no-tags --no-write-fetch-head --shallow-since="$SINCE" origin "$HEAD_SHA" "$BASE_SHA"
git -c user.name=pr-check -c [email protected] merge --no-ff --no-edit -m "Merge $BASE_SHA into $HEAD_SHA" "$BASE_SHA"
- uses: pnpm/[email protected]
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
- name: Run the pre-merge command
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_PRE_MERGE }}
run: |
if ! bash -euxo pipefail -c 'pnpm install --frozen-lockfile && pnpm exec tsx scripts/compile-referenced-projects.ts host-contracts && pnpm exec tsx scripts/compile-referenced-projects.ts client'; then
if [ "$CHECK_MODE" = block ]; then exit 1; fi
echo "::warning title=Pre-Merge Check::the merged tree does not install or compile; this check does not block"
fi
+1
View File
@@ -75,6 +75,7 @@ External packages installed for runtime use or embedded in distributed Host or b
| [`@xterm/xterm`](https://github.com/xtermjs/xterm.js) | MIT |
| [`@yarnpkg/parsers`](https://github.com/yarnpkg/berry) | BSD-2-Clause |
| [`acorn`](https://github.com/acornjs/acorn) | MIT |
| [`acorn-walk`](https://github.com/acornjs/acorn) | MIT |
| [`ajv`](https://github.com/ajv-validator/ajv) | MIT |
| [`anser`](https://github.com/IonicaBizau/anser) | MIT |
| [`big.js`](https://github.com/MikeMcl/big.js) | MIT |
+6 -1
View File
@@ -29,6 +29,7 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
writeFileSync(join(root, 'package.json'), '{"type":"module"}')
writeFileSync(join(modules, 'dsh-app-boot', 'package.json'), '{"type":"module","exports":"./index.js"}')
writeFileSync(join(modules, 'dsh-app-boot', 'index.js'), `
export class StartupError extends Error {}
export const loadProfileDirectory = () => ({ skippedBundles: [] });
export const reportSkippedBundles = () => {};
export const loadLayeredEnv = () => ({});
@@ -64,7 +65,11 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
const boot = await new Promise<{
packageManager: { command: string; args: string[]; env: Record<string, string> }
}>((resolve, reject) => {
child.once('message', resolve)
child.on('message', (message) => {
if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'booting' && 'packageManager' in message) {
resolve(message as { packageManager: { command: string; args: string[]; env: Record<string, string> } })
}
})
child.once('error', reject)
child.once('exit', (code) => { reject(new Error(`Host exited before booting: ${String(code)} ${stderr}`)) })
})
@@ -1,4 +1,4 @@
/** Account catalog diagnostics preserve the shipped ACP profile's JSON-RPC stream. */
/** Account catalog and MCP resource-listing diagnostics keep the shipped ACP profile's stdout JSON-RPC only. */
import { once } from 'node:events'
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
@@ -6,10 +6,22 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk'
import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server'
import { launchAcpTestAgent, type AgentUnderTest, type LaunchedAcpTestAgent } from '@deepseek-ai/dsh-session-snapshot'
import { expect, it } from 'vitest'
import { cleanupAcpExampleTest } from './cleanup.ts'
const repoRoot = fileURLToPath(new URL('../../../../../../', import.meta.url))
const binScript = join(repoRoot, 'apps/cli/src/bin.ts')
const tsconfigPath = join(repoRoot, 'tsconfig.json')
/** Parse every stdout line as a JSON-RPC frame; a diagnostic line fails the parse with its leading text. */
function jsonRpcFrames(launched: LaunchedAcpTestAgent): Record<string, unknown>[] {
const frames = launched.rawStdout().trim().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
for (const frame of frames) expect(frame).toMatchObject({ jsonrpc: '2.0' })
return frames
}
it('keeps account model-listing diagnostics on stderr during API-key session creation', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'dsh-acp-stdout-'))
const token = 'acp-catalog-fixture-token'
@@ -100,3 +112,48 @@ it('keeps account model-listing diagnostics on stderr during API-key session cre
if (failures.length > 0) throw new AggregateError(failures, 'ACP catalog test cleanup failed')
}
})
it('keeps MCP resource-listing diagnostics off stdout for a tools-only client server', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'dsh-acp-stdout-'))
const llm = await startMockLlmServer({
sequence: ['tool_call_success', 'success'],
toolName: 'list_mcp_resources',
toolArguments: JSON.stringify({ server: 'fixture' }),
})
let launched: LaunchedAcpTestAgent | undefined
try {
const configPath = join(cwd, 'mcp.patch.yml')
await writeFile(configPath, JSON.stringify([
{ id: 'llm-deepseek', config: { baseURL: llm.baseURL, models: [{ id: 'fixture-api-key-model' }] } },
{ id: 'acp', config: { provider: 'deepseek-official', model: 'fixture-api-key-model' } },
{ id: 'session-persistence-jsonl', config: { root: join(cwd, 'sessions'), compression: 'none' } },
]) + '\n')
launched = launchAcpTestAgent({
agent: { binScript, configPath, profile: 'acp', tsconfigPath },
cwd,
env: { DEEPSEEK_API_KEY: 'acp-fixture-api-key', DEEPSEEK_BASE_URL: llm.baseURL, DSH_TELEMETRY_DISABLED: '1' },
})
await launched.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
// The fixture server advertises only the tools capability.
const mcpServer = join(repoRoot, 'packages/mcp/mcp-client/tests/fixture-server.ts')
const created = await launched.client.newSession({
cwd, mcpServers: [{ name: 'fixture', command: process.execPath, args: [mcpServer], env: [] }],
})
await expect(launched.client.prompt({
sessionId: created.sessionId,
prompt: [{ type: 'text', text: 'list the fixture resources' }],
})).resolves.toEqual({ stopReason: 'end_turn' })
expect(launched.updates).toContainEqual(expect.objectContaining({ sessionUpdate: 'tool_call_update', status: 'completed' }))
await launched.client.closeSession({ sessionId: created.sessionId })
await launched.close()
expect(launched.child.exitCode).toBe(0)
expect(llm.requests.map(request => request.behavior)).toEqual(['tool_call_success', 'success'])
expect(jsonRpcFrames(launched).length).toBeGreaterThanOrEqual(5)
} finally {
const cleanup = await Promise.allSettled([cleanupAcpExampleTest(launched, cwd), llm.close()])
const failures: unknown[] = []
for (const result of cleanup) if (result.status === 'rejected') failures.push(result.reason)
if (failures.length > 0) throw new AggregateError(failures, 'ACP MCP test cleanup failed')
}
})
+2 -1
View File
@@ -25,7 +25,8 @@
"@deepseek-ai/dsh-tool-workspace-dependencies": "workspace:*",
"@deepseek-ai/dsh-skill-office": "workspace:*",
"@deepseek-ai/dsh-deepseek-account": "workspace:*",
"@deepseek-ai/dsh-workspace": "workspace:*"
"@deepseek-ai/dsh-workspace": "workspace:*",
"@deepseek-ai/dsh-plugin-manager": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
+59
View File
@@ -0,0 +1,59 @@
/** Bounded Host failure details sent to the Desktop crash reporter. */
import { inspect } from 'node:util'
import { StartupError } from '@deepseek-ai/dsh-app-boot'
/** Maximum characters carried by one fatal diagnostic, including its truncation notice. */
export const MAX_FATAL_DIAGNOSTIC_CHARS = 64 * 1024
/** Original-error budget when startup metadata needs space in the same report. */
const MAX_ORIGINAL_ERROR_CHARS = 8 * 1024
/** Startup entry details leave room for composition and provider observations. */
const MAX_STARTUP_ENTRY_CHARS = 8 * 1024
/**
* Render the original error and explicitly selected startup metadata.
* Selected metadata excludes configuration values and arbitrary startup logger arguments.
* @param error - Failure received by the Host entry point.
* @returns Bounded text with an explicit notice when the report is shortened.
*/
export function formatFatalDiagnostic(error: unknown): string {
const original = inspect(error, { depth: 4, maxArrayLength: 50 })
const sections: string[] = []
const seen = new Set<Error>()
function visit(value: unknown): void {
if (!(value instanceof Error) || seen.has(value)) return
seen.add(value)
if (value instanceof StartupError) {
if (value.startup !== undefined) {
sections.push(`Configuration file: ${value.startup.configurationPath}`)
}
const entries = inspect(value.entries, { depth: 6, maxArrayLength: null, maxStringLength: 4096 })
sections.push('--- startup entries ---', entries.length <= MAX_STARTUP_ENTRY_CHARS ? entries
: `${entries.slice(0, MAX_STARTUP_ENTRY_CHARS).replace(/[\uD800-\uDBFF]$/u, '')}\n… (startup entries truncated at ${MAX_STARTUP_ENTRY_CHARS} characters)`)
if (value.composition !== undefined) {
const { plugins, services, omittedPlugins, omittedServices } = value.composition
const sources = [...new Set(plugins.map(plugin => plugin.source))]
sections.push('--- startup composition ---',
'Provider lists contain observed registrations only; an empty list means the provider is unknown.',
'Source identifies the Loader tree, not necessarily the overriding patch.',
`Omitted plugin rows: ${omittedPlugins}; omitted missing-service observations: ${omittedServices}.`,
'--- missing services ---', ...services.map(service => JSON.stringify(service)),
'--- plugin sources (sourceIndex) ---', ...sources.map((source, index) => JSON.stringify({ index, source })),
'--- plugins (inactive first) ---', ...plugins.map(({ source, ...plugin }) => JSON.stringify({ ...plugin, sourceIndex: sources.indexOf(source) })))
} else {
sections.push('Startup composition diagnostic unavailable.')
}
}
visit(value.cause)
if (value instanceof AggregateError) value.errors.forEach(visit)
}
visit(error)
sections.unshift(sections.length === 0 || original.length <= MAX_ORIGINAL_ERROR_CHARS ? original
: `${original.slice(0, MAX_ORIGINAL_ERROR_CHARS).replace(/[\uD800-\uDBFF]$/u, '')}\n… (original error truncated at ${MAX_ORIGINAL_ERROR_CHARS} characters)`)
const text = sections.join('\n')
if (text.length <= MAX_FATAL_DIAGNOSTIC_CHARS) return text
const notice = `\n… (Host diagnostic truncated at ${MAX_FATAL_DIAGNOSTIC_CHARS} characters)`
return text.slice(0, MAX_FATAL_DIAGNOSTIC_CHARS - notice.length).replace(/[\uD800-\uDBFF]$/u, '') + notice
}
+8 -5
View File
@@ -1,7 +1,9 @@
/** Launch the Desktop profile through the Web application and report its URL to Electron. */
import { delimiter, join } from 'node:path'
import { inspect } from 'node:util'
import { randomUUID } from 'node:crypto'
import type { PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
import { formatFatalDiagnostic } from './fatal-diagnostic.ts'
import { loadLayeredEnv, loadProfileDirectory, reportSkippedBundles } from '@deepseek-ai/dsh-app-boot'
import { runProfile } from '@deepseek-ai/dsh/profile-boot'
import type {} from '@deepseek-ai/dsh-client-connection'
@@ -15,8 +17,11 @@ import { installDesktopUpdateTaskControl } from './update-tasks.ts'
import { installDesktopQuitInspection } from './quit-inspection.ts'
import { installPlatformSessionPublisher } from './platform-session.ts'
import { installOfficeEngineResolution } from './office-engine.ts'
import { installOperationDiagnostics } from './operation-diagnostics.ts'
async function main(): Promise<void> {
const runId = randomUUID() as PluginOperationRunId
if (process.connected) process.send?.({ type: 'starting', runId }, (error) => { if (error !== null) console.error(error) })
const runtimeDir = process.argv[2] as string
const projectDir = process.argv[3] as string
installOfficeEngineResolution(runtimeDir)
@@ -123,6 +128,7 @@ async function main(): Promise<void> {
})
process.once('disconnect', () => { void stop() })
const { ctx } = await application
installOperationDiagnostics(ctx, record => send({ type: 'plugin-operation', record }), 32, runId)
control.updateTasks = installDesktopUpdateTaskControl(ctx)
control.quitInspection = installDesktopQuitInspection(ctx)
await ctx.plugin(desktopOffice, {
@@ -137,16 +143,13 @@ async function main(): Promise<void> {
if (process.connected) process.send?.({ type: 'ready', url, injections: ctx.webServer.collectIndexInjections(ctx.connection.browserPeer) }, (error) => { if (error !== null) console.error(error) })
}
/** Upper bound of the startup diagnostic carried over IPC; the head holds the message and stack. */
const MAX_FATAL_DIAGNOSTIC_CHARS = 64 * 1024
if (import.meta.main) {
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error)
// The shell receives the complete inspected error here, not through stderr:
// stderr bytes and this IPC message race, and the shell reports the first
// failure it sees.
const diagnostic = inspect(error, { depth: 4, maxArrayLength: 50 }).slice(0, MAX_FATAL_DIAGNOSTIC_CHARS)
const diagnostic = formatFatalDiagnostic(error)
if (process.connected) process.send?.({ type: 'fatal', message, diagnostic }, (error) => { if (error !== null) console.error(error) })
console.error(error)
process.exitCode = 1
@@ -0,0 +1,34 @@
/** Bounded delivery of management facts to the shell which owns durable diagnostics. */
import type { Context } from '@deepseek-ai/cordis'
import { parsePluginOperationRecord, type PluginOperationRecord, type PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
/**
* Observe manager operations after Host startup, with bounded concurrent IPC deliveries.
* @param ctx - Context owning the subscription and its pending deliveries.
* @param send - IPC transport promise which settles when delivery succeeds or fails.
* @param maxPending - Maximum number of outstanding deliveries; excess events are counted and omitted.
* @param runId - Host lifetime identity announced before profile startup.
*/
export function installOperationDiagnostics(
ctx: Context, send: (record: PluginOperationRecord) => Promise<void>, maxPending: number, runId: PluginOperationRunId,
): void {
if (!Number.isSafeInteger(maxPending) || maxPending < 1) throw new RangeError('Invalid diagnostic delivery budget')
const pending = new Set<Promise<void>>()
let dropped = 0
let closed = false
ctx.on('plugin-manager/operation', (operation) => {
if (closed || pending.size >= maxPending) { dropped++; return }
const record = parsePluginOperationRecord({ runId, operation, transportDropped: dropped })
if (record === undefined) { dropped++; return }
const delivery = Promise.resolve().then(async () => {
try { await send(record) }
catch (_error) { dropped++ /* IPC failure does not change the management operation. */ }
})
pending.add(delivery)
void delivery.then(() => { pending.delete(delivery) })
})
ctx.effect(() => async () => {
closed = true
await Promise.allSettled(pending)
})
}
@@ -0,0 +1,105 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished } from 'vitest'
import { boot, StartupError } from '@deepseek-ai/dsh-app-boot'
import { formatFatalDiagnostic, MAX_FATAL_DIAGNOSTIC_CHARS } from '../src/fatal-diagnostic.ts'
import { renderCrashReport } from '../../desktop/src/crash-report.ts'
it.each([
['import', 'throw new Error("qualification-import-failure")'],
['initialize', 'export function apply() { throw new Error("qualification-initialize-failure", { cause: new Error("qualification-root-cause") }) }'],
])('retains real plugin %s failure evidence in the Desktop report after Loader disposal', async (stage, source) => {
const directory = await mkdtemp(join(tmpdir(), 'desktop-plugin-failure-'))
onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) })
await writeFile(join(directory, 'failure.mjs'), source + '\n')
const config = join(directory, 'cordis.yml')
await writeFile(config, '- id: agent-loop\n name: ./failure.mjs\n')
const failure: unknown = await boot('diagnostic-test', config).then(async (ctx) => {
await ctx.fiber.dispose()
throw new Error('Expected fixture plugin to fail startup')
}, (error: unknown) => error)
expect(failure).toBeInstanceOf(StartupError)
const diagnostic = formatFatalDiagnostic(failure)
const report = renderCrashReport({ source: 'host', phase: 'startup', error: failure,
hostDiagnostic: diagnostic, rendererConsole: [], operationHistoryPlanned: true,
time: new Date('2026-10-19T00:00:00Z'),
app: { name: 'qualification', version: 'test', platform: 'win32', arch: 'x64', electron: 'test', node: process.version, locale: 'zh-CN' },
})
expect(report).toContain(`qualification-${stage}-failure`)
expect(report).toContain('./failure.mjs')
expect(report).toContain('--- startup composition ---')
if (stage === 'initialize') expect(report).toContain('qualification-root-cause')
})
it('includes non-enumerable startup entries without copying arbitrary startup logger arguments', () => {
const error = new StartupError('required plugin did not activate', [{
id: 'agent-loop', module: '@deepseek-ai/dsh-agent-loop', required: true, fiberState: undefined,
outcome: { kind: 'pending', missing: ['agents', 'sessions'] },
}])
error.startup = { configurationPath: '/profile/cordis.yml', messages: [{
ts: 1, name: 'plugin', type: 'warn', args: ['private-plugin-output'],
}] }
const report = formatFatalDiagnostic(new Error('Host startup failed', { cause: error }))
expect(report).toContain('--- startup entries ---')
expect(report).toContain('@deepseek-ai/dsh-agent-loop')
expect(report).toContain("missing: [ 'agents', 'sessions' ]")
expect(report).toContain('Configuration file: /profile/cordis.yml')
expect(report).not.toContain('private-plugin-output')
})
it('marks truncation within the complete IPC budget and preserves Unicode', () => {
const error = new Error('😀'.repeat(MAX_FATAL_DIAGNOSTIC_CHARS))
const report = formatFatalDiagnostic(error)
expect(report.length).toBeLessThanOrEqual(MAX_FATAL_DIAGNOSTIC_CHARS)
expect(report).toContain('Host diagnostic truncated at 65536 characters')
expect(report.isWellFormed()).toBe(true)
})
it('keeps missing-service evidence ahead of a truncated plugin inventory', () => {
const error = new StartupError('failure '.repeat(2000), [{
id: 'waiting-entry', module: './waiting.mjs', required: true, fiberState: undefined,
outcome: { kind: 'pending', missing: ['agents'] },
}])
error.startup = { configurationPath: '/profile/critical-cordis.yml', messages: [] }
error.composition = {
services: [{ consumer: 'agent-loop', service: 'agents', providers: [] }],
plugins: Array.from({ length: 256 }, (_, index) => ({
id: `plugin-${index}`, module: 'long-package-name'.repeat(30), version: '1.0.0',
state: 'disabled', source: '/profile/cordis.yml', missing: [],
})),
omittedPlugins: 3, omittedServices: 2,
}
const report = formatFatalDiagnostic(error)
expect(report).toContain('original error truncated at 8192 characters')
expect(report).toContain('Configuration file: /profile/critical-cordis.yml')
expect(report).toContain('waiting-entry')
expect(report).toContain('"service":"agents","providers":[]')
expect(report).toContain('Omitted plugin rows: 3; omitted missing-service observations: 2.')
expect(report).toContain('"source":"/profile/cordis.yml"')
expect(report).toContain('Host diagnostic truncated at 65536 characters')
expect(report.length).toBeLessThanOrEqual(MAX_FATAL_DIAGNOSTIC_CHARS)
})
it('terminates traversal through cyclic and aggregate causes', () => {
const error = new AggregateError([], 'cycle')
error.errors.push(error)
error.cause = error
expect(formatFatalDiagnostic(error)).toContain('cycle')
})
it.each(['many entries', 'long stack'])('retains composition evidence after %s', (scenario) => {
const failure = new Error('startup failure')
failure.stack = 'x'.repeat(70000)
const error = new StartupError('startup failed', scenario === 'long stack'
? [{ id: 'failed', module: './failed.mjs', required: true, fiberState: undefined, outcome: { kind: 'failed', error: failure } }]
: Array.from({ length: 256 }, (_, index) => ({ id: `pending-${index}`, module: 'module'.repeat(60), required: true, fiberState: undefined, outcome: { kind: 'pending' as const, missing: ['agents'] } })))
error.startup = { configurationPath: '/profile/cordis.yml', messages: [] }
error.composition = { plugins: [{ id: 'provider', module: 'example', version: '1.0.0', state: 'active', source: '/profile/cordis.yml', missing: [] }], services: [{ consumer: 'consumer', service: 'agents', providers: [] }], omittedPlugins: 0, omittedServices: 0 }
const report = formatFatalDiagnostic(error)
expect(report).toContain('Configuration file: /profile/cordis.yml')
expect(report).toContain('startup entries truncated')
expect(report).toContain('"service":"agents"')
expect(report).toContain('"version":"1.0.0"')
expect(report.length).toBeLessThanOrEqual(65536)
})
@@ -0,0 +1,41 @@
import { Context } from '@deepseek-ai/cordis'
import type { PluginOperation } from '@deepseek-ai/dsh-plugin-manager/types'
import type { PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
import { expect, it, onTestFinished, vi } from 'vitest'
import { installOperationDiagnostics } from '../src/operation-diagnostics.ts'
const operation: PluginOperation = {
id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9' as PluginOperation['id'],
time: '2026-10-19T00:00:00.000Z', reason: 'plugin', phase: 'started', target: 'managed', stage: 'enable',
}
const runId = 'c254ab28-97c9-4382-95e6-2db9c66f98c8' as PluginOperationRunId
it('bounds outstanding deliveries and drains them on context disposal', async () => {
const ctx = new Context()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
onTestFinished(async () => { release.resolve(undefined); await ctx.fiber.dispose() })
const send = vi.fn(async () => { entered.resolve(undefined); await release.promise })
installOperationDiagnostics(ctx, send, 1, runId)
ctx.emit('plugin-manager/operation', operation)
await entered.promise
for (let i = 0; i < 1000; i++) ctx.emit('plugin-manager/operation', operation)
expect(send).toHaveBeenCalledTimes(1)
expect(send).toHaveBeenCalledWith(expect.objectContaining({ runId }))
let stopped = false
const stopping = ctx.fiber.dispose().then(() => { stopped = true })
await Promise.resolve(undefined)
expect(stopped).toBe(false)
release.resolve(undefined)
await stopping
ctx.emit('plugin-manager/operation', operation)
expect(send).toHaveBeenCalledTimes(1)
})
it('contains transport rejections during teardown', async () => {
const ctx = new Context()
onTestFinished(async () => { await ctx.fiber.dispose() })
installOperationDiagnostics(ctx, async () => { throw new Error('disconnected') }, 1, runId)
ctx.emit('plugin-manager/operation', operation)
await expect(ctx.fiber.dispose()).resolves.toBeUndefined()
})
+3
View File
@@ -31,6 +31,9 @@
{
"path": "../../packages/credentials/deepseek-account"
},
{
"path": "../../packages/boot/plugin-manager"
},
{
"path": "../../packages/fs/fs"
},
+6 -6
View File
@@ -12,11 +12,11 @@
en: 7bc8bf30de693222
zh: e85993d8852b6cab
/deepseek-harness-desktop/table-of-contents:
en: 05fd227f99ee535a
zh: 60d7d62bc0026973
en: 127ea90553cb6af7
zh: 7b1c5aec8558c684
/deepseek-harness-desktop/application-overview:
en: e9b22f232837e131
zh: fc5f3834b969d2d2
en: b57525e17b9638ab
zh: 274fe8344f7c2202
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
@@ -36,8 +36,8 @@
en: 160b500cdcd6a39a
zh: 6c267f1762ec3689
/deepseek-harness-desktop/installation-ownership/runtime-and-plugin-activation:
en: a1a47b09f4a72ba4
zh: 7b1cf27f0b72cf31
en: 4951cd3ee659eb33
zh: 96bdd6358dad587a
/deepseek-harness-desktop/installation-ownership/host-environment:
en: 98cf848762482d48
zh: 74f9100a39ec8c2f
+5 -8
View File
@@ -18,6 +18,7 @@ Desktop runs the Harness workspace in a native application. This reference cover
- [Key technical decisions](#key-technical-decisions)
- [Bundled command runtime](#bundled-command-runtime)
- [Installation ownership](#installation-ownership)
- [Recovery and diagnostics](docs/diagnostics/README.md)
- [Develop](#develop)
- [Package](#package)
- [Windows installer interface](#windows-installer-interface)
@@ -30,6 +31,8 @@ Desktop runs the Harness workspace in a native application. This reference cover
## Application overview
Electron caches the last confirmed UI language in `userData/desktop/locale-cache` so startup recovery dialogs can use it before Host settings are available. Missing, invalid, or unreadable caches fall back to the system language; cache write failures do not block startup. A successful Host startup or a UI language change refreshes the cache. Until then, a changed system language may differ from the cached language.
Desktop analytics follows the [product collection policy](../../packages/client/product-analytics/README.md), including its live application setting. Web usage is excluded. Update installation waits for its local analytics intake before locking API admission and stopping the Host. Intake has a one-second deadline; failure does not prevent installation, and collector delivery is not awaited.
The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it.
@@ -40,7 +43,7 @@ The first application-menu command, **About DeepSeek Harness**, opens Electron's
Desktop’s local native directory flow opens an Electron folder dialog attached to the application window, restoring, showing, and focusing that window first. Concurrent requests share one dialog; cancellation returns no path and failures remain retryable. Ordinary Web uses the Host chooser. Browse mode lists Host directories. On Linux without zenity or kdialog, automatic selection uses browse instead of the Electron dialog.
Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/dependencies/pnpm`. Build-time production installation, the installed `dsh` CLI, Creator and the Web Plugin Manager execute its `bin/pnpm.mjs` with Electron Node mode; package operations do not require pnpm on PATH. The private Node launcher environment applies only to package operations. Agent workspace dependencies copy the same self-contained primary-runtime payload into the Harness home and execute pnpm with its standalone Node.
Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/dependencies/pnpm`, without the native packages of other targets. Build-time production installation, the installed `dsh` CLI, Creator and the Web Plugin Manager execute its `bin/pnpm.mjs` with Electron Node mode; package operations do not require pnpm on PATH. The private Node launcher environment applies only to package operations. Agent workspace dependencies copy the same self-contained primary-runtime payload into the Harness home and execute pnpm with its standalone Node.
Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar.
@@ -172,13 +175,7 @@ The signed `resources/app.asar/dsh/desktop-runtime.json` binds the shell version
The [Web plugin UI](../../packages/client/ui-plugin-manager/README.md) owns the management interface. Desktop profile initialization and recovery preserve installed plugin files.
Fatal main-window creation, main-document loading, preload, renderer, Web initialization, or backend failures open one native recovery dialog per application process. It shows a bounded tail of the first error, notes any truncation, and offers Exit, Restart, and Disable third-party plugins, back up profile patch, and restart. Startup failures retain the Web loading page and spinner; runtime failures retain the current page. Expected shutdowns, cancelled navigation, and ordinary requests do not trigger recovery. The shared Web plugin manager reports package-operation errors; Host startup failures after plugin changes enter native recovery. There is no startup timeout heuristic. A listener failure containing `listen EADDRINUSE` replaces the diagnostics and reinstall advice with guidance to quit other running DSH instances, and offers only Exit and Restart.
Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines, plus the path of the crash report described below when one was written. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely.
Before the first fatal dialog opens, Electron writes a crash report to the platform logs directory (`app.getPath('logs')`: `~/Library/Logs/DeepSeek Harness` on macOS, `logs` under the application’s `userData` directory on Windows and Linux), waiting at most one second for the write; a slow or failed write shows the dialog without a path. The file `crash-<UTC time>-<source>.log` records the source (`host` for a Host exit, `web-boot` for a renderer boot failure, `renderer` for a renderer or document failure, `main` for a shell error), whether the backend had reached ready, application and runtime versions, the error with its enumerable properties and cause chain (cut at 256 KiB), the Host’s own inspected error (at most 64 KiB) when the Host reported a startup failure over IPC before exiting, and the primary window’s recent error-level console output (at most 64 KiB). A Host exit report therefore contains the retained stderr tail, which may include plugin output. A fatal failure during shutdown writes a report without opening a dialog. Files are owner-only where the platform supports it; startup keeps the ten newest reports and removes older ones without touching other files in the directory.
Recovery waits for Host shutdown before changing plugin activation. The native recovery action calls the shared app-boot recovery function under the profile transaction lock. It disables third-party bundles and renames the profile’s `cordis.patch.yml` to `cordis.patch.yml.bak-<timestamp>` (with an ordinal on collisions) without parsing it; the next startup creates an empty patch. Installed packages and earlier backups remain. The home-level patch is unchanged. The Electron console records the backup path (or its absence) and the unchanged home-level patch. Invalid profile data, rename failures, or write failures are reported as recovery-operation errors; completed changes remain, and Desktop does not restart as though recovery succeeded. Desktop has no profile-reset action or emergency HTML document.
Desktop fatal failures use native recovery with Exit, Restart, Disable third-party plugins, back up profile patch, and restart, and Get diagnostic report. See [recovery and diagnostics](docs/diagnostics/README.md) for triggers, report locations and contents, recent operation records, and shutdown limits.
### Host environment
+5 -8
View File
@@ -18,6 +18,7 @@ Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用
- [关键技术决策](#key-technical-decisions)
- [内置命令运行时](#bundled-command-runtime)
- [安装归属](#installation-ownership)
- [故障恢复与诊断](docs/diagnostics/README.zh.md)
- [开发](#develop)
- [打包](#package)
- [Windows 安装界面](#windows-installer-interface)
@@ -30,6 +31,8 @@ Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用
## 应用概览
Electron 在 `userData/desktop/locale-cache` 缓存最近确认的界面语言,使启动恢复弹窗在 Host 设置尚不可用时也能使用该语言。缓存缺失、无效或不可读时回退到系统语言;缓存写入失败不阻断启动。Host 成功启动或界面语言变更时会刷新缓存;在此之前,变更后的系统语言可能与缓存语言不同。
桌面埋点遵循[产品采集策略](../../packages/client/product-analytics/README.zh.md)及其动态应用配置,不包含 Web 使用情况。安装更新会等待该操作的本地埋点接收请求结束,再锁定 API 准入并停止 Host。接收请求的时限为一秒,失败不会阻止安装,也不等待收集端完成发送。
桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。
@@ -40,7 +43,7 @@ Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过
Desktop 的本地原生目录流程打开绑定应用窗口的 Electron 文件夹对话框,并先恢复、显示和聚焦该窗口。并发请求共用一个对话框;取消不返回路径,失败后可以重试。普通 Web 使用 Host 选择器。浏览模式列出 Host 目录。Linux 缺少 zenity 或 kdialog 时,自动选择使用浏览模式,不使用 Electron 对话框。
Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一份 pnpm 分发包。构建时的生产依赖安装、安装版 `dsh` CLI、Creator 和 Web 插件管理器通过 Electron Node 模式执行其中的 `bin/pnpm.mjs`;包操作不要求 PATH 上存在 pnpm。私有 Node 启动器环境仅用于包操作。agent(智能体)的工作区依赖将同一份完整 primary-runtime 复制到 Harness 主目录,并使用其中的独立 Node 执行 pnpm。
Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一份 pnpm 分发包,不含其他目标平台的原生包。构建时的生产依赖安装、安装版 `dsh` CLI、Creator 和 Web 插件管理器通过 Electron Node 模式执行其中的 `bin/pnpm.mjs`;包操作不要求 PATH 上存在 pnpm。私有 Node 启动器环境仅用于包操作。agent(智能体)的工作区依赖将同一份完整 primary-runtime 复制到 Harness 主目录,并使用其中的独立 Node 执行 pnpm。
Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。
@@ -172,13 +175,7 @@ macOS 上自定义菜单保留 Electron 的标准 Window 菜单及应用隐藏
[Web 插件 UI](../../packages/client/ui-plugin-manager/README.zh.md)负责管理界面。Desktop profile 初始化和恢复保留已安装插件文件。
主窗口创建、主文档加载、preload、渲染器、Web 初始化或后端的致命失败,会在每个应用进程中打开一次原生恢复对话框。对话框显示首次错误末尾的限长摘要,标明截断情况,并提供退出、重启、禁用第三方插件、备份 profile patch 并重启。启动失败保留 Web 加载页和动画;运行中失败保留当前页面。预期关闭、取消导航和普通请求错误不会触发恢复。共享 Web 插件管理器报告包操作错误;插件变更后的 Host 启动失败会进入原生恢复。不通过启动超时推断故障。 包含 `listen EADDRINUSE` 的监听失败以退出其他正在运行的 DSH 实例的提示替代诊断和重装建议,仅提供退出和重启。
原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断,若已写入下述崩溃报告则附上其路径。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。
首个致命弹窗打开前,Electron 会向平台日志目录(`app.getPath('logs')`:macOS 为 `~/Library/Logs/DeepSeek Harness`,Windows 与 Linux 为应用 `userData` 目录下的 `logs`)写入一份崩溃报告,最多等待写入一秒;写入缓慢或失败时弹窗不带路径。文件 `crash-<UTC 时间>-<source>.log` 记录来源(`host` 为 Host 退出、`web-boot` 为渲染进程启动失败、`renderer` 为渲染进程或文档失败、`main` 为壳自身错误)、后端是否已就绪、应用与运行时版本、包含可枚举属性与 cause 链的错误(截至 256 KiB)、Host 在退出前通过 IPC 报告启动失败时自己的 inspect 错误(最多 64 KiB),以及主窗口最近的 error 级 console 输出(最多 64 KiB)。因此 Host 退出报告包含保留的 stderr 尾部,其中可能含有插件输出。关闭过程中的致命失败只写报告、不弹窗。平台支持时文件仅所有者可读;启动时保留最新十份报告并删除更早的,不触碰目录中的其他文件。
恢复操作等待 Host 关闭后才修改插件启用状态。原生恢复操作在 profile 事务锁内调用共享 app-boot 恢复函数。它禁用第三方 bundle,并将 profile 的 `cordis.patch.yml` 重命名为 `cordis.patch.yml.bak-<timestamp>`(重名时追加序号),无需解析;下次启动创建空 patch。已安装包和已有备份保留。home 级 patch 不变。Electron 控制台记录备份路径(或原文件不存在)以及 home 级 patch 未修改。profile 数据无效、重命名失败或写入失败会作为恢复操作错误报告;已完成的修改保留,Desktop 不会假装恢复成功后重启。Desktop 不提供 profile 重置操作或应急 HTML 文档。
Desktop 的致命故障通过原生恢复对话框提供退出、重启、禁用第三方插件并备份 profile patch 后重启,以及获取诊断报告。触发范围、报告位置与内容、近期操作记录和退出限制见[故障恢复与诊断](docs/diagnostics/README.zh.md)。
### Host 环境
@@ -0,0 +1,28 @@
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/docs/diagnostics/README.md
/:
en: 29d76ee1849cd8fd
zh: a2b8cbabe79557f9
/desktop-recovery-and-diagnostics:
en: 4d4fd8a92047e5c6
zh: 15ec51d703ccd70b
/desktop-recovery-and-diagnostics/summary:
en: e61d0f55e426aa6f
zh: dc13c7e054eac9d1
/desktop-recovery-and-diagnostics/table-of-contents:
en: 8f3a2a84eaf575af
zh: 3087306f10e7c2cf
/desktop-recovery-and-diagnostics/recover-from-a-failure:
en: 9d0645dba352979d
zh: e1556207a04d9a71
/desktop-recovery-and-diagnostics/report-contents:
en: 1a2eb71ac2dccf63
zh: 5cf59639d3e49591
/desktop-recovery-and-diagnostics/recent-operation-records:
en: f1c19c1516a51ab6
zh: b350f7c18086d274
/desktop-recovery-and-diagnostics/collection-and-shutdown:
en: bac4a49f63d4aaf8
zh: df1ae908ee2148e1
+76
View File
@@ -0,0 +1,76 @@
---
description: "Use this reference when recovering Desktop failures or collecting reports; it explains report contents, operation history, and shutdown limits."
---
# Desktop recovery and diagnostics
English | [中文](README.zh.md)
## Summary
This reference describes Desktop native failure recovery, diagnostic reports, recent plugin operation records, and collection and shutdown limits.
## Table of Contents
- [Recover from a failure](#recovery)
- [Report contents](#report-contents)
- [Recent operation records](#operation-records)
- [Collection and shutdown](#collection-and-shutdown)
<a id="recovery"></a>
## Recover from a failure
Fatal main-window creation, main-document loading, preload, renderer, Web initialization, or backend failures open one native recovery dialog per application process. It shows a bounded tail of the first error, notes any truncation, and offers “Exit”, “Restart”, “Disable third-party plugins, back up profile patch, and restart”, and “Get diagnostic report” while report writing is pending or after it succeeds. Startup failures retain the Web loading page and spinner; runtime failures retain the current page. Expected shutdowns, cancelled navigation, and ordinary requests do not trigger recovery. The shared Web plugin manager reports package-operation errors; Host startup failures after plugin changes enter native recovery. There is no startup timeout heuristic. A listener failure containing `listen EADDRINUSE` replaces the diagnostics and reinstall advice with guidance to quit other running DSH instances, and offers “Exit”, “Restart”, and “Get diagnostic report” while report writing is pending or after it succeeds.
Recovery uses the last confirmed Desktop language from the local cache before Host settings are available; an absent or invalid cache falls back to system languages.
Recovery waits for Host shutdown before changing plugin activation. The native recovery action calls the shared app-boot recovery function under the profile transaction lock. It disables third-party bundles and renames the profile’s `cordis.patch.yml` to `cordis.patch.yml.bak-<timestamp>` (with an ordinal on collisions) without parsing it; the next startup creates an empty patch. Installed packages and earlier backups remain. The home-level patch is unchanged. The Electron console records the backup path (or its absence) and the unchanged home-level patch. Invalid profile data, rename failures, or write failures are reported as recovery-operation errors; completed changes remain, and Desktop does not restart as though recovery succeeded. Desktop has no profile-reset action or emergency HTML document.
<a id="report-contents"></a>
## Report contents
Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines, plus the crash report path or its pending/unavailable status. Retrieving a pending or unavailable report preserves any recovery-operation failure headline and details. Configuration paths and startup entries precede the composition inventory so plugin rows cannot displace them when output is truncated. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely.
Before the first fatal dialog opens, Electron writes a crash report to the platform logs directory (`app.getPath('logs')`: `~/Library/Logs/DeepSeek Harness` on macOS, `logs` under the application’s `userData` directory on Windows and Linux), waiting at most one second for the write; a slow or failed write shows the dialog with an explicit pending or unavailable status. Get diagnostic report checks the same write and reveals a saved file in the system file manager without restarting or stopping the Host; a write that completes after the initial deadline remains available. The user attaches that file to a support ticket. The attachment contains the original failure; later recovery-operation errors remain in the dialog and require a separate screenshot. Retrieving a saved report shows its sharing or reveal-failure heading while retaining the recovery error details. If writing fails, the dialog hides Get diagnostic report and suggests providing a screenshot.
The file `crash-<UTC time>-<source>.log` records the source (`host` for a Host exit, `web-boot` for a renderer boot failure, `renderer` for a renderer or document failure, `main` for a shell error), whether the backend had reached ready, application and runtime versions, the error with its enumerable properties and cause chain (cut at 256 KiB), the Host’s own error and explicitly selected startup metadata (at most 64 Ki characters, including a truncation notice; startup errors reserve space for metadata by limiting the original error and startup-entry details to 8 Ki characters each, with explicit truncation notices) when the Host reported a startup failure over IPC before exiting, and the primary window’s recent error-level console output (at most 64 KiB).
A Host exit report therefore contains the retained stderr tail, which may include plugin output. A fatal failure during shutdown writes a report without opening a dialog. Files are owner-only where the platform supports it; startup keeps the ten newest reports and removes older ones without touching other files in the directory.
<a id="operation-records"></a>
## Recent operation records
Operation records and the application single-instance lock are isolated by `userData`; the shared platform logs directory does not store operation records. The reader only reads the two operation files under `userData/plugin-operations`. Repairing an unfinished append preserves complete lines in the current segment and the previous segment.
Version-exemption changes reuse the bundle enable/disable record fields. When the exemption and installed versions match, the record cannot distinguish an exemption change from a bundle toggle.
Host `transportDropped` is a lower bound as of the last successful delivery; Desktop rejects malformed or mismatched-run records without adding them to that counter.
The journal retains two 256 KiB segments, accepts records up to 4 KiB, and bounds queued writes to 64 KiB.
Exit, recovery restart and installer preparation wait at most 500 ms for queued writes; a timeout disables further writes and later drains return immediately without another wait, while an already-issued OS request may still settle.
Records cover manager operations observed after Host startup, not direct CLI commands or manual file changes. Package-manager output remains in its existing detailed logs and is not copied into this summary. Missing records, a start without an end, and damaged history do not establish a successful operation. This collection does not diagnose kernel hangs, OOM or native crashes.
Persistence failures also disable the writer for the rest of this shell lifetime, including after recovery or installer failure. This bounds repeated failing I/O and avoids appending behind an uncertain partial write. Restarting the application creates a new writer. Omission and repair counters cover only the current shell lifetime. Retained segments provide a larger local troubleshooting window than the deliberately smaller report attachment.
<a id="collection-and-shutdown"></a>
## Collection and shutdown
After saving the basic report, the shell attempts to append recent plugin-management records in an isolated Worker packaged as `lib/operation-report-worker.js` inside `app.asar`. The completion marker and omission counters distinguish a finished collection from missing or partial material.
The Host announces its run ID before profile loading; reported Host errors carry that ID as `hostRunId`, matching operation records from the same lifetime. Failure before this announcement leaves the run identity unknown. Recent operations are context, not proof of cause.
Collection reads only two owned files under `userData/plugin-operations`, at most 64 KiB and 100 records; the complete appended section is limited to 64 KiB.
The 500 ms collection budget reserves its final 100 ms for cooperative cancellation before requesting forced Worker termination; completion waits for its exit. Application exit, recovery exit or restart, and confirmed update installation also cancel collection and wait at most 500 ms for Worker exit. A rejected shutdown cleanup is logged without skipping the remaining cleanup waits. Shutdown prevents late basic-report saves from starting another collector. An update installation failure permits future collection again.
Worker messages interrupt collection between bounded records; an in-flight file open, stat, read or close must settle, and synchronous parsing cannot be preempted within one record. The final append uses an abort signal but can leave partial bytes. Forced termination remains the fallback when cooperative cleanup does not finish.
The basic report remains available independently. Only one collector runs at a time; concurrent reports keep their basic content without an auxiliary section. A rejected termination request does not release that slot until exit is observed. Get diagnostic report can reveal the basic file before the append finishes. The completion marker confirms only that collection ended, not that all operations were captured; queued bytes and omission counters describe missing material.
See [local verification](../../tests/README.md#verification-diagnostics) for fault setup and acceptance steps, and the [Desktop README](../../README.md) for the application overview and development entry points.
@@ -0,0 +1,76 @@
---
description: "排查 Desktop 故障或收集报告时阅读,了解恢复操作、报告内容、操作历史和退出限制。"
---
# Desktop 故障恢复与诊断
[English](README.md) | 中文
## 概述
本参考文档说明 Desktop 的原生故障恢复、诊断报告、近期插件操作记录,以及采集和退出时的限制。
## 目录
- [遇到故障怎么办](#recovery)
- [报告包含什么](#report-contents)
- [近期操作记录](#operation-records)
- [采集与退出行为](#collection-and-shutdown)
<a id="recovery"></a>
## 遇到故障怎么办
主窗口创建、主文档加载、preload、渲染器、Web 初始化或后端的致命失败,会在每个应用进程中打开一次原生恢复对话框。对话框显示首次错误末尾的限长摘要,标明截断情况,并提供“退出”“重启”“禁用第三方插件、备份 profile patch 并重启”,以及报告仍在保存或已保存时的“获取诊断报告”。启动失败保留 Web 加载页和动画;运行中失败保留当前页面。预期关闭、取消导航和普通请求错误不会触发恢复。共享 Web 插件管理器报告包操作错误;插件变更后的 Host 启动失败会进入原生恢复。不通过启动超时推断故障。包含 `listen EADDRINUSE` 的监听失败以退出其他正在运行的 DSH 实例的提示替代诊断和重装建议,提供“退出”“重启”,以及报告仍在保存或已保存时的“获取诊断报告”。
Host 设置可用前,恢复对话框使用本地缓存中最后确认的 Desktop 语言;缓存不存在或无效时回退到系统语言。
恢复操作等待 Host 关闭后才修改插件启用状态。原生恢复操作在 profile 事务锁内调用共享 app-boot 恢复函数。它禁用第三方 bundle,并将 profile 的 `cordis.patch.yml` 重命名为 `cordis.patch.yml.bak-<timestamp>`(重名时追加序号),无需解析;下次启动创建空 patch。已安装包和已有备份保留。home 级 patch 不变。Electron 控制台记录备份路径(或原文件不存在)以及 home 级 patch 未修改。profile 数据无效、重命名失败或写入失败会作为恢复操作错误报告;已完成的修改保留,Desktop 不会假装恢复成功后重启。Desktop 不提供 profile 重置操作或应急 HTML 文档。
<a id="report-contents"></a>
## 报告包含什么
原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断,并附上崩溃报告路径或仍在保存、无法保存的状态。获取仍在保存或无法保存的报告时,保留恢复操作失败的标题和详情。配置路径和启动条目排在组合清单之前,避免输出截断时被插件记录挤掉。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。
首个致命弹窗打开前,Electron 会向平台日志目录(`app.getPath('logs')`:macOS 为 `~/Library/Logs/DeepSeek Harness`,Windows 与 Linux 为应用 `userData` 目录下的 `logs`)写入一份崩溃报告,最多等待写入一秒;写入缓慢或失败时明确显示仍在保存或无法保存。“获取诊断报告”检查同一次写入,并在系统文件管理器中定位已保存的文件,不停止 Host 或重启;超过首次等待期限后写入完成的文件仍可获取。用户可将文件作为工单附件。附件只包含最初的故障;后续恢复操作错误保留在对话框中,需要另行截图。获取已保存报告会显示分享或打开失败的标题,同时保留恢复错误详情。写入失败时隐藏获取报告按钮,并提示提供窗口截图。
文件 `crash-<UTC 时间>-<source>.log` 记录来源(`host` 为 Host 退出、`web-boot` 为渲染进程启动失败、`renderer` 为渲染进程或文档失败、`main` 为壳自身错误)、后端是否已就绪、应用与运行时版本、包含可枚举属性与 cause 链的错误(截至 256 KiB)、Host 在退出前通过 IPC 报告启动失败时的错误及显式选择的启动元数据(最多 64 Ki 个字符,包含截断提示;启动错误的原始错误文本和启动条目详情分别限制为 8 Ki 个字符,并明确标注截断,为结构化元数据保留空间),以及主窗口最近的 error 级 console 输出(最多 64 KiB)。
因此 Host 退出报告包含保留的 stderr 尾部,其中可能含有插件输出。关闭过程中的致命失败只写报告、不弹窗。平台支持时文件仅所有者可读;启动时保留最新十份报告并删除更早的,不触碰目录中的其他文件。
<a id="operation-records"></a>
## 近期操作记录
操作记录目录与应用单实例锁均按 `userData` 隔离;共享平台日志目录不用于保存操作记录。读取器只读取 `userData/plugin-operations` 下的两个操作记录文件。修复未写完的尾行时保留当前段的完整行与上一段。
版本豁免变更复用 bundle 启停记录字段。豁免版本与安装版本相同时,记录无法区分豁免变更与 bundle 开关。
Host 的 `transportDropped` 只表示最近一次成功发送时的计数下界;Desktop 拒绝的非法或运行 ID 不匹配记录不计入该值。
操作历史保留两个 256 KiB 文件段,单条记录不超过 4 KiB,排队写入不超过 64 KiB。
退出、恢复重启和安装准备最多等待排队写入 500 ms;超时会停用后续写入,此后的排空调用立即返回,不会再次等待;但已经发出的操作系统请求仍可能随后结束。
记录覆盖 Host 启动后观察到的管理器操作,不包含直接执行的 CLI 命令或手工文件修改。包管理器输出保留在原有详细日志中,不复制到摘要。缺失记录、只有开始没有结束的操作以及损坏的历史,都不能说明操作已成功。此收集不诊断内核卡死、OOM 或原生崩溃。
持久化失败也会在本次壳生命周期内停用写入,包括恢复或安装器失败后继续运行的情况,以限制重复失败的 I/O,并避免在可能残缺的写入后追加记录。重启应用会创建新写入器。遗漏和修复计数仅覆盖当前壳生命周期。保留文件段提供比报告附件更大的本地排障历史窗口。
<a id="collection-and-shutdown"></a>
## 采集与退出行为
基本报告保存后,壳会尝试通过独立 Worker 追加近期插件管理记录;该 Worker 以 `lib/operation-report-worker.js` 打包在 `app.asar` 中。完成标记和遗漏计数用于区分已完成收集与缺失或不完整的材料。
Host 在加载 profile 前报告运行 ID;Host 错误中的 `hostRunId` 与该次运行的操作记录使用同一标识。在此通知之前发生的失败,其运行标识仍为未知。近期操作只是上下文,不是因果证据。
收集只读取 `userData/plugin-operations` 下归其管理的两个文件,最多读取 64 KiB 和 100 条记录;完整追加内容不超过 64 KiB。
500 ms 收集预算中的最后 100 ms 用于协作取消,随后才请求强制终止 Worker;只有 Worker 退出后才确认收集结束。应用退出、恢复退出或重启、确认安装更新也会取消收集,并最多等待 500 ms 确认 Worker 退出。退出清理中的拒绝会被记录,但不会跳过其他清理等待。退出过程中,延迟保存完成的基本报告不会再启动收集器。更新安装失败后可再次收集。
Worker 在有界记录之间处理取消消息;已经发出的文件打开、状态读取、读取或关闭操作必须等待完成,单条记录的同步解析不能被抢占。最后的追加写入传入取消信号,但仍可能留下部分字节。协作清理未及时完成时仍需强制终止。
基本报告独立可用。同时只运行一个收集器;并发报告保留基本内容,不追加辅助部分。终止请求被拒绝时,必须观察到退出才能释放该名额。“获取诊断报告”可能在追加完成前定位基本文件。完成标记仅表示收集结束,不表示捕获了全部操作;排队字节数和遗漏计数说明缺失材料。
故障构造与验收步骤见[本地验证](../../tests/README.zh.md#verification-diagnostics);应用概览与开发入口见 [Desktop README](../../README.zh.md)。
+2
View File
@@ -84,6 +84,8 @@
"@deepseek-ai/dsh-client-shortcuts": "workspace:*",
"@deepseek-ai/dsh-atomic-write": "workspace:*",
"@deepseek-ai/dsh-client-product-analytics": "workspace:*",
"@deepseek-ai/dsh-plugin-manager": "workspace:*",
"zod": "4.4.3",
"@deepseek-ai/dsh-util-file-drag": "workspace:*"
}
}
@@ -139,6 +139,7 @@ export function createElectronBuilderConfig(
},
files: [
'lib/main.js',
'lib/operation-report-worker.js',
'lib/welcome/**/*',
'lib/preload-app.cjs',
'lib/preload-mandatory.cjs',
+5
View File
@@ -29,6 +29,8 @@ export interface CrashReportApp {
/** Inputs of {@link renderCrashReport} and {@link writeCrashReport}. */
export interface CrashReportInput {
/** The shell will attempt an independently bounded operation-history append after saving this report. */
readonly operationHistoryPlanned?: boolean
readonly source: CrashReportSource
readonly phase: CrashReportPhase
readonly error: unknown
@@ -125,6 +127,9 @@ export function renderCrashReport(input: CrashReportInput): string {
...(input.hostDiagnostic === undefined ? [] : ['--- host diagnostic (as reported by the Host process) ---', input.hostDiagnostic, '']),
'--- renderer console (error level, oldest first) ---',
consoleSection,
...(input.operationHistoryPlanned === true ? ['', '--- auxiliary diagnostics ---',
'Operation history is best effort. Without its completion marker below, it is unavailable or incomplete.',
'Recent operations are context only. Missing records do not establish that no changes occurred.'] : []),
'',
].join('\n')
}
+51 -23
View File
@@ -12,10 +12,14 @@ interface RecoveryOperations {
disablePlugins(): Promise<void>
exit(): void
restart(): void
/** Reveal an existing report in the system file manager; reject if it is no longer available. */
revealReport(path: string): Promise<void>
/** Persist the complete diagnostic; resolves with the file path, or `undefined` when nothing was written. */
writeReport(error: unknown, source: CrashReportSource): Promise<string | undefined>
}
type ReportState = { kind: 'pending' } | { kind: 'failed' } | { kind: 'ready'; path: string }
/** Upper bound on waiting for the crash report before the dialog opens. */
export const CRASH_REPORT_WAIT_MS = 1_000
@@ -25,28 +29,28 @@ const DETAIL_BUDGET = 1200
/** Tail lines of the error kept in the dialog; the report file holds the rest. */
const DETAIL_TAIL_LINES = 8
/**
* Compose the dialog detail: the error's last lines (prefixed by the
* shortening notice when they are not the whole error), then the report path
* when one was written, then the reinstall advice. The report line does not
* depend on shortening: a short error that was persisted names its file too.
/** At most eight error-tail lines; status, advice and truncation notice share the detail character budget.
* The message heading has its own field.
*/
function dialogDetail(error: string, messages: DesktopMessages, reportPath: string | undefined): string {
function dialogDetail(error: string, messages: DesktopMessages, reportState: ReportState): string {
const advice = `\n\n${messages.startupReinstallAdvice}`
const report = reportLine(messages, reportPath)
const report = reportLine(messages, reportState)
const tail = error.split(/\r\n|[\n\r\u2028\u2029]/u).slice(-DETAIL_TAIL_LINES).join('\n')
const budget = DETAIL_BUDGET - advice.length - report.length - messages.diagnosticTruncated.length - 1
const shortened = tail.slice(-budget).replace(/^[\uDC00-\uDFFF]/u, '')
return `${shortened === error ? error : `${messages.diagnosticTruncated}\n${shortened}`}${report}${advice}`
}
function reportLine(messages: DesktopMessages, reportPath: string | undefined): string {
return reportPath === undefined ? '' : `\n${formatDesktopMessage(messages.reportWrittenTo, { path: reportPath })}`
function reportLine(messages: DesktopMessages, state: ReportState): string {
if (state.kind === 'pending') return `\n${messages.reportPending}`
if (state.kind === 'failed') return `\n${messages.reportUnavailable}`
return `\n${formatDesktopMessage(messages.reportWrittenTo, { path: state.path })}`
}
/** Deduplicates fatal reports while keeping explicit recovery-operation failures actionable. */
export class DesktopFatalRecovery {
private reported = false
private reportState: ReportState = { kind: 'pending' }
/** @param operations - Native presentation, report persistence, and application-owned shutdown operations. */
constructor(private readonly operations: RecoveryOperations) {}
@@ -57,7 +61,7 @@ export class DesktopFatalRecovery {
/**
* Show the first fatal error; later reports cannot replace it or open another dialog.
* The crash report is written first, bounded by {@link CRASH_REPORT_WAIT_MS}, so the dialog can name it;
* a slow or failed write shows the dialog without a path.
* a slow or failed write shows its status. Retrieving a report rechecks the same write.
* @param error - Fatal failure, including nested diagnostic causes.
* @param source - Where the failure surfaced, recorded in the report.
* @returns Completion of the user's recovery action; duplicate reports resolve immediately.
@@ -66,25 +70,42 @@ export class DesktopFatalRecovery {
if (this.reported) return
this.reported = true
const messages = this.operations.messages()
const reportPath = await this.persist(error, source)
const report = this.persist(error, source)
await this.waitForReport(report)
let detail = desktopErrorState(error).message
let message = messages.fatalSummary
for (;;) {
const addressInUse = /\blisten EADDRINUSE\b/u.test(detail)
const buttons = addressInUse
? [messages.exitApplication, messages.restartApplication]
: [messages.exitApplication, messages.restartApplication, messages.disableThirdPartyPlugins]
const reportButton = this.reportState.kind === 'failed' ? undefined : buttons.length
if (reportButton !== undefined) buttons.push(messages.getDiagnosticReport)
const { response } = await this.operations.show({
type: 'error',
title: messages.startupFailed,
message,
detail: addressInUse
? `${messages.startupAddressInUse}${reportLine(messages, reportPath)}`
: dialogDetail(detail, messages, reportPath),
buttons: addressInUse
? [messages.exitApplication, messages.restartApplication]
: [messages.exitApplication, messages.restartApplication, messages.disableThirdPartyPlugins],
? `${messages.startupAddressInUse}${reportLine(messages, this.reportState)}`
: dialogDetail(detail, messages, this.reportState),
buttons,
defaultId: 1,
cancelId: 0,
noLink: true,
})
if (response === reportButton) {
await this.waitForReport(report)
if (this.reportState.kind === 'ready') {
try {
await this.operations.revealReport(this.reportState.path)
message = messages.reportShareHint
} catch (failure) {
console.error('dsh desktop: could not reveal crash report', failure)
message = messages.reportRevealFailed
}
}
continue
}
if (response === 0) {
try { await this.operations.stop() } catch (failure) { console.error(failure) }
this.operations.exit()
@@ -103,16 +124,23 @@ export class DesktopFatalRecovery {
}
}
private async persist(error: unknown, source: CrashReportSource): Promise<string | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined
private async persist(error: unknown, source: CrashReportSource): Promise<void> {
try {
return await Promise.race([
this.operations.writeReport(error, source),
new Promise<undefined>((resolve) => { timer = setTimeout(() => { resolve(undefined) }, CRASH_REPORT_WAIT_MS) }),
])
const path = await this.operations.writeReport(error, source)
this.reportState = path === undefined ? { kind: 'failed' } : { kind: 'ready', path }
} catch (failure) {
console.error('dsh desktop: crash report failed', failure)
return undefined
this.reportState = { kind: 'failed' }
}
}
private async waitForReport(report: Promise<void>): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined
try {
await Promise.race([
report,
new Promise<void>((resolve) => { timer = setTimeout(resolve, CRASH_REPORT_WAIT_MS) }),
])
} finally {
clearTimeout(timer)
}
+26 -2
View File
@@ -2,8 +2,10 @@
import { spawn, type ChildProcess } from 'node:child_process'
import { join } from 'node:path'
import { z } from 'zod'
import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account'
import { desktopNodeEnvironment } from './node-environment.ts'
import { parsePluginOperationRecord, type PluginOperationRecord, type PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
interface ReadyEvent {
readonly type: 'ready'
@@ -23,7 +25,10 @@ interface PlatformSessionEvent {
readonly session: PlatformSession | null
}
type DesktopHostEvent = ReadyEvent | FatalEvent | PlatformSessionEvent | { readonly type: 'shutdown-complete' } | {
type DesktopHostEvent = ReadyEvent | FatalEvent | PlatformSessionEvent | {
readonly type: 'starting'
readonly runId: PluginOperationRunId
} | { readonly type: 'shutdown-complete' } | {
readonly type: 'file-drag-resource'
readonly requestId: number
readonly resource: { readonly path: string; readonly sha256: string; readonly size: number } | null
@@ -54,11 +59,14 @@ export interface DesktopQuitInspection {
export const QUIT_INSPECTION_DEADLINE_MS = 2_000
const MAX_HOST_DIAGNOSTIC_CHARS = 64 * 1024
const runIdSchema = z.uuid()
function isDesktopHostEvent(message: unknown): message is DesktopHostEvent {
if (typeof message !== 'object' || message === null || !('type' in message)) return false
const candidate = message as Record<string, unknown>
switch (candidate.type) {
case 'starting':
return runIdSchema.safeParse(candidate.runId).success
case 'shutdown-complete':
return true
case 'ready':
@@ -148,6 +156,7 @@ export class DesktopHostFatalError extends Error {
/** One Web backend running under the Electron executable in Node mode. */
export class DesktopHostProcess {
private runId: PluginOperationRunId | undefined
private child: ChildProcess | undefined
private readyResolve!: (ready: DesktopHostReady) => void
private readyReject!: (error: Error) => void
@@ -177,6 +186,7 @@ export class DesktopHostProcess {
* `office-skills` resources fail Host startup.
* @param packageManager - Bundled pnpm entry and Node launcher directory, scoped to package operations.
* @param onPlatformSession - Private credential updates for embedded Platform views.
* @param onPluginOperation - Optional diagnostic sink; malformed records are ignored without failing the Host.
*/
constructor(
private readonly node: string,
@@ -189,6 +199,7 @@ export class DesktopHostProcess {
private readonly packageManager?: { readonly pnpm: string; readonly nodeBin: string },
private readonly onPlatformSession?: (session: PlatformSession | null) => void,
private readonly onPluginOperation?: (record: PluginOperationRecord) => void,
) {}
/**
@@ -216,12 +227,24 @@ export class DesktopHostProcess {
child.stderr?.on('data', (chunk: string) => { this.stderr = (this.stderr + chunk).slice(-MAX_HOST_DIAGNOSTIC_CHARS) })
child.stdout?.pipe(process.stdout)
child.on('message', (message: unknown) => {
if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'plugin-operation') {
const record = 'record' in message ? parsePluginOperationRecord(message.record) : undefined
if (record !== undefined && record.runId === this.runId) {
try { this.onPluginOperation?.(record) }
catch (_error) {
// Diagnostic persistence cannot invalidate the Host's business IPC channel.
console.error('desktop plugin operation diagnostic sink failed')
}
}
return
}
if (!isDesktopHostEvent(message)) {
this.fail(new Error('dsh desktop host sent an invalid IPC event'))
child.kill('SIGTERM')
return
}
if (message.type === 'ready') this.readyResolve({ url: message.url, injections: message.injections })
if (message.type === 'starting') this.runId = message.runId
else if (message.type === 'ready') this.readyResolve({ url: message.url, injections: message.injections })
else if (message.type === 'platform-session') this.onPlatformSession?.(message.session)
else if (message.type === 'shutdown-complete') {
if (this.stopping) this.shutdownCompleted = true
@@ -344,6 +367,7 @@ export class DesktopHostProcess {
}
private fail(error: Error): void {
if (this.runId !== undefined) Object.assign(error, { hostRunId: this.runId })
this.onPlatformSession?.(null)
this.readyReject(error)
for (const request of this.controlRequests.values()) request.reject(error)
+38
View File
@@ -0,0 +1,38 @@
/** Last confirmed shell language, available even when the Host cannot start. */
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { resolveDesktopLocale, type DesktopLocale } from './locale.ts'
/**
* Read the last confirmed language without requiring Host settings.
* @param userData - Electron userData directory.
* @returns Cached language, or undefined when missing, invalid or unreadable.
*/
export function readDesktopLocaleCache(userData: string): DesktopLocale['id'] | undefined {
try {
const value = readFileSync(join(userData, 'desktop', 'locale-cache'), 'utf8').trim()
const locale = resolveDesktopLocale(value)
if (locale.id === value) return locale.id
throw new Error('expected a canonical Desktop locale id')
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('desktop locale cache: using system language because the cache could not be read', error)
}
return undefined
}
}
/**
* Remember a confirmed language; write failure leaves the active language unchanged.
* @param userData - Electron userData directory.
* @param locale - Language confirmed by Host settings or the owned renderer.
*/
export function writeDesktopLocaleCache(userData: string, locale: DesktopLocale['id']): void {
try {
const directory = join(userData, 'desktop')
mkdirSync(directory, { recursive: true, mode: 0o700 })
writeFileSync(join(directory, 'locale-cache'), `${locale}\n`, { mode: 0o600 })
} catch (error) {
console.warn('desktop locale cache: language could not be saved for the next startup', error)
}
}
+40
View File
@@ -61,6 +61,11 @@ export const en = {
startupAddressInUse: 'Another DSH instance (such as dsh web or the desktop app) is running. They cannot start at the same time. Quit the other running DSH instance, then restart.',
diagnosticTruncated: '… Error details shortened.',
reportWrittenTo: 'Diagnostic report: {path}',
getDiagnosticReport: 'Get diagnostic report',
reportPending: 'The diagnostic report is still being saved. Choose Get diagnostic report to check again.',
reportUnavailable: 'The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support.',
reportShareHint: 'The report location has been opened. Attach the selected file to your support ticket.',
reportRevealFailed: 'The report location could not be opened. Use the path below to find the file.',
startupReinstallAdvice: 'If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.',
exitApplication: 'Exit',
restartApplication: 'Restart',
@@ -235,6 +240,11 @@ export const zh = {
startupAddressInUse: '有其他正在运行的 DSH(如其他 dsh web、桌面端),无法同时启动,请退出其他正在运行的 DSH 后重启。',
diagnosticTruncated: '… 错误详情已截短。',
reportWrittenTo: '诊断报告:{path}',
getDiagnosticReport: '获取诊断报告',
reportPending: '诊断报告仍在保存,可点击“获取诊断报告”再次检查。',
reportUnavailable: '诊断报告未能保存,反馈问题时可提供此窗口的截图。',
reportShareHint: '已打开报告位置,请将选中的文件附在支持工单中。',
reportRevealFailed: '无法打开报告位置,请通过下方路径查找文件。',
startupReinstallAdvice: '如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。',
exitApplication: '退出',
restartApplication: '重启',
@@ -407,6 +417,11 @@ export const ja = {
startupAddressInUse: '別の DSH インスタンス (dsh web やデスクトップアプリなど) が実行中です。同時に起動することはできません。実行中の他の DSH インスタンスを終了してから再起動してください。',
diagnosticTruncated: '… エラー詳細は省略されています。',
reportWrittenTo: '診断レポート: {path}',
getDiagnosticReport: '診断レポートを取得',
reportPending: '診断レポートを保存中です。「診断レポートを取得」を選択して再度確認してください。',
reportUnavailable: '診断レポートを保存できませんでした。サポートへのお問い合わせ時に、このダイアログのスクリーンショットを提供できます。',
reportShareHint: 'レポートの保存場所を開きました。選択されたファイルをサポートチケットに添付してください。',
reportRevealFailed: 'レポートの保存場所を開けませんでした。以下のパスからファイルを探してください。',
startupReinstallAdvice: 'アプリケーションファイルが見つからないか破損している場合は、アプリケーションを閉じて再インストールしてください。タスクは別途保存されています。',
exitApplication: '終了',
restartApplication: '再起動',
@@ -579,6 +594,11 @@ export const es = {
startupAddressInUse: 'Se está ejecutando otra instancia de DSH (como la web de dsh o la aplicación de escritorio). No pueden empezar al mismo tiempo. Salga de la otra instancia DSH en ejecución y luego reinicie.',
diagnosticTruncated: '… Detalles del error acortados.',
reportWrittenTo: 'Informe de diagnóstico: {path}',
getDiagnosticReport: 'Obtener informe de diagnóstico',
reportPending: 'El informe de diagnóstico se está guardando. Seleccione Obtener informe de diagnóstico para volver a comprobarlo.',
reportUnavailable: 'No se pudo guardar el informe de diagnóstico. Puede proporcionar una captura de pantalla de este diálogo al solicitar asistencia.',
reportShareHint: 'Se ha abierto la ubicación del informe. Adjunte el archivo seleccionado a su solicitud de asistencia.',
reportRevealFailed: 'No se pudo abrir la ubicación del informe. Use la ruta que aparece a continuación para encontrar el archivo.',
startupReinstallAdvice: 'Si faltan archivos de la aplicación o están dañados, ciérrela y vuelva a instalarla. Sus tareas se almacenan por separado.',
exitApplication: 'Salir',
restartApplication: 'Reiniciar',
@@ -751,6 +771,11 @@ export const fr = {
startupAddressInUse: "Une autre instance DSH (telle que le Web dsh ou l'application de bureau) est en cours d'exécution. Ils ne peuvent pas démarrer en même temps. Quittez l'autre instance DSH en cours d'exécution, puis redémarrez.",
diagnosticTruncated: '… Détails de l’erreur raccourcis.',
reportWrittenTo: 'Rapport de diagnostic : {path}',
getDiagnosticReport: 'Obtenir le rapport de diagnostic',
reportPending: 'Le rapport de diagnostic est en cours d’enregistrement. Sélectionnez Obtenir le rapport de diagnostic pour vérifier à nouveau.',
reportUnavailable: 'Le rapport de diagnostic n’a pas pu être enregistré. Vous pouvez fournir une capture d’écran de cette boîte de dialogue lorsque vous contactez l’assistance.',
reportShareHint: 'L’emplacement du rapport a été ouvert. Joignez le fichier sélectionné à votre demande d’assistance.',
reportRevealFailed: 'L’emplacement du rapport n’a pas pu être ouvert. Utilisez le chemin ci-dessous pour trouver le fichier.',
startupReinstallAdvice: "Si les fichiers de l'application sont manquants ou endommagés, fermez l'application et réinstallez-la. Vos tâches sont stockées séparément.",
exitApplication: 'Quitter',
restartApplication: 'Redémarrer',
@@ -923,6 +948,11 @@ export const de = {
startupAddressInUse: 'Eine andere DSH-Instanz (z. B. dsh Web oder die Desktop-App) wird ausgeführt. Sie können nicht gleichzeitig starten. Beenden Sie die andere laufende DSH-Instanz und starten Sie sie neu.',
diagnosticTruncated: '… Fehlerdetails gekürzt.',
reportWrittenTo: 'Diagnosebericht: {path}',
getDiagnosticReport: 'Diagnosebericht abrufen',
reportPending: 'Der Diagnosebericht wird noch gespeichert. Wählen Sie „Diagnosebericht abrufen“, um ihn erneut zu prüfen.',
reportUnavailable: 'Der Diagnosebericht konnte nicht gespeichert werden. Sie können bei einer Supportanfrage einen Screenshot dieses Dialogs bereitstellen.',
reportShareHint: 'Der Speicherort des Berichts wurde geöffnet. Fügen Sie die ausgewählte Datei Ihrer Supportanfrage bei.',
reportRevealFailed: 'Der Speicherort des Berichts konnte nicht geöffnet werden. Verwenden Sie den folgenden Pfad, um die Datei zu finden.',
startupReinstallAdvice: 'Wenn Anwendungsdateien fehlen oder beschädigt sind, schließen Sie die Anwendung und installieren Sie sie erneut. Ihre Aufgaben werden separat gespeichert.',
exitApplication: 'Beenden',
restartApplication: 'Neustart',
@@ -1095,6 +1125,11 @@ export const ru = {
startupAddressInUse: 'Другой экземпляр DSH (например, веб-приложение dsh или настольное приложение) запущен. Они не могут начаться одновременно. Закройте другой работающий экземпляр DSH, а затем перезапустите.',
diagnosticTruncated: '… Подробности об ошибках сокращены.',
reportWrittenTo: 'Диагностический отчет: {path}',
getDiagnosticReport: 'Получить диагностический отчет',
reportPending: 'Диагностический отчет еще сохраняется. Выберите «Получить диагностический отчет», чтобы проверить еще раз.',
reportUnavailable: 'Не удалось сохранить диагностический отчет. При обращении в службу поддержки можно приложить снимок экрана этого диалогового окна.',
reportShareHint: 'Открыта папка с отчетом. Прикрепите выбранный файл к обращению в службу поддержки.',
reportRevealFailed: 'Не удалось открыть папку с отчетом. Найдите файл по указанному ниже пути.',
startupReinstallAdvice: 'Если файлы приложения отсутствуют или повреждены, закройте приложение и переустановите его. Ваши задачи хранятся отдельно.',
exitApplication: 'Выход',
restartApplication: 'Перезапустить',
@@ -1267,6 +1302,11 @@ export const pt = {
startupAddressInUse: 'Outra instância DSH (como dsh web ou aplicativo de desktop) está em execução. Eles não podem começar ao mesmo tempo. Saia da outra instância DSH em execução e reinicie.',
diagnosticTruncated: '… Detalhes do erro reduzidos.',
reportWrittenTo: 'Relatório de diagnóstico: {path}',
getDiagnosticReport: 'Obter relatório de diagnóstico',
reportPending: 'O relatório de diagnóstico ainda está sendo salvo. Selecione Obter relatório de diagnóstico para verificar novamente.',
reportUnavailable: 'Não foi possível salvar o relatório de diagnóstico. Você pode fornecer uma captura de tela desta caixa de diálogo ao solicitar suporte.',
reportShareHint: 'O local do relatório foi aberto. Anexe o arquivo selecionado à sua solicitação de suporte.',
reportRevealFailed: 'Não foi possível abrir o local do relatório. Use o caminho abaixo para encontrar o arquivo.',
startupReinstallAdvice: 'Se os arquivos do aplicativo estiverem ausentes ou danificados, feche o aplicativo e reinstale-o. Suas tarefas são armazenadas separadamente.',
exitApplication: 'Sair',
restartApplication: 'Reiniciar',
+90 -19
View File
@@ -2,7 +2,7 @@ import type { ProductEventMap, ProductEvent } from '@deepseek-ai/dsh-client-prod
import { WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts'
/** Electron shell: desktop project ownership, custom protocol, windows, and lifecycle. */
import { readFile, writeFile } from 'node:fs/promises'
import { access, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
@@ -41,6 +41,8 @@ import { DesktopCommandManager } from './command-management.ts'
import { serveWebDocument, authenticateWebHost, forwardWebRequest } from './web-document.ts'
import { DesktopFatalRecovery } from './fatal-recovery.ts'
import { pruneCrashReports, RendererConsoleTail, writeCrashReport, type CrashReportSource } from './crash-report.ts'
import { OperationJournal } from './operation-journal.ts'
import { runOperationReportJob, type OperationReportJobResult } from './operation-report-job.ts'
import { openWelcomeWindow } from './welcome-window.ts'
import { WELCOME_IPC, needsWelcome, type WelcomeNotice } from './welcome-api.ts'
import { connectDesktopWelcome, type DesktopWelcomeBackend } from './welcome-backend.ts'
@@ -55,6 +57,7 @@ import { desktopClientMetadata, desktopClientVersion } from './client-metadata.t
import { DesktopMandatoryUpdateWindow } from './mandatory-update-window.ts'
import { DesktopPolicyTestAuth } from './policy-test-auth.ts'
import { readDesktopSettings } from './settings.ts'
import { readDesktopLocaleCache, writeDesktopLocaleCache } from './locale-cache.ts'
import { DesktopUpdateDialog, type UpdateDialogOptions } from './update-dialog.ts'
import { readDesktopRuntime } from './runtime-tree.ts'
import { DesktopBrowserGuests } from './browser-guests.ts'
@@ -65,14 +68,14 @@ import { DesktopTray } from './tray.ts'
import { DesktopBackgroundNotice } from './background-notice.ts'
let focusPrimaryWindow = (): void => {}
let stopForRecovery = async (): Promise<void> => {}
let stopForRecovery = async (): Promise<void> => { await stopOperationReports() }
let shuttingDown = false
/**
* Set by quit entries that must not ask: crash recovery exit and restart, and the
* development restart command. The installer handoff has its own before-quit branch.
*/
let skipQuitConfirmation = false
let windowsLanguage: string | undefined
let windowsLanguage: string | undefined = readDesktopLocaleCache(app.getPath('userData'))
/**
* Whether the backend has reached ready: false until the first ready, back to
* false when a restart returns it to starting, frozen during shutdown so a
@@ -106,10 +109,39 @@ const recovery = new DesktopFatalRecovery({
exit: () => { quitWithoutConfirmation() },
restart: () => { app.relaunch(); quitWithoutConfirmation() },
writeReport: (error, source) => persistCrashReport(error, source),
revealReport: async (path) => { await access(path); shell.showItemInFolder(path) },
})
let operationJournal: OperationJournal | undefined
let operationReportJob: Promise<OperationReportJobResult> | undefined
let operationReportAbort: AbortController | undefined
let operationReportsStopping = false
let operationReportStop: Promise<void> | undefined
/** Bound application shutdown waiting without claiming that an unresponsive Worker has exited. */
function stopOperationReports(): Promise<void> {
operationReportStop ??= waitForOperationReports()
return operationReportStop
}
async function waitForOperationReports(): Promise<void> {
operationReportsStopping = true
operationReportAbort?.abort()
const job = operationReportJob
if (job === undefined) return
let timer: ReturnType<typeof setTimeout> | undefined
try {
const exited = await Promise.race([job.then(() => true), new Promise<false>((resolve) => {
timer = setTimeout(() => { resolve(false) }, 500)
})])
if (!exited) console.error('dsh desktop: operation report Worker has not exited; continuing shutdown')
} finally { clearTimeout(timer) }
}
function persistCrashReport(error: unknown, source: CrashReportSource): Promise<string | undefined> {
return writeCrashReport(app.getPath('logs'), {
const directory = app.getPath('logs')
const report = writeCrashReport(directory, {
operationHistoryPlanned: !shuttingDown && !operationReportsStopping,
source,
phase: backendReady ? 'running' : 'startup',
error,
@@ -121,6 +153,17 @@ function persistCrashReport(error: unknown, source: CrashReportSource): Promise<
},
time: new Date(),
})
void report.then((path) => {
if (path !== undefined && operationReportJob === undefined && !shuttingDown && !operationReportsStopping) {
operationReportAbort = new AbortController()
operationReportJob = runOperationReportJob({ reportPath: path, directory: join(app.getPath('userData'), 'plugin-operations'),
limits: { bytes: 64 * 1024, recordBytes: 4096, records: 100, outputBytes: 64 * 1024 },
journal: operationJournal?.status() ?? null,
}, { timeoutMs: 500, cancellationGraceMs: 100 }, operationReportAbort.signal)
void operationReportJob.finally(() => { operationReportJob = undefined; operationReportAbort = undefined })
}
}).catch((_error: unknown) => { /* Basic persistence failure is owned by fatal recovery. */ })
return report
}
function reportFatal(error: unknown, source: CrashReportSource): void {
@@ -130,7 +173,12 @@ function reportFatal(error: unknown, source: CrashReportSource): void {
void persistCrashReport(error, source)
return
}
void recovery.report(error, source).catch((failure: unknown) => { console.error(failure); app.exit(1) })
void recovery.report(error, source).catch(async (failure: unknown) => {
console.error(failure)
shuttingDown = true
await stopOperationReports()
app.exit(1)
})
}
protocol.registerSchemesAsPrivileged([{
@@ -374,7 +422,8 @@ async function main(): Promise<void> {
let updateStopFailure: DesktopHostUncleanExitError | undefined
let updateState: DesktopUpdateState = { phase: 'idle' }
const systemLanguages = app.getPreferredSystemLanguages()
let locale = resolveDesktopStartupLocale(null, systemLanguages)
let locale = windowsLanguage === undefined
? resolveDesktopStartupLocale(null, systemLanguages) : resolveDesktopLocale(windowsLanguage)
windowsLanguage = locale.id
let mandatoryPolicy: DesktopMandatoryUpdatePolicy | undefined
let mandatoryUI: DesktopMandatoryUpdateWindow | undefined
@@ -470,7 +519,12 @@ async function main(): Promise<void> {
const host = new DesktopHostProcess(resources.node, resources.dsh, activeProject,
hostInspectPort, { ...hostEnvironment, DSH_CLIENT_VERSION: desktopClientVersion() }, onFailure,
primaryRuntime,
resources, (next) => { platformView.setSession(next) })
resources, (next) => { platformView.setSession(next) }, (record) => {
operationJournal ??= new OperationJournal(join(app.getPath('userData'), 'plugin-operations'), {
segmentBytes: 256 * 1024, recordBytes: 4096, queuedBytes: 64 * 1024,
})
operationJournal.enqueue(JSON.stringify(record))
})
return {
start: async () => {
const ready = await host.start()
@@ -565,6 +619,10 @@ async function main(): Promise<void> {
fileDragStopped = false
}
const restoreHost = state.failedOperation === 'install' && updateStoppedHost && !quitting
if (state.failedOperation === 'install' && !quitting) {
operationReportsStopping = shuttingDown
operationReportStop = undefined
}
shellInstallerOwnsQuit = false
updateStoppedHost = false
if (restoreHost) {
@@ -593,7 +651,11 @@ async function main(): Promise<void> {
if (backend.host === undefined || welcomeBackend === undefined) throw new Error('desktop welcome: backend unavailable')
return welcomeBackend.read()
}
stopForRecovery = () => backend.close()
stopForRecovery = async () => {
const reports = stopOperationReports()
try { await backend.close() }
finally { await Promise.all([operationJournal?.drain(500), reports]) }
}
const reconcileBackend = (): Promise<void> => {
startup ??= (async () => {
@@ -651,14 +713,17 @@ async function main(): Promise<void> {
await disposeFileDrag().catch((error: unknown) => { console.error(error) })
requireCleanStop = true
updateStopFailure = undefined
await backend.stop()
await Promise.all([backend.stop(), stopOperationReports()])
updateStoppedHost = true
// The backend's async cleanup callback can assign this after the reset above.
const stopFailure = updateStopFailure as DesktopHostUncleanExitError | undefined
if (stopFailure !== undefined) throw new DesktopUpdatePreparationError('stop-failed', locale.messages.updateStopFailed, stopFailure.message)
await operationJournal?.drain(500)
updateJournal?.action('install-confirmed')
shellInstallerOwnsQuit = true
} catch (error) {
operationReportsStopping = shuttingDown
operationReportStop = undefined
if (!updateStoppedHost) await host.updateTasks('unlock').catch((unlockError: unknown) => { console.error(unlockError) })
throw error
} finally {
@@ -793,6 +858,7 @@ async function main(): Promise<void> {
if (window === undefined || event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame
|| typeof next !== 'string') return
const current = resolveDesktopStartupLocale(next, systemLanguages)
writeDesktopLocaleCache(app.getPath('userData'), current.id)
if (current.id === locale.id) return
locale = current
platformView.notifyLocaleChanged()
@@ -1076,13 +1142,11 @@ async function main(): Promise<void> {
Menu.buildFromTemplate(items).popup({ window, x: Math.round(x * zoom), y: Math.round(y * zoom), callback: resolve })
})
})
ipcMain.on(DESKTOP_IPC.windowsAppearance, (event, language: unknown, color: unknown, symbolColor: unknown) => {
ipcMain.on(DESKTOP_IPC.windowsAppearance, (event, _language: unknown, color: unknown, symbolColor: unknown) => {
if (mainWindow === undefined || event.sender !== mainWindow.webContents
|| event.senderFrame !== mainWindow.webContents.mainFrame) return
if (!event.senderFrame.url.startsWith(`${SCHEME}://app/`)) return
if (typeof language === 'string' && /^[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$/u.test(language)) {
windowsLanguage = language
}
// Document lang starts as English before Host locale bootstrap; only localeChanged owns shell language.
// Empty colors precede client stylesheet installation; only CSS color values cross IPC.
const validColor = (value: unknown): value is string => typeof value === 'string'
&& /^(?:#[\da-f]{3,8}|rgba?\([\d.,%\s]+\))$/iu.test(value)
@@ -1236,6 +1300,7 @@ async function main(): Promise<void> {
const state = await readWelcomeState()
if (isQuitting() || backend.state.phase !== 'ready') return
locale = resolveDesktopStartupLocale(state.localePreference, systemLanguages)
writeDesktopLocaleCache(app.getPath('userData'), locale.id)
windowsLanguage = locale.id
refreshApplicationMenu()
if (!enteredWorkspace && needsWelcome({ loggedIn: state.loggedIn, hasApiKey: state.hasApiKey })) {
@@ -1288,11 +1353,15 @@ async function main(): Promise<void> {
updateSchedule.dispose()
updateDialog.dispose()
mandatoryUI?.dispose()
void Promise.all([Promise.resolve(mandatoryPolicy?.dispose()).then(() => policyAuth?.dispose()), backend.close(),
// A Platform cleanup failure is logged without cutting the remaining Host shutdown short.
platformView.dispose().catch((error: unknown) => { console.error(error) }),
disposeFileDrag().catch((error: unknown) => { console.error(error) })])
.catch((error: unknown) => { console.error(error) }).finally(() => { app.quit() })
void Promise.all([stopOperationReports(), Promise.resolve(mandatoryPolicy?.dispose()).then(() => policyAuth?.dispose()),
backend.close().then(async () => { await operationJournal?.drain(500) }, async (error: unknown) => {
await operationJournal?.drain(500)
throw error
}),
platformView.dispose(),
disposeFileDrag(),
].map(cleanup => cleanup.catch((error: unknown) => { console.error(error) })))
.then(() => { app.quit() })
}
app.on('before-quit', (event) => {
if (shellInstallerOwnsQuit) {
@@ -1381,7 +1450,9 @@ if (ownsDesktopInstance) void app.whenReady().then(main).catch(async (error: unk
await writeFile(diagnosticFile, `${error instanceof Error ? error.stack ?? message : message}\n`).catch(() => undefined)
}
reportFatal(error, 'main')
}).catch((error: unknown) => {
}).catch(async (error: unknown) => {
console.error(error)
shuttingDown = true
await stopOperationReports()
app.exit(1)
})
+120
View File
@@ -0,0 +1,120 @@
/** Bounded, cancellable reads of Desktop-owned plugin operation history. */
import { open } from 'node:fs/promises'
import { join } from 'node:path'
import { setImmediate } from 'node:timers/promises'
import { parsePluginOperationRecord, type PluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
/** Resource budgets for auxiliary history collection, independent of basic crash report writing. */
export interface OperationHistoryReadLimits {
readonly bytes: number
readonly recordBytes: number
readonly records: number
}
/** Collection facts; incomplete history must not be interpreted as absence of plugin changes. */
export interface OperationHistoryReadResult {
readonly records: readonly PluginOperationRecord[]
readonly bytesRead: number
/** Distinct files from which at least one byte was read. */
readonly filesRead: number
readonly truncated: boolean
readonly invalidRecords: number
readonly unavailableFiles: number
readonly cancelled: boolean
}
/**
* Read only the bounded tails of the two owned history files, newest segment first.
* Cancellation is observed between bounded records after yielding to Worker messages and stops subsequent I/O and parsing.
* An already-issued OS read must settle before its handle closes.
* @param directory - Desktop's operation history directory; unrelated files are never enumerated.
* @param limits - Positive byte, record-size and record-count budgets.
* @param signal - Caller-owned collection deadline or shutdown cancellation.
* @returns Partial records and explicit omissions; filesystem failures never reject the collection.
*/
export async function readOperationHistory(
directory: string,
limits: OperationHistoryReadLimits,
signal: AbortSignal,
): Promise<OperationHistoryReadResult> {
if (![limits.bytes, limits.recordBytes, limits.records].every(value => Number.isSafeInteger(value) && value > 0)) {
throw new RangeError('Operation history budgets must be positive safe integers')
}
await setImmediate()
const cancelled = (): boolean => signal.aborted
const records: PluginOperationRecord[] = []
let bytesRead = 0
const seenFiles = new Set<string>()
let truncated = false
let invalidRecords = 0
let unavailableFiles = 0
for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
if (cancelled()) break
try {
await using handle = await open(join(directory, name), 'r')
if (cancelled()) break
const fileStat = await handle.stat()
if (cancelled()) break
if (!fileStat.isFile()) {
unavailableFiles++
continue
}
const identity = `${String(fileStat.dev)}:${String(fileStat.ino)}`
if (seenFiles.has(identity)) {
truncated = true
continue
}
if (fileStat.size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
truncated = true
break
}
const readLength = Math.min(fileStat.size, limits.bytes - bytesRead)
const readStart = fileStat.size - readLength
const buffer = Buffer.alloc(readLength)
let readOffset = 0
while (readOffset < readLength && !cancelled()) {
const read = await handle.read(buffer, readOffset, Math.min(16 * 1024, readLength - readOffset), readStart + readOffset)
bytesRead += read.bytesRead
if (read.bytesRead === 0) break
readOffset += read.bytesRead
}
if (readOffset > 0) seenFiles.add(identity)
if (cancelled()) break
truncated ||= readStart > 0 || readOffset < readLength
// An unterminated last record can still be in flight; never parse it as a committed record.
if (readOffset === 0) continue
let lineEnd = buffer.lastIndexOf(10, readOffset - 1)
if (lineEnd !== readOffset - 1) truncated = true
while (lineEnd >= 0 && records.length < limits.records && !cancelled()) {
await setImmediate()
if (cancelled()) break
const previousLineEnd = lineEnd === 0 ? -1 : buffer.lastIndexOf(10, lineEnd - 1)
if (previousLineEnd < 0 && readStart > 0) {
truncated = true
break
}
const recordBytes = lineEnd - previousLineEnd - 1
if (recordBytes > limits.recordBytes) {
invalidRecords++
} else if (recordBytes > 0) {
try {
const value: unknown = JSON.parse(buffer.subarray(previousLineEnd + 1, lineEnd).toString('utf8'))
const record = parsePluginOperationRecord(value)
if (record === undefined) invalidRecords++
else records.push(record)
} catch (_error) {
// A corrupt record does not invalidate independently delimited older records.
invalidRecords++
}
}
lineEnd = previousLineEnd
}
if (lineEnd >= 0) truncated = true
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') unavailableFiles++
}
}
return { records, bytesRead, filesRead: seenFiles.size, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() }
}
+208
View File
@@ -0,0 +1,208 @@
/** Single-shell, bounded persistence for already-projected operation diagnostics. */
import { mkdir, open, rename, stat, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
/** Budgets include serialized JSON and its line delimiter. */
export interface OperationJournalLimits {
readonly segmentBytes: number
readonly recordBytes: number
readonly queuedBytes: number
}
/** In-memory omissions for the current shell lifetime; missing records never imply no operations occurred. */
export interface OperationJournalStatus {
readonly dropped: number
readonly failed: number
readonly queuedBytes: number
readonly disabled: boolean
/** Damaged or oversized segments repaired; their lost record count is unknown. */
readonly repairedSegments: number
}
/** Owns two known files and one serial writer; the owning shell must exclude other writers. */
export class OperationJournal {
private readonly queue: string[] = []
private queuedBytes = 0
private dropped = 0
private failed = 0
private repairedSegments = 0
private disabled = false
private closed = false
private writing: Promise<void> | undefined
private initialized = false
private readonly abort = new AbortController()
/**
* @param directory - Directory reserved for the shell's operation journal.
* @param limits - Positive byte budgets, with recordBytes no greater than either other budget.
*/
constructor(
private readonly directory: string,
private readonly limits: OperationJournalLimits,
) {
if (![limits.segmentBytes, limits.recordBytes, limits.queuedBytes].every(value => Number.isSafeInteger(value) && value > 0)
|| limits.recordBytes > limits.segmentBytes || limits.recordBytes > limits.queuedBytes) {
throw new RangeError('Invalid operation journal budgets')
}
}
/**
* Queue one prevalidated, whitelisted JSON record without awaiting disk I/O.
* @param record - An already serialized JSON object without literal line delimiters.
* @returns Whether the record was accepted; disk failures are reported separately by status().
*/
enqueue(record: string): boolean {
const line = record + '\n'
const bytes = Buffer.byteLength(line)
if (this.closed || this.disabled || bytes > this.limits.recordBytes
|| bytes + this.queuedBytes > this.limits.queuedBytes || /[\r\n]/u.test(record)) {
this.dropped++
return false
}
this.queue.push(line)
this.queuedBytes += bytes
this.startWriter()
return true
}
/** @returns Current queue occupancy and omission counters. */
status(): OperationJournalStatus {
return {
dropped: this.dropped,
failed: this.failed,
queuedBytes: this.queuedBytes,
disabled: this.disabled,
repairedSegments: this.repairedSegments,
}
}
/** Stop accepting records and await completion of the owned writer. */
async close(): Promise<void> {
this.closed = true
while (this.writing !== undefined) await this.writing
}
/**
* Wait for queued records during shutdown or installer handoff without holding the application indefinitely.
* @param timeoutMs - Waiting budget before disabling the writer and cancelling subsequent I/O.
* @returns True after the queue settles successfully; false immediately when disabled, or on failure or deadline.
* False does not confirm that an issued OS request has settled.
*/
async drain(timeoutMs: number): Promise<boolean> {
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new RangeError('Invalid journal drain deadline')
if (this.disabled) return false
let timer: ReturnType<typeof setTimeout> | undefined
try {
return await Promise.race([
(async () => {
while (this.writing !== undefined) await this.writing
return !this.disabled
})(),
new Promise<false>((resolve) => {
timer = setTimeout(() => {
this.disabled = true
this.abort.abort()
resolve(false)
}, timeoutMs)
}),
])
} finally {
clearTimeout(timer)
}
}
private startWriter(): void {
this.writing ??= this.writeQueue().finally(() => {
this.writing = undefined
if (this.queue.length > 0) this.startWriter()
})
}
private async writeQueue(): Promise<void> {
try {
await mkdir(this.directory, { recursive: true, mode: 0o700 })
this.abort.signal.throwIfAborted()
const current = join(this.directory, 'operations.jsonl')
const previous = join(this.directory, 'operations.previous.jsonl')
if (!this.initialized) {
await this.prepareSegments(current, previous)
this.initialized = true
}
for (let line = this.queue[0]; line !== undefined; line = this.queue[0]) {
this.abort.signal.throwIfAborted()
const bytes = Buffer.byteLength(line)
let size = 0
try {
size = (await stat(current)).size
}
catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
this.abort.signal.throwIfAborted()
if (size > this.limits.segmentBytes) {
// An oversized pre-existing segment is not copied into the bounded retained history.
await writeFile(current, '', { mode: 0o600 })
this.repairedSegments++
} else if (size + bytes > this.limits.segmentBytes) {
await rename(current, previous)
}
this.abort.signal.throwIfAborted()
await writeFile(current, line, { flag: 'a', mode: 0o600, signal: this.abort.signal })
this.queue.shift()
this.queuedBytes -= bytes
}
} catch (_error) {
// A failed append may have written a partial line; disable this writer rather than concatenate another record.
this.disabled = true
this.failed += this.queue.length
this.queue.length = 0
this.queuedBytes = 0
}
}
private async prepareSegments(current: string, previous: string): Promise<void> {
try {
const size = (await stat(previous)).size
this.abort.signal.throwIfAborted()
if (size > this.limits.segmentBytes) {
await writeFile(previous, '', { mode: 0o600 })
this.repairedSegments++
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
this.abort.signal.throwIfAborted()
{
await using handle = await open(current, 'r+').catch((error: unknown) => {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
this.abort.signal.throwIfAborted()
return open(current, 'wx+', 0o600)
})
this.abort.signal.throwIfAborted()
const size = (await handle.stat()).size
this.abort.signal.throwIfAborted()
if (size > this.limits.segmentBytes) {
await handle.truncate(0)
this.repairedSegments++
} else if (size > 0) {
const byte = Buffer.alloc(1)
const read = await handle.read(byte, 0, 1, size - 1)
if (read.bytesRead !== 1 || byte[0] !== 10) {
const buffer = Buffer.alloc(size)
let offset = 0
while (offset < size) {
this.abort.signal.throwIfAborted()
const chunk = await handle.read(buffer, offset, size - offset, offset)
if (chunk.bytesRead === 0) break
offset += chunk.bytesRead
}
this.abort.signal.throwIfAborted()
// Keep committed lines in both segments; only the unfinished append is discarded.
await handle.truncate(buffer.subarray(0, offset).lastIndexOf(10) + 1)
this.repairedSegments++
}
}
}
this.abort.signal.throwIfAborted()
}
}
+106
View File
@@ -0,0 +1,106 @@
/** Worker lifetime for an auxiliary report; completion includes worker exit. */
import { Worker } from 'node:worker_threads'
import type { OperationReportLimits } from './operation-report.ts'
import type { OperationJournalStatus } from './operation-journal.ts'
/** Facts passed to the isolated collector after the basic report is saved. */
export interface OperationReportJobInput {
readonly reportPath: string
readonly directory: string
readonly limits: OperationReportLimits
readonly journal: OperationJournalStatus | null
}
/** Collection and cooperative shutdown share one total budget. */
export interface OperationReportJobOptions {
/** Deadline for requesting forced termination, including Worker startup. */
readonly timeoutMs: number
/** Reserved part of timeoutMs for cancellation and resource cleanup. */
readonly cancellationGraceMs: number
}
/** Cancellation can leave a partial append; the independently saved basic report remains valid. */
export interface OperationReportJobResult {
readonly appended: boolean
readonly timedOut: boolean
readonly cancelled: boolean
}
/**
* Collect history, request cooperative cancellation, then force termination if cleanup exceeds its budget.
* @param input - Bounded collection request for an existing basic report.
* @param options - Total deadline and the cleanup window reserved within it.
* @param signal - Application shutdown or recovery cancellation; an already-aborted signal prevents startup.
* @returns Append outcome only after Worker exit; cancellation or termination requests alone do not confirm exit.
*/
export async function runOperationReportJob(
input: OperationReportJobInput,
options: OperationReportJobOptions,
signal: AbortSignal,
): Promise<OperationReportJobResult> {
const { timeoutMs, cancellationGraceMs } = options
if (!Number.isSafeInteger(timeoutMs) || !Number.isSafeInteger(cancellationGraceMs)
|| cancellationGraceMs < 1 || timeoutMs <= cancellationGraceMs) throw new RangeError('Invalid operation report deadlines')
if (signal.aborted) return { appended: false, timedOut: false, cancelled: true }
const terminationDeadline = performance.now() + timeoutMs
let worker: Worker
try {
worker = new Worker(new URL('./operation-report-worker.js', import.meta.url), {
workerData: input,
resourceLimits: {
maxOldGenerationSizeMb: 32,
maxYoungGenerationSizeMb: 8,
stackSizeMb: 2,
},
})
}
catch (_error) {
return { appended: false, timedOut: false, cancelled: false }
}
return new Promise((resolve) => {
let appended = false
let failed = false
let timedOut = false
let cancelled = false
let terminationTimer: ReturnType<typeof setTimeout> | undefined
const terminateWorker = (): void => {
void worker.terminate().catch(() => {
failed = true
})
}
const requestCancellation = (): void => {
if (cancelled) return
cancelled = true
clearTimeout(collectionTimer)
try {
worker.postMessage('cancel')
}
catch (_error) {
failed = true
}
terminationTimer = setTimeout(terminateWorker, Math.max(0, Math.min(cancellationGraceMs, terminationDeadline - performance.now())))
}
const collectionTimer = setTimeout(() => {
timedOut = true
requestCancellation()
}, Math.max(0, terminationDeadline - performance.now() - cancellationGraceMs))
signal.addEventListener('abort', requestCancellation, { once: true })
worker.on('message', (message: unknown) => {
appended = message === true
})
worker.once('error', () => {
failed = true
})
worker.once('exit', (code) => {
clearTimeout(collectionTimer)
clearTimeout(terminationTimer)
signal.removeEventListener('abort', requestCancellation)
resolve({ appended: appended && code === 0 && !failed && !cancelled, timedOut, cancelled })
})
if (signal.aborted) requestCancellation()
})
}
@@ -0,0 +1,36 @@
/** Isolated auxiliary-report I/O; the shell owns termination and observes worker exit. */
import { parentPort, workerData } from 'node:worker_threads'
import { z } from 'zod'
import { appendOperationReport } from './operation-report.ts'
const positive = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
const input = z.object({
reportPath: z.string(),
directory: z.string(),
limits: z.object({
bytes: positive,
recordBytes: positive,
records: positive,
outputBytes: positive,
}),
journal: z.object({
dropped: z.number().int().nonnegative(),
failed: z.number().int().nonnegative(),
repairedSegments: z.number().int().nonnegative(),
queuedBytes: z.number().int().nonnegative(),
disabled: z.boolean(),
}).nullable(),
}).parse(workerData)
const cancellation = new AbortController()
const cancel = (message: unknown): void => {
if (message === 'cancel') cancellation.abort()
}
parentPort?.on('message', cancel)
try {
const appended = await appendOperationReport(input.reportPath, input.directory, input.limits, cancellation.signal, input.journal)
parentPort?.postMessage(appended)
} finally {
parentPort?.off('message', cancel)
parentPort?.close()
}
+62
View File
@@ -0,0 +1,62 @@
/** Best-effort operation history appended only after the independent basic report exists. */
import { writeFile } from 'node:fs/promises'
import { setImmediate } from 'node:timers/promises'
import { readOperationHistory, type OperationHistoryReadLimits } from './operation-history.ts'
import type { OperationJournalStatus } from './operation-journal.ts'
/** Read budgets and the complete appended section's UTF-8 byte budget. */
export interface OperationReportLimits extends OperationHistoryReadLimits {
readonly outputBytes: number
}
/**
* Append a bounded summary without rewriting the basic report's bytes.
* A missing completion marker means the auxiliary section is unavailable or incomplete.
* @param reportPath - Successfully saved basic report.
* @param directory - Owned operation history directory.
* @param limits - Read and parse budgets.
* @param signal - Collection deadline or shutdown cancellation; already-issued OS I/O must settle.
* @param journal - Current writer status, or null when this shell has not received operation records.
* @returns Whether the complete auxiliary section was appended.
*/
export async function appendOperationReport(
reportPath: string,
directory: string,
limits: OperationReportLimits,
signal: AbortSignal,
journal: OperationJournalStatus | null,
): Promise<boolean> {
try {
if (!Number.isSafeInteger(limits.outputBytes) || limits.outputBytes < 1) return false
const cancelled = (): boolean => signal.aborted
const history = await readOperationHistory(directory, limits, signal)
if (cancelled()) return false
const { records, ...facts } = history
const renderHeader = (omitted: number): string => '\n--- recent plugin operations (context, not proof of cause) ---\n'
+ JSON.stringify({ journal, ...facts, outputRecordsOmitted: omitted }).slice(0, -1) + ',"records":['
const completionFooter = ']}\n--- operation history collection complete; consult omission counters above ---\n'
let outputBytes = Buffer.byteLength(renderHeader(records.length) + completionFooter)
if (outputBytes > limits.outputBytes) return false
const encodedRecords: string[] = []
for (const record of records) {
await setImmediate()
if (cancelled()) return false
const encodedRecord = JSON.stringify(record)
const additionalBytes = Buffer.byteLength(encodedRecord) + (encodedRecords.length === 0 ? 0 : 1)
if (outputBytes + additionalBytes > limits.outputBytes) break
encodedRecords.push(encodedRecord)
outputBytes += additionalBytes
}
const reportSection = renderHeader(records.length - encodedRecords.length) + encodedRecords.join(',') + completionFooter
await setImmediate()
if (cancelled()) return false
await writeFile(reportPath, reportSection, { flag: 'a', signal })
return true
} catch (_error) {
// The independently written basic report remains usable, including after a partial append.
return false
}
}
+15 -12
View File
@@ -2,27 +2,30 @@
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/tests/README.md
/desktop-local-update-verification:
en: 194f1f0f1ca90743
zh: 773ca28e04c8911f
/desktop-local-update-verification/summary:
/desktop-local-verification:
en: 5056a9b4d24c1880
zh: 4d0c9d8e5f69d153
/desktop-local-verification/summary:
en: 94559f431b0b2151
zh: 1a22166a2bc59686
/desktop-local-update-verification/table-of-contents:
en: 86afdf78fa613876
zh: 66fad143d99e999f
/desktop-local-update-verification/update-dialog-themes:
/desktop-local-verification/table-of-contents:
en: fa9e3048995c0e3c
zh: ef30232afa4ba125
/desktop-local-verification/fault-report-verification:
en: a418eb04ce93b1ee
zh: 1ec04872a66ce1b7
/desktop-local-verification/update-dialog-themes:
en: d086c3b38ce623f1
zh: 8327c31092f5f174
/desktop-local-update-verification/native-overlay-visibility:
/desktop-local-verification/native-overlay-visibility:
en: 6f4de4503748f3e2
zh: 648370375f16e463
/desktop-local-update-verification/manual-walkthrough:
/desktop-local-verification/manual-walkthrough:
en: c4b4ee8763d8464a
zh: ee2159bc08966592
/desktop-local-update-verification/evidence:
/desktop-local-verification/evidence:
en: dcb2473264c825d4
zh: cebb2832efa15974
/desktop-local-update-verification/open-verification:
/desktop-local-verification/open-verification:
en: 20e9ea47acb1ff50
zh: acce24b56d57e12c
+15 -1
View File
@@ -1,4 +1,4 @@
# Desktop local update verification
# Desktop local verification
English | [中文](README.zh.md)
@@ -10,12 +10,26 @@ Installed qualification can opt into `DSH_DESKTOP_UPDATE_JOURNAL_DIR`, an absolu
## Table of Contents
- [Fault-report verification](#verification-diagnostics)
- [Update dialog themes](#verification-theme)
- [Native overlay visibility](#verification-overlay)
- [Evidence](#verification-evidence)
- [Manual walkthrough](#verification-interactive)
- [Open verification](#verification-open)
<a id="verification-diagnostics"></a>
## Fault-report verification
See [recovery and diagnostics](../docs/diagnostics/README.md) for product behavior and limitations.
Use a disposable profile and separate Electron `userData` with the actual packaged client. Construct a minimal local bundle with `package.json`, `dsh.bundle.patch` pointing to `cordis.patch.yml`, and an optional plugin module; archive it as a local `.tgz`. These packages deliberately break the application and must not be published or installed in a daily profile.
Exercise import and plugin-initialization exceptions, an asynchronous exception after `appReady`, and a nonzero Host exit. A patch disabling the `agent`, `session`, `llm`, and `tools` providers exercises missing-service diagnostics. To check cross-restart history, select that bundle through `pluginManager`, then restart the same profile. Runtime scenarios require observing actual client readiness; `appReady` alone does not establish that the window is visible.
Check the original error and cause or exit code, operation and Host run IDs across restart, report-collection completion and omissions, file retrieval from the native dialog, and startup after plugin recovery. Record the package version and source commit; successful package generation or a management result alone does not establish client functionality. Restore protocol associations and stop test processes afterward.
For resource checks, use large sparse history files, unrelated files, dense records, and malformed or unfinished lines. Measure setup separately from collection in fresh processes, recording actual bytes read, output size, time, and peak memory. To check Worker cancellation, a test-only module hook can hold an asynchronous file open after writing an entry marker. Confirm that marker, observe Worker exit after the deadline, and compare the basic report bytes. This does not reproduce a kernel-hung system call or establish packaged-client behavior.
<a id="verification-theme"></a>
## Update dialog themes
+15 -1
View File
@@ -1,4 +1,4 @@
# Desktop 本地更新验证
# Desktop 本地验证
[English](README.md) | 中文
@@ -10,12 +10,26 @@
## 目录
- [故障报告验证](#verification-diagnostics)
- [更新弹窗主题](#verification-theme)
- [原生浮层可见性](#verification-overlay)
- [验证证据](#verification-evidence)
- [手动演练](#verification-interactive)
- [待验证事项](#verification-open)
<a id="verification-diagnostics"></a>
## 故障报告验证
产品行为与限制见[故障恢复与诊断](../docs/diagnostics/README.zh.md)。
使用可丢弃的 profile、独立的 Electron `userData` 和实际打包客户端。构造最小本地组合包:`package.json` 的 `dsh.bundle.patch` 指向 `cordis.patch.yml`,需要执行代码时再加入插件模块,然后打成可本地安装的 `.tgz`。这些包会故意使应用出错,不得发布或安装到日常 profile。
分别构造模块导入异常、插件初始化异常、`appReady` 后的异步异常,以及 Host 非零退出。用 patch 禁用 `agent`、`session`、`llm`、`tools` 提供者,检查服务缺失诊断。跨重启场景通过 `pluginManager` 选入该组合包,再重启同一 profile。运行期场景须实际观察客户端就绪;`appReady` 不代表窗口已经显示。
检查原始错误与 cause 或退出码、跨重启的操作 ID 和 Host 运行 ID、报告收集完成标记与遗漏信息、原生弹窗中的文件获取,以及禁用插件恢复后的启动。记录安装包版本和源码提交;生成测试包成功或管理操作返回成功,都不能代替客户端功能验证。测试后恢复协议关联并退出测试进程。
资源验证可构造大型稀疏历史文件、大量无关文件、密集记录,以及损坏行和未完成行。在独立新进程中测量,分开记录数据构造与收集开销,并核对实际读取量、输出大小、耗时和峰值内存。验证 Worker 取消时,可用仅测试加载的模块钩子在写入进入标记后挂起异步文件打开操作;先确认标记,再观察期限到达后的 Worker 退出,并逐字节核对基本报告。该方法不模拟内核系统调用卡死,也不代替打包客户端验证。
<a id="verification-theme"></a>
## 更新弹窗主题
@@ -1,5 +1,6 @@
DeepSeek Harness is unavailable
The application could not start or stopped unexpectedly.
Another DSH instance (such as dsh web or the desktop app) is running. They cannot start at the same time. Quit the other running DSH instance, then restart.
The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support.
Exit
Restart
@@ -1,5 +1,6 @@
DeepSeek Harness 无法使用
应用无法启动或已意外停止。
有其他正在运行的 DSH(如其他 dsh web、桌面端),无法同时启动,请退出其他正在运行的 DSH 后重启。
诊断报告未能保存,反馈问题时可提供此窗口的截图。
退出
重启
@@ -2,6 +2,7 @@ DeepSeek Harness is unavailable
The application could not start or stopped unexpectedly.
Desktop Host failed
Plugin initialization failed
The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support.
If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.
Exit
@@ -8,3 +8,4 @@ If application files are missing or damaged, close the application and reinstall
Exit
Restart
Disable third-party plugins, back up profile patch, and restart
Get diagnostic report
@@ -8,3 +8,4 @@ Plugin initialization failed
退出
重启
禁用第三方插件、备份 profile patch 并重启
获取诊断报告
@@ -2,6 +2,7 @@ DeepSeek Harness 无法使用
应用无法启动或已意外停止。
Desktop Host failed
Plugin initialization failed
诊断报告未能保存,反馈问题时可提供此窗口的截图。
如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。
退出
@@ -0,0 +1,4 @@
--- recent plugin operations (context, not proof of cause) ---
{"journal":null,"bytesRead":260,"filesRead":1,"truncated":false,"invalidRecords":0,"unavailableFiles":0,"cancelled":false,"outputRecordsOmitted":0,"records":[{"runId":"c254ab28-97c9-4382-95e6-2db9c66f98c8","operation":{"id":"c254ab28-97c9-4382-95e6-2db9c66f98c9","time":"2026-10-19T00:00:00.000Z","reason":"bundle","target":"test-bundle","stage":"enable","phase":"started"},"transportDropped":0}]}
--- operation history collection complete; consult omission counters above ---
+115 -5
View File
@@ -17,6 +17,7 @@ function fixture(
disablePlugins: vi.fn(async () => {}),
exit: vi.fn(),
restart: vi.fn(),
revealReport: vi.fn(async (_path: string) => {}),
writeReport: vi.fn(writeReport),
}
return { operations, choice, stopped, recovery: new DesktopFatalRecovery(operations) }
@@ -31,14 +32,16 @@ const REPORT_PATH = 'C:\\Users\\someone\\AppData\\Roaming\\DeepSeek Harness\\log
afterEach(() => { vi.restoreAllMocks() })
it.each(['en', 'zh-CN'])('offers only exit and restart for a listener conflict in %s', async (locale) => {
it.each(['en', 'zh-CN'])('offers exit and restart for a listener conflict without a saved report in %s', async (locale) => {
const { operations, choice, stopped, recovery } = fixture(locale)
const pending = recovery.report(new AggregateError([
new Error('webserver (@deepseek-ai/dsh-host-webserver): Error: listen EADDRINUSE: address already in use 127.0.0.1:19387'),
], 'required startup failure'), 'host')
await shown(operations)
const options = operations.show.mock.calls[0]![0]
expect(options.buttons).toEqual([operations.messages().exitApplication, operations.messages().restartApplication])
expect(options.buttons).toEqual([
operations.messages().exitApplication, operations.messages().restartApplication,
])
await expect([options.title, options.message, options.detail, ...options.buttons!].join('\n') + '\n')
.toMatchFileSnapshot(`expected/fatal-address-in-use-${locale}.txt`)
choice.resolve({ response: 1, checkboxChecked: false })
@@ -56,7 +59,7 @@ it.each(['win32', 'darwin', 'linux'] as const)('offers the same listener conflic
expect(operations.show.mock.calls[0]![0].buttons).toEqual([
operations.messages().exitApplication, operations.messages().restartApplication,
])
expect(operations.show.mock.calls[0]![0].detail).toBe(operations.messages().startupAddressInUse)
expect(operations.show.mock.calls[0]![0].detail).toBe(`${operations.messages().startupAddressInUse}\n${operations.messages().reportUnavailable}`)
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await pending
@@ -188,7 +191,7 @@ it('names the report file in the listener-conflict dialog too', async () => {
await shown(operations)
await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() })
const options = operations.show.mock.calls[0]![0]
expect(options.buttons).toHaveLength(2)
expect(options.buttons).toHaveLength(3)
expect(options.detail).toBe(`${operations.messages().startupAddressInUse}\n${operations.messages().reportWrittenTo.replace('{path}', REPORT_PATH)}`)
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
@@ -202,7 +205,7 @@ it('shows the dialog without a path when the report write fails or returns nothi
const pending = recovery.report(new Error('fatal'), 'main')
await shown(operations)
await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() })
expect(operations.show.mock.calls[0]![0].detail).toBe(`fatal\n\n${operations.messages().startupReinstallAdvice}`)
expect(operations.show.mock.calls[0]![0].detail).toBe(`fatal\n${operations.messages().reportUnavailable}\n\n${operations.messages().startupReinstallAdvice}`)
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await pending
@@ -239,3 +242,110 @@ it('writes the report once for the first fatal failure and not for the recovery-
expect(operations.writeReport).toHaveBeenCalledOnce()
expect(operations.show.mock.calls[1]![0].detail).toContain(REPORT_PATH)
})
it('reveals the saved report without stopping the Host or restarting', async () => {
const { operations, stopped, recovery } = fixture('en', async () => REPORT_PATH)
operations.show.mockResolvedValueOnce({ response: 3, checkboxChecked: false })
.mockImplementationOnce(async () => {
expect(operations.revealReport).toHaveBeenCalledWith(REPORT_PATH)
expect(operations.stop).not.toHaveBeenCalled()
expect(operations.restart).not.toHaveBeenCalled()
return { response: 0, checkboxChecked: false }
})
stopped.resolve(undefined)
await recovery.report(new Error('fatal'), 'host')
expect(operations.writeReport).toHaveBeenCalledOnce()
expect(operations.show.mock.calls[1]![0].message).toBe(operations.messages().reportShareHint)
})
it('keeps the original failure and report path when revealing the file fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const { operations, stopped, recovery } = fixture('en', async () => REPORT_PATH)
operations.revealReport.mockRejectedValueOnce(new Error('file removed'))
operations.show.mockResolvedValueOnce({ response: 3, checkboxChecked: false })
.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await recovery.report(new Error('original startup failure'), 'host')
expect(operations.show.mock.calls[1]![0]).toMatchObject({ message: operations.messages().reportRevealFailed })
expect(operations.show.mock.calls[1]![0].detail).toContain('original startup failure')
expect(operations.show.mock.calls[1]![0].detail).toContain(REPORT_PATH)
})
it('makes a report that finishes after the initial deadline available without rewriting it', async () => {
vi.useFakeTimers()
try {
const write = Promise.withResolvers<string>()
const { operations, choice, stopped, recovery } = fixture('en', () => write.promise)
const pending = recovery.report(new Error('fatal'), 'host')
await vi.advanceTimersByTimeAsync(CRASH_REPORT_WAIT_MS)
expect(operations.show.mock.calls[0]![0].detail).toContain(operations.messages().reportPending)
operations.show.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
write.resolve(REPORT_PATH)
choice.resolve({ response: 3, checkboxChecked: false })
stopped.resolve(undefined)
await pending
expect(operations.revealReport).toHaveBeenCalledWith(REPORT_PATH)
expect(operations.writeReport).toHaveBeenCalledOnce()
} finally {
vi.useRealTimers()
}
})
it('does not attempt to reveal an unavailable report', async () => {
const { operations, stopped, recovery } = fixture()
operations.show.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await recovery.report(new Error('fatal'), 'host')
expect(operations.revealReport).not.toHaveBeenCalled()
expect(operations.show.mock.calls[0]![0].buttons).not.toContain(operations.messages().getDiagnosticReport)
expect(operations.show.mock.calls[0]![0].detail).toContain(operations.messages().reportUnavailable)
})
it.each(['pending', 'failed'] as const)('keeps the recovery failure visible when fetching a %s report', async (state) => {
vi.useFakeTimers()
vi.spyOn(console, 'error').mockImplementation(() => {})
const write = Promise.withResolvers<string | undefined>()
try {
const { operations, stopped, recovery } = fixture('en', () => write.promise)
stopped.resolve(undefined)
operations.disablePlugins.mockRejectedValueOnce(new Error('profile is read-only'))
operations.show.mockResolvedValueOnce({ response: 2, checkboxChecked: false })
.mockImplementationOnce(async () => {
if (state === 'failed') write.resolve(undefined)
return { response: 3, checkboxChecked: false }
})
.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
const pending = recovery.report(new Error('original startup failure'), 'host')
await vi.runAllTimersAsync()
await pending
expect(operations.show).toHaveBeenCalledTimes(3)
const last = operations.show.mock.calls[2]![0]
expect(last.message).toBe(operations.messages().recoveryOperationFailed)
expect(last.detail).toContain('profile is read-only')
if (state === 'failed') expect(last.buttons).not.toContain(operations.messages().getDiagnosticReport)
expect(last.detail).toContain(state === 'pending' ? operations.messages().reportPending : operations.messages().reportUnavailable)
expect(operations.revealReport).not.toHaveBeenCalled()
expect(operations.writeReport).toHaveBeenCalledOnce()
} finally {
write.resolve(undefined)
vi.useRealTimers()
}
})
it.each([false, true])('keeps the original attachment when revealing after a recovery failure (reveal fails=%s)', async (revealFails) => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const { operations, stopped, recovery } = fixture('en', async () => REPORT_PATH)
const original = new Error('original startup failure')
stopped.resolve(undefined)
operations.disablePlugins.mockRejectedValueOnce(new Error('profile is read-only'))
if (revealFails) operations.revealReport.mockRejectedValueOnce(new Error('file manager unavailable'))
operations.show.mockResolvedValueOnce({ response: 2, checkboxChecked: false })
.mockResolvedValueOnce({ response: 3, checkboxChecked: false })
.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
await recovery.report(original, 'host')
const last = operations.show.mock.calls[2]![0]
expect(last.message).toBe(revealFails ? operations.messages().reportRevealFailed : operations.messages().reportShareHint)
expect(last.detail).toContain('profile is read-only')
expect(operations.writeReport).toHaveBeenCalledExactlyOnceWith(original, 'host')
expect(operations.revealReport).toHaveBeenCalledExactlyOnceWith(REPORT_PATH)
})
+83 -1
View File
@@ -1,8 +1,11 @@
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { DesktopHostFatalError, DesktopHostProcess, DesktopHostUncleanExitError, QUIT_INSPECTION_DEADLINE_MS } from '../src/host-process.ts'
import { OperationJournal } from '../src/operation-journal.ts'
import { readOperationHistory } from '../src/operation-history.ts'
import { renderCrashReport } from '../src/crash-report.ts'
const roots: string[] = []
const hosts: DesktopHostProcess[] = []
@@ -88,6 +91,85 @@ afterEach(async () => {
})
describe('desktop host process', () => {
it('retains the announced run identity when startup fails before readiness', async () => {
const runtime = projectWithHost(`
process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' })
process.send({ type: 'fatal', message: 'profile startup failed', diagnostic: 'required plugin failed' }, () => process.disconnect())
`)
const host = hostProcess(runtime)
const failure: unknown = await host.start().catch((error: unknown) => error)
await host.stop()
expect(failure).toBeInstanceOf(DesktopHostFatalError)
expect(failure).toHaveProperty('hostRunId', 'c254ab28-97c9-4382-95e6-2db9c66f98c8')
})
it.each([
['exception', 'queueMicrotask(() => { throw new Error("qualification-exception", { cause: new Error("qualification-runtime-cause") }) })'],
['rejection', 'Promise.reject(new Error("qualification-rejection"))'],
['exit', 'process.stderr.write("qualification-exit", () => process.exit(7))'],
])('retains real child %s evidence in the final report after readiness', async (kind, trigger) => {
const failed = Promise.withResolvers<Error>()
const runtime = projectWithHost(`
process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' })
process.send({ type: 'ready', url: 'http://127.0.0.1:3080/' }, () => { ${trigger} })
`)
const host = hostProcess(runtime, runtime, failed.resolve)
await host.start()
const failure = await failed.promise
await host.stop()
const report = renderCrashReport({ source: 'host', phase: 'running', error: failure,
rendererConsole: [], operationHistoryPlanned: true, time: new Date('2026-10-19T00:00:00Z'),
app: { name: 'qualification', version: 'test', platform: process.platform, arch: process.arch,
electron: 'not-running', node: process.version, locale: 'zh-CN' },
})
expect(report).toContain(`qualification-${kind}`)
expect(report).toContain('phase: running')
expect(report).toContain("hostRunId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8'")
if (kind === 'exception') expect(report).toContain('qualification-runtime-cause')
if (kind === 'exit') expect(report).toContain('7')
})
it('persists validated operation IPC across Host lifetimes and isolates a failing diagnostic sink', async () => {
const record = {
runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z',
reason: 'bundle', phase: 'started', target: 'test-bundle', stage: 'enable' },
secret: 'not-persisted',
}
const runtime = projectWithHost(`
process.send({ type: 'starting', runId: ${JSON.stringify(record.runId)} })
process.send({ type: 'plugin-operation', record: { invalid: true } })
process.send({ type: 'plugin-operation', record: { ...${JSON.stringify(record)}, runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c0' } })
process.send({ type: 'plugin-operation', record: ${JSON.stringify(record)} })
${HTTP_HOST}`)
const directory = join(runtime, 'operation-history')
const journal = new OperationJournal(directory, { recordBytes: 4096, segmentBytes: 8192, queuedBytes: 8192 })
onTestFinished(async () => { await journal.close() })
const sink = vi.fn(value => journal.enqueue(JSON.stringify(value)))
const first = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env,
undefined, undefined, undefined, undefined, sink)
hosts.push(first)
await first.start()
await first.stop()
await journal.close()
expect(sink).toHaveBeenCalledTimes(1)
const saved = await readOperationHistory(directory, { bytes: 8192, recordBytes: 4096, records: 10 }, new AbortController().signal)
expect(saved.records).toEqual([{ runId: record.runId, transportDropped: 0, operation: record.operation }])
const warning = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
const failure = vi.fn()
const second = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env,
failure, undefined, undefined, undefined, () => { throw new Error('sink unavailable') })
hosts.push(second)
await second.start()
expect(await second.updateTasks('inspect')).toBe(false)
await second.stop()
expect(failure).not.toHaveBeenCalled()
expect(warning).toHaveBeenCalledWith('desktop plugin operation diagnostic sink failed')
} finally { warning.mockRestore() }
})
it('correlates authorized file resources and rejects Host denial over private IPC', async () => {
const host = hostProcess(projectWithHost())
await host.start()
+62
View File
@@ -0,0 +1,62 @@
import { SHIPPED_LOCALE_IDS } from '../../../scripts/shipped-locales.ts'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished, vi } from 'vitest'
import { readDesktopLocaleCache, writeDesktopLocaleCache } from '../src/locale-cache.ts'
import { resolveDesktopLocale, resolveDesktopStartupLocale } from '../src/locale.ts'
function fixture() {
const directory = mkdtempSync(join(tmpdir(), 'desktop-locale-'))
onTestFinished(() => { rmSync(directory, { recursive: true, force: true }) })
return directory
}
it('uses the confirmed Chinese language for recovery before Host settings are available', () => {
const directory = fixture()
expect(readDesktopLocaleCache(directory)).toBeUndefined()
writeDesktopLocaleCache(directory, 'zh-CN')
const cached = readDesktopLocaleCache(directory)
const locale = cached === undefined ? resolveDesktopStartupLocale(null, ['en-US']) : resolveDesktopLocale(cached)
expect(locale.messages.fatalSummary).toBe('应用无法启动或已意外停止。')
writeDesktopLocaleCache(directory, 'en')
expect(readDesktopLocaleCache(directory)).toBe('en')
})
it('uses the confirmed Japanese language for recovery before Host settings are available', () => {
const directory = fixture()
writeDesktopLocaleCache(directory, 'ja')
const cached = readDesktopLocaleCache(directory)
const locale = cached === undefined ? resolveDesktopStartupLocale(null, ['en-US']) : resolveDesktopLocale(cached)
expect(locale.id).toBe('ja')
expect(locale.messages.getDiagnosticReport).toBe('診断レポートを取得')
})
it.each(SHIPPED_LOCALE_IDS)('restores the confirmed shipped language %s before Host settings are available', (id) => {
const directory = fixture()
const selected = resolveDesktopLocale(id)
writeDesktopLocaleCache(directory, selected.id)
const cached = readDesktopLocaleCache(directory)
expect(cached).toBe(selected.id)
expect(resolveDesktopLocale(cached!).messages.getDiagnosticReport).toBe(selected.messages.getDiagnosticReport)
})
it.each(['', 'it', '{invalid'])('falls back to system language for an invalid cache: %s', (value) => {
const directory = fixture()
writeDesktopLocaleCache(directory, 'en')
writeFileSync(join(directory, 'desktop', 'locale-cache'), value)
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
onTestFinished(() => { warn.mockRestore() })
expect(readDesktopLocaleCache(directory)).toBeUndefined()
expect(warn).toHaveBeenCalled()
})
it('keeps read and write failures from blocking recovery', () => {
const directory = fixture()
writeFileSync(join(directory, 'desktop'), 'not a directory')
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
onTestFinished(() => { warn.mockRestore() })
expect(() => { writeDesktopLocaleCache(directory, 'zh-CN') }).not.toThrow()
expect(readDesktopLocaleCache(directory)).toBeUndefined()
expect(warn).toHaveBeenCalled()
})
+142 -13
View File
@@ -1,9 +1,11 @@
import { parsePluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
import type { DesktopHostProcess } from '../src/host-process.ts'
import type { AccountView } from '@deepseek-ai/dsh-deepseek-account/types'
import { WINDOWS_TITLEBAR_HEIGHT } from '../src/windows-layout.ts'
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import type { IpcMainInvokeEvent } from 'electron'
import { join } from 'node:path'
import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import type { MenuItemConstructorOptions, MessageBoxOptions } from 'electron'
import { DESKTOP_IPC, type DesktopUpdateState } from '../src/ipc.ts'
@@ -12,6 +14,7 @@ import { DesktopHostFatalError, DesktopHostUncleanExitError } from '../src/host-
import { en, zh } from '../src/locale.ts'
import { DesktopUpdatePreparationError } from '../src/update-error.ts'
import { writeCrashReport } from '../src/crash-report.ts'
import { runOperationReportJob } from '../src/operation-report-job.ts'
type InvokeEvent = { sender?: unknown; senderFrame: { url: string } }
type InvokeHandler = (event: InvokeEvent, ...args: unknown[]) => unknown
@@ -20,11 +23,12 @@ const fileDrag = vi.hoisted(() => ({ dispose: vi.fn<() => Promise<void>>(), inst
vi.mock('../src/file-drag.ts', () => ({ installDesktopFileDrag: () => { fileDrag.install(); return fileDrag.dispose } }))
vi.mock('../src/web-document.ts', () => ({ authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn() }))
vi.mock('../src/operation-report-job.ts', () => ({ runOperationReportJob: vi.fn(async () => ({ appended: false, timedOut: false, cancelled: false })) }))
// Report persistence has its own unit tests; here it resolves within microtasks so the fatal
// dialog never outlives the test that triggered it.
vi.mock('../src/crash-report.ts', async importOriginal => ({
...await importOriginal<typeof import('../src/crash-report.ts')>(),
writeCrashReport: vi.fn(async () => 'desktop-test-logs/crash-test.log'),
writeCrashReport: vi.fn<(...args: unknown[]) => Promise<string | undefined>>(),
pruneCrashReports: vi.fn(async () => {}),
}))
@@ -164,6 +168,8 @@ const harness = await vi.hoisted(async () => {
readonly inspectPort?: number, readonly environment?: NodeJS.ProcessEnv, readonly onFailure?: (error: Error) => void,
readonly primaryRuntime?: string,
readonly packageManager?: { pnpm: string; nodeBin: string },
readonly onPlatformSession?: ConstructorParameters<typeof DesktopHostProcess>[8],
readonly onPluginOperation?: ConstructorParameters<typeof DesktopHostProcess>[9],
) { hosts.push(this) }
}
const app = Object.assign(new EventEmitter(), {
@@ -427,9 +433,10 @@ beforeEach(() => {
harness.reset()
const userData = mkdtempSync(join(tmpdir(), 'dsh-main-user-data-'))
onTestFinished(() => { rmSync(userData, { recursive: true, force: true }) })
harness.app.getPath.mockImplementation(name => name === 'userData' ? userData : `desktop-test-${name}`)
harness.app.getPath.mockImplementation(name => name === 'userData' ? userData : join(userData, `desktop-test-${name}`))
vi.mocked(writeCrashReport).mockResolvedValue(join(harness.app.getPath('logs'), 'crash-test.log'))
harness.dialog.showMessageBox.mockImplementation((options: { title?: string }) => {
if (options.title !== en.startupFailed) return Promise.resolve({ response: 1 })
if (options.title !== en.startupFailed && options.title !== zh.startupFailed) return Promise.resolve({ response: 1 })
harness.dialogShown.resolve()
return new Promise(() => {})
})
@@ -954,7 +961,7 @@ describe('desktop main startup', () => {
expect(window.setBackgroundColor).not.toHaveBeenCalled()
})
it('follows the Windows primary document language and palette without trusting other frames', async () => {
it('follows confirmed language and primary document palette without trusting other frames', async () => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
await import('../src/main.ts')
await harness.preparing.promise
@@ -963,10 +970,12 @@ describe('desktop main startup', () => {
const event = { sender: window.webContents, senderFrame: window.webContents.mainFrame }
listener({ ...event, senderFrame: { url: 'dsh-app://app/' } }, 'zh-CN', '#ffffff', '#000000')
expect(window.setTitleBarOverlay).not.toHaveBeenCalled()
harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1](event, 'zh')
listener(event, 'zh-CN', 'rgb(249, 250, 251)', '#0f1115')
expect(window.setTitleBarOverlay).toHaveBeenCalledWith({ color: 'rgb(249, 250, 251)', symbolColor: '#0f1115' })
window.webContents.emit('context-menu', {}, { isEditable: false, selectionText: 'text', editFlags: { canCopy: true } })
expect(harness.menu.buildFromTemplate).toHaveBeenLastCalledWith([{ role: 'copy', enabled: true, label: '复制', accelerator: '' }])
harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1](event, 'en')
listener(event, 'en', '#1b1b1c', '#f9fafb')
window.webContents.emit('context-menu', {}, { isEditable: false, selectionText: 'text', editFlags: { canCopy: true } })
expect(harness.menu.buildFromTemplate).toHaveBeenLastCalledWith([{ role: 'copy', enabled: true, label: 'Copy', accelerator: '' }])
@@ -979,7 +988,30 @@ describe('desktop main startup', () => {
window.webContents.mainFrame.url = 'dsh-app://unowned/index.html'
listener(event, 'zh-CN', '#fff', '#000')
expect(window.setTitleBarOverlay).not.toHaveBeenCalled()
expect(harness.menu.setApplicationMenu).toHaveBeenCalledOnce()
expect(harness.menu.setApplicationMenu).toHaveBeenCalledTimes(3)
})
it('retains cached Chinese for a Host startup crash after the loading page reports English', async () => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const directory = join(harness.app.getPath('userData'), 'desktop')
mkdirSync(directory, { recursive: true })
writeFileSync(join(directory, 'locale-cache'), 'zh-CN\n')
await import('../src/main.ts')
await harness.preparing.promise
const window = harness.windows[0]!
const appearance = harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.windowsAppearance)![1]
appearance({ sender: window.webContents, senderFrame: window.webContents.mainFrame }, 'en', '#fff', '#000')
harness.prepared.resolve()
await harness.hostStarted.promise
const host = harness.hosts[0]!
const failure = new DesktopHostFatalError('test plugin failed', 'missing required services')
host.onFailure!(failure)
host.ready.reject(failure)
await host.stopping.promise
host.exited.resolve()
await harness.dialogShown.promise
expect(vi.mocked(writeCrashReport).mock.calls[0]![1].app.locale).toBe('zh-CN')
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).message).toBe(zh.fatalSummary)
})
it('maps Windows caption menus to localized native commands and rejects foreign popup requests', async () => {
@@ -989,6 +1021,7 @@ describe('desktop main startup', () => {
const window = harness.windows[0]!
const event = { sender: window.webContents, senderFrame: window.webContents.mainFrame }
const appearance = harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.windowsAppearance)![1]
harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1](event, 'zh')
appearance(event, 'zh-CN', '#fff', '#000')
const handler = harness.handlers.get(DESKTOP_IPC.windowsMenu)!
const foreignEvent = { ...event, sender: {} }
@@ -2206,8 +2239,8 @@ describe('desktop main startup', () => {
handler(event, 'client mount failed')
await harness.dialogShown.promise
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('client mount failed')
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('desktop-test-logs/crash-test.log')
expect(writeCrashReport).toHaveBeenCalledWith('desktop-test-logs', expect.objectContaining({ source: 'web-boot', phase: 'startup' }))
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain(join(harness.app.getPath('logs'), 'crash-test.log'))
expect(writeCrashReport).toHaveBeenCalledWith(harness.app.getPath('logs'), expect.objectContaining({ source: 'web-boot', phase: 'startup' }))
expect(window.urls).toEqual(['dsh-app://app/'])
})
@@ -2221,7 +2254,7 @@ describe('desktop main startup', () => {
window.webContents.emit('did-fail-load', {}, -2, 'failed', 'dsh-app://app/', true)
await harness.dialogShown.promise
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('Desktop page failed to load')
expect(writeCrashReport).toHaveBeenCalledWith('desktop-test-logs', expect.objectContaining({ source: 'renderer' }))
expect(writeCrashReport).toHaveBeenCalledWith(harness.app.getPath('logs'), expect.objectContaining({ source: 'renderer' }))
})
it('offers all recovery choices when resources fail before the Host starts', async () => {
@@ -2230,7 +2263,7 @@ describe('desktop main startup', () => {
harness.prepared.reject(new Error('runtime resources missing'))
await harness.dialogShown.promise
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('runtime resources missing')
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).buttons).toEqual(['Exit', 'Restart', 'Disable third-party plugins, back up profile patch, and restart'])
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).buttons).toEqual(['Exit', 'Restart', 'Disable third-party plugins, back up profile patch, and restart', 'Get diagnostic report'])
expect(harness.windows[0]!.urls).toEqual(['dsh-app://app/'])
})
@@ -2270,6 +2303,20 @@ describe('desktop main startup', () => {
expect(harness.hosts).toHaveLength(0)
})
it('writes operation history under the instance userData instead of the shared logs directory', async () => {
await import('../src/main.ts')
await harness.preparing.promise
harness.prepared.resolve()
await harness.hostStarted.promise
const record = parsePluginOperationRecord({ runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-20T00:00:00.000Z',
reason: 'bundle', phase: 'started', target: 'test', stage: 'enable' } })!
harness.hosts[0]!.onPluginOperation!(record)
const file = join(harness.app.getPath('userData'), 'plugin-operations', 'operations.jsonl')
await vi.waitFor(() => { expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual(record) })
expect(existsSync(join(harness.app.getPath('logs'), 'plugin-operations'))).toBe(false)
})
it('writes the Host\'s own diagnostic into a startup-phase crash report when the Host reports a fatal error before ready', async () => {
await import('../src/main.ts')
await harness.preparing.promise
@@ -2285,11 +2332,15 @@ describe('desktop main startup', () => {
host.exited.resolve()
await harness.dialogShown.promise
const [directory, report] = vi.mocked(writeCrashReport).mock.calls[0]!
expect(directory).toBe('desktop-test-logs')
expect(directory).toBe(harness.app.getPath('logs'))
expect(report.source).toBe('host')
expect(report.phase).toBe('startup')
expect(report.error).toBeInstanceOf(DesktopHostFatalError)
expect(report.hostDiagnostic).toBe(diagnostic)
expect(runOperationReportJob).toHaveBeenCalledWith({
reportPath: join(harness.app.getPath('logs'), 'crash-test.log'), directory: join(harness.app.getPath('userData'), 'plugin-operations'),
limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 }, journal: null,
}, { timeoutMs: 500, cancellationGraceMs: 100 }, expect.any(AbortSignal))
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('profile has no cordis.yml')
})
@@ -2312,7 +2363,7 @@ describe('desktop main startup', () => {
await host.stopping.promise
expect(writeCrashReport).toHaveBeenCalledOnce()
const [directory, report] = vi.mocked(writeCrashReport).mock.calls[0]!
expect(directory).toBe('desktop-test-logs')
expect(directory).toBe(harness.app.getPath('logs'))
expect(report.source).toBe('host')
expect(report.phase).toBe('running')
expect(report.error).toBeInstanceOf(Error)
@@ -2324,7 +2375,76 @@ describe('desktop main startup', () => {
await harness.quitCompleted.promise
})
it.each([0, 1, 2])('waits for Host exit before recovery action %s', async (response) => {
it.each([{ rejectCleanup: false, stuck: false }, { rejectCleanup: true, stuck: false },
{ rejectCleanup: true, stuck: true }])('waits for the diagnostic Worker (policy rejects=$rejectCleanup, stuck=$stuck)', async ({ rejectCleanup, stuck }) => {
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test',
allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'] }
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () =>
Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })))
let finishReport!: () => void
let reportSignal: AbortSignal | undefined
let workerExited = false
const report = new Promise<{ appended: boolean; timedOut: boolean; cancelled: boolean }>((resolve) => {
finishReport = () => { workerExited = true; resolve({ appended: false, timedOut: false, cancelled: true }) }
})
vi.mocked(runOperationReportJob).mockImplementationOnce((_input, _options, signal) => {
reportSignal = signal
return report
})
let finishPolicy!: () => void
let failPolicy!: (error: Error) => void
const policy = new Promise<void>((resolve, reject) => { finishPolicy = resolve; failPolicy = reject })
testAuth.dispose.mockImplementationOnce(() => policy)
const failure = new Error('policy Session storage cleanup failed')
const host = await readyForUpdate()
let quitCompleted = false
void harness.quitCompleted.promise.then(() => { quitCompleted = true })
try {
const window = harness.windows[0]!
window.webContents.emit('render-process-gone', {}, { reason: 'crashed' })
await harness.dialogShown.promise
expect(runOperationReportJob).toHaveBeenCalledOnce()
host.exited.resolve()
window.emit('session-end', { reasons: ['shutdown'] })
harness.app.quit()
await vi.advanceTimersByTimeAsync(0)
expect(testAuth.dispose).toHaveBeenCalledOnce()
expect(reportSignal?.aborted).toBe(true)
expect(quitCompleted).toBe(false)
if (rejectCleanup) failPolicy(failure)
else finishPolicy()
await vi.advanceTimersByTimeAsync(0)
if (rejectCleanup) expect(console.error).toHaveBeenCalledWith(failure)
expect(workerExited).toBe(false)
expect(quitCompleted).toBe(false)
if (stuck) {
await vi.advanceTimersByTimeAsync(499)
expect(quitCompleted).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(workerExited).toBe(false)
expect(console.error).toHaveBeenCalledWith('dsh desktop: operation report Worker has not exited; continuing shutdown')
} else {
finishReport()
await vi.advanceTimersByTimeAsync(0)
}
expect(quitCompleted).toBe(true)
} finally {
finishPolicy()
finishReport()
host.exited.resolve()
await vi.advanceTimersByTimeAsync(0)
await harness.quitCompleted.promise
}
})
it.each([{ response: 0, stuck: false }, { response: 1, stuck: false }, { response: 2, stuck: false },
{ response: 0, stuck: true }])('waits for Host exit and bounds Worker cleanup for recovery $response (stuck=$stuck)', async ({ response, stuck }) => {
let finishReport!: (result: { appended: boolean; timedOut: boolean; cancelled: boolean }) => void
let reportSignal: AbortSignal | undefined
vi.mocked(runOperationReportJob).mockImplementationOnce(async (_input, _options, signal) => {
reportSignal = signal
return new Promise((resolve) => { finishReport = resolve })
})
harness.dialog.showMessageBox.mockResolvedValue({ response, checkboxChecked: false })
await import('../src/main.ts')
await harness.preparing.promise
@@ -2338,7 +2458,16 @@ describe('desktop main startup', () => {
expect(harness.app.relaunch).not.toHaveBeenCalled()
expect(harness.disableAllPlugins).not.toHaveBeenCalled()
host.exited.resolve()
await vi.advanceTimersByTimeAsync(0)
expect(reportSignal?.aborted).toBe(true)
expect(harness.app.quit).not.toHaveBeenCalled()
if (stuck) await vi.advanceTimersByTimeAsync(500)
else finishReport({ appended: false, timedOut: false, cancelled: true })
await harness.quitCompleted.promise
if (stuck) {
expect(console.error).toHaveBeenCalledWith('dsh desktop: operation report Worker has not exited; continuing shutdown')
finishReport({ appended: false, timedOut: false, cancelled: true })
}
expect(harness.app.relaunch).toHaveBeenCalledTimes(response === 0 ? 0 : 1)
expect(harness.disableAllPlugins).toHaveBeenCalledTimes(response === 2 ? 1 : 0)
if (response === 2) {
@@ -0,0 +1,172 @@
import { mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished, vi } from 'vitest'
import { readOperationHistory } from '../src/operation-history.ts'
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>()
return { ...actual, open: vi.fn(actual.open) }
})
const limits = { bytes: 64 * 1024, recordBytes: 2048, records: 100 }
function record(id: string | number) {
return { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z',
reason: 'plugin', phase: 'started', target: String(id), stage: 'enable' } }
}
function line(id: string | number) { return JSON.stringify(record(id)) + '\n' }
async function fixture() {
const path = await mkdtemp(join(tmpdir(), 'desktop-operation-history-'))
onTestFinished(async () => { await rm(path, { recursive: true, force: true }) })
return path
}
it('collects recent complete records and reports malformed and incomplete entries', async () => {
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(1) + '{broken}\n' + line(2) + '{"incomplete":')
await writeFile(join(path, 'operations.previous.jsonl'), line(0))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(2), record(1), record(0)])
expect(result).toMatchObject({ invalidRecords: 1, truncated: true, cancelled: false, unavailableFiles: 0 })
})
it('reads no more than its byte budget from a two GiB file and ignores unrelated history', async () => {
const path = await fixture()
await using large = await open(join(path, 'operations.jsonl'), 'w')
const size = 2 * 1024 * 1024 * 1024
await large.truncate(size)
const tail = Buffer.from('\n' + line('last'))
await large.write(tail, 0, tail.length, size - tail.length)
await writeFile(join(path, 'pnpm.log'), 'unrelated output')
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record('last')])
expect(result.bytesRead).toBe(limits.bytes)
expect(result.truncated).toBe(true)
})
it('bounds parsed record size and output count independently', async () => {
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(1) + '{"large":"' + 'x'.repeat(4096) + '"}\n' + line(2))
const result = await readOperationHistory(path, { ...limits, records: 2 }, new AbortController().signal)
expect(result.records).toEqual([record(2), record(1)])
expect(result.invalidRecords).toBe(1)
})
it('returns immediately without I/O when already cancelled', async () => {
const result = await readOperationHistory('not-a-directory', limits, AbortSignal.abort())
expect(result).toMatchObject({ records: [], bytesRead: 0, cancelled: true, unavailableFiles: 0 })
})
it('reports unreadable segments without failing the whole collection', async () => {
const path = await fixture()
await mkdir(join(path, 'operations.jsonl'))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result.unavailableFiles).toBe(1)
})
it('awaits an in-flight read before closing and schedules no further reads after cancellation', async () => {
const path = await fixture()
const filename = join(path, 'operations.jsonl')
await writeFile(filename, ' '.repeat(limits.bytes))
const handle = await open(filename, 'r')
onTestFinished(async () => { await handle.close() })
const started = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(handle)
const reader = vi.spyOn(handle, 'read').mockImplementationOnce(async () => {
started.resolve(undefined)
await release.promise
return { bytesRead: 1, buffer: Buffer.alloc(1) }
})
const controller = new AbortController()
let settled = false
const collecting = readOperationHistory(path, limits, controller.signal)
.then((result) => { settled = true; return result })
try {
await started.promise
controller.abort()
await Promise.resolve(undefined)
expect(settled).toBe(false)
expect(handle.fd).not.toBe(-1)
release.resolve(undefined)
expect(await collecting).toMatchObject({ cancelled: true, bytesRead: 1, records: [] })
expect(handle.fd).toBe(-1)
expect(reader).toHaveBeenCalledTimes(1)
expect(opener).toHaveBeenCalledTimes(1)
} finally {
release.resolve(undefined)
await collecting
reader.mockRestore()
opener.mockClear()
await handle.close()
}
})
it('contains truncation between stat and read and still collects the previous segment', async () => {
const path = await fixture()
const filename = join(path, 'operations.jsonl')
await writeFile(filename, line(2))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
const handle = await open(filename, 'r+')
onTestFinished(async () => { await handle.close() })
const originalStat = await handle.stat()
const stat = vi.spyOn(handle, 'stat').mockImplementationOnce(async () => {
await handle.truncate(0)
return originalStat
})
const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(handle)
try {
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result).toMatchObject({ records: [record(1)], truncated: true, unavailableFiles: 0 })
expect(handle.fd).toBe(-1)
} finally {
stat.mockRestore()
opener.mockClear()
await handle.close()
}
})
it('rejects invalid resource budgets before opening a file', async () => {
for (const bytes of [0, -1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) {
await expect(readOperationHistory('not-a-directory', { ...limits, bytes }, new AbortController().signal))
.rejects.toThrow(RangeError)
}
})
it('does not collect the same open segment twice when it rotates during collection', async () => {
const path = await fixture()
const current = join(path, 'operations.jsonl')
await writeFile(current, line(1))
const handle = await open(current, 'r')
onTestFinished(async () => { await handle.close() })
const opener = vi.mocked(open).mockImplementationOnce(async () => {
await rename(current, join(path, 'operations.previous.jsonl'))
await writeFile(current, line(2))
return handle
})
try {
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result).toMatchObject({ filesRead: 1, truncated: true })
expect(handle.fd).toBe(-1)
} finally {
opener.mockClear()
await handle.close()
}
})
it.each(['absent', 'empty', 'nonempty'])('reports omitted bytes at an exact budget: previous segment %s', async (previous) => {
const path = await fixture()
const current = line(1)
await writeFile(join(path, 'operations.jsonl'), current)
if (previous !== 'absent') await writeFile(join(path, 'operations.previous.jsonl'), previous === 'empty' ? '' : line(0))
const result = await readOperationHistory(path,
{ ...limits, bytes: Buffer.byteLength(current), records: 1 }, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result.truncated).toBe(previous === 'nonempty')
expect(result.filesRead).toBe(1)
})
@@ -0,0 +1,115 @@
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished, vi } from 'vitest'
import { OperationJournal } from '../src/operation-journal.ts'
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>()
return { ...actual, mkdir: vi.fn(actual.mkdir) }
})
async function fixture() {
const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-journal-'))
onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) })
return directory
}
it('retains two bounded segments after dense operations across 50 plugins', async () => {
const directory = await fixture()
const journal = new OperationJournal(directory, { recordBytes: 128, segmentBytes: 1024, queuedBytes: 128 * 1000 })
onTestFinished(async () => { await journal.close() })
for (let i = 0; i < 1000; i++) expect(journal.enqueue(JSON.stringify({ plugin: i % 50, operation: i }))).toBe(true)
await journal.close()
expect((await readdir(directory)).sort()).toEqual(['operations.jsonl', 'operations.previous.jsonl'])
for (const name of await readdir(directory)) {
expect((await stat(join(directory, name))).size).toBeLessThanOrEqual(1024)
for (const line of (await readFile(join(directory, name), 'utf8')).trim().split('\n')) expect(() => { JSON.parse(line) }).not.toThrow()
}
expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toContain('"operation":999')
expect(journal.status()).toEqual({ dropped: 0, failed: 0, queuedBytes: 0, disabled: false, repairedSegments: 0 })
})
it('bounds the queue and encoded record bytes including multibyte characters and newline', async () => {
const directory = await fixture()
const journal = new OperationJournal(directory, { recordBytes: 8, segmentBytes: 32, queuedBytes: 16 })
onTestFinished(async () => { await journal.close() })
expect(journal.enqueue('{"中":1}')).toBe(false)
expect(journal.enqueue('{"a":1}')).toBe(true)
expect(journal.enqueue('{"a":2}')).toBe(true)
expect(journal.enqueue('{"a":3}')).toBe(false)
expect(journal.status()).toMatchObject({ queuedBytes: 16, dropped: 2 })
await journal.close()
expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toBe('{"a":1}\n{"a":2}\n')
expect(journal.enqueue('{}')).toBe(false)
})
it('disables persistence after a write failure without rejecting producers or close', async () => {
const directory = await fixture()
const blocked = join(directory, 'file')
await writeFile(blocked, 'untouched')
const journal = new OperationJournal(blocked, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 })
expect(journal.enqueue('{"operation":1}')).toBe(true)
await expect(journal.close()).resolves.toBeUndefined()
expect(journal.status()).toEqual({ dropped: 0, failed: 1, queuedBytes: 0, disabled: true, repairedSegments: 0 })
expect(await readFile(blocked, 'utf8')).toBe('untouched')
})
it.each(['', '{"old":1}\n'])('preserves both segments when repairing a partial append after %j', async (prefix) => {
const directory = await fixture()
const previous = '{"previous":0}\n'
await writeFile(join(directory, 'operations.previous.jsonl'), previous)
await writeFile(join(directory, 'operations.jsonl'), prefix + '{"partial":')
const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 })
expect(journal.enqueue('{"new":2}')).toBe(true)
await journal.close()
expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toBe(prefix + '{"new":2}\n')
expect(await readFile(join(directory, 'operations.previous.jsonl'), 'utf8')).toBe(previous)
expect(journal.status()).toMatchObject({ repairedSegments: 1, disabled: false })
})
it('bounds both pre-existing oversized segments before writing new records', async () => {
const directory = await fixture()
for (const name of ['operations.jsonl', 'operations.previous.jsonl']) await writeFile(join(directory, name), 'x'.repeat(1000))
const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 })
journal.enqueue('{"new":2}')
await journal.close()
for (const name of await readdir(directory)) expect((await stat(join(directory, name))).size).toBeLessThanOrEqual(64)
expect(journal.status()).toMatchObject({ repairedSegments: 2, disabled: false })
})
it('stops scheduling writes after a drain deadline without claiming the in-flight request ended', async () => {
const directory = await fixture()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
vi.mocked(mkdir).mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise; return undefined })
const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 })
onTestFinished(async () => { release.resolve(undefined); await journal.close(); vi.useRealTimers() })
journal.enqueue('{"operation":1}')
await entered.promise
vi.useFakeTimers()
const draining = journal.drain(500)
await vi.advanceTimersByTimeAsync(500)
expect(await draining).toBe(false)
expect(journal.status()).toMatchObject({ disabled: true, queuedBytes: 16 })
expect(journal.enqueue('{"operation":2}')).toBe(false)
let repeated: boolean | undefined
void journal.drain(500).then((result) => { repeated = result })
await vi.advanceTimersByTimeAsync(0)
expect(repeated).toBe(false)
release.resolve(undefined)
await journal.close()
expect(await readdir(directory)).toEqual([])
expect(journal.status()).toMatchObject({ failed: 1, queuedBytes: 0 })
})
it('can keep recording after successful installer preparation when the installer later fails', async () => {
const directory = await fixture()
const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 })
onTestFinished(async () => { await journal.close() })
journal.enqueue('{"operation":1}')
expect(await journal.drain(1000)).toBe(true)
expect(journal.enqueue('{"operation":2}')).toBe(true)
await journal.close()
expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toBe('{"operation":1}\n{"operation":2}\n')
})
@@ -0,0 +1,103 @@
import { EventEmitter } from 'node:events'
import { afterEach, expect, it, vi } from 'vitest'
import { runOperationReportJob } from '../src/operation-report-job.ts'
const create = vi.hoisted(() => vi.fn<(...args: unknown[]) => EventEmitter>())
vi.mock('node:worker_threads', () => ({ Worker: function (...args: unknown[]) { return create(...args) } }))
afterEach(() => { vi.useRealTimers(); create.mockReset() })
const input = { reportPath: 'saved.log', directory: 'history',
limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 }, journal: null }
it('does not report cancellation complete until the terminated worker exits', async () => {
vi.useFakeTimers()
const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn(async () => 1) })
create.mockReturnValue(worker)
let settled = false
const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal).then((value) => {
settled = true
return value
})
await vi.advanceTimersByTimeAsync(500)
expect(worker.terminate).toHaveBeenCalledTimes(1)
expect(settled).toBe(false)
worker.emit('exit', 1)
expect(await result).toEqual({ appended: false, timedOut: true, cancelled: true })
expect(vi.getTimerCount()).toBe(0)
})
it('requires successful worker exit after the complete append message', async () => {
vi.useFakeTimers()
const worker = new EventEmitter()
create.mockReturnValue(worker)
const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal)
worker.emit('message', true)
worker.emit('exit', 0)
expect(await result).toEqual({ appended: true, timedOut: false, cancelled: false })
expect(vi.getTimerCount()).toBe(0)
})
it('contains startup and runtime worker failures', async () => {
create.mockImplementationOnce(() => { throw new Error('worker unavailable') })
expect(await runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal))
.toEqual({ appended: false, timedOut: false, cancelled: false })
const worker = new EventEmitter()
create.mockReturnValue(worker)
const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal)
worker.emit('error', new Error('collector failed'))
worker.emit('exit', 1)
expect(await result).toEqual({ appended: false, timedOut: false, cancelled: false })
})
it('retains ownership after termination rejects until the worker actually exits', async () => {
vi.useFakeTimers()
const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn(async () => { throw new Error('termination failed') }) })
create.mockReturnValue(worker)
let settled = false
const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal).then((value) => {
settled = true
return value
})
await vi.advanceTimersByTimeAsync(500)
expect(worker.terminate).toHaveBeenCalledTimes(1)
expect(settled).toBe(false)
worker.emit('exit', 1)
expect(await result).toEqual({ appended: false, timedOut: true, cancelled: true })
expect(vi.getTimerCount()).toBe(0)
})
it('allows cooperative exit during the reserved cleanup window', async () => {
vi.useFakeTimers()
const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn() })
create.mockReturnValue(worker)
const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal)
await vi.advanceTimersByTimeAsync(400)
expect(worker.postMessage).toHaveBeenCalledExactlyOnceWith('cancel')
expect(worker.terminate).not.toHaveBeenCalled()
worker.emit('exit', 0)
expect(await result).toEqual({ appended: false, timedOut: true, cancelled: true })
expect(vi.getTimerCount()).toBe(0)
})
it('cancels on application shutdown without extending the cleanup window', async () => {
vi.useFakeTimers()
const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn(async () => 1) })
create.mockReturnValue(worker)
const controller = new AbortController()
const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, controller.signal)
await vi.advanceTimersByTimeAsync(200)
controller.abort()
controller.abort()
expect(worker.postMessage).toHaveBeenCalledExactlyOnceWith('cancel')
await vi.advanceTimersByTimeAsync(100)
expect(worker.terminate).toHaveBeenCalledTimes(1)
worker.emit('exit', 1)
expect(await result).toEqual({ appended: false, timedOut: false, cancelled: true })
expect(vi.getTimerCount()).toBe(0)
})
it('does not start a collector after shutdown was requested', async () => {
expect(await runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, AbortSignal.abort()))
.toEqual({ appended: false, timedOut: false, cancelled: true })
expect(create).not.toHaveBeenCalled()
})
@@ -0,0 +1,81 @@
/** Built job and packaged Worker acceptance without provider credentials. */
import { existsSync } from 'node:fs'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { execa } from 'execa'
import { expect, it, onTestFinished } from 'vitest'
const job = new URL('../lib/types/operation-report-job.js', import.meta.url)
const worker = new URL('../lib/operation-report-worker.js', import.meta.url)
it.skipIf(!existsSync(new URL('../lib/types/', import.meta.url)))('appends operation history through the built job and packaged Worker', async () => {
expect(existsSync(job), 'built report job').toBe(true)
expect(existsSync(worker), 'packaged report Worker').toBe(true)
const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-worker-'))
onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) })
const record = { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z',
reason: 'bundle', phase: 'started', target: 'real-worker-test', stage: 'enable' } }
await writeFile(join(directory, 'operations.jsonl'), JSON.stringify(record) + '\n')
for (const mode of ['job', 'packaged']) {
const reportPath = join(directory, mode + '.log')
await writeFile(reportPath, 'basic report\n')
const input = { reportPath, directory, journal: null,
limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 } }
const script = join(directory, mode + '.mjs')
await writeFile(script, mode === 'job'
? `import { runOperationReportJob } from ${JSON.stringify(job.href)};\nconsole.log(JSON.stringify(await runOperationReportJob(${JSON.stringify(input)}, { timeoutMs: 10000, cancellationGraceMs: 100 }, new AbortController().signal)));\n`
: `import { Worker } from 'node:worker_threads';\nconst worker = new Worker(${JSON.stringify(fileURLToPath(worker))}, { workerData: ${JSON.stringify(input)} });\nworker.on('error', error => { throw error });\nworker.on('exit', code => { if (code !== 0) process.exitCode = 1 });\n`)
const result = await execa(process.execPath, [script], { timeout: 30000, reject: false })
expect(result.timedOut).toBe(false)
expect(result.signal).toBeUndefined()
expect(result.exitCode, result.stderr).toBe(0)
if (mode === 'job') expect(JSON.parse(result.stdout)).toEqual({ appended: true, timedOut: false, cancelled: false })
const report = await readFile(reportPath, 'utf8')
expect(report.startsWith('basic report\n')).toBe(true)
const summary = JSON.parse(report.split('\n').find(line => line.startsWith('{'))!) as { records: unknown[] }
expect(summary.records).toEqual([record])
expect(report).toContain('operation history collection complete')
}
})
it.skipIf(!existsSync(new URL('../lib/types/', import.meta.url)))('cancels the packaged Worker after an in-flight open settles', async () => {
const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-cancel-'))
onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) })
const reportPath = join(directory, 'report.log')
await writeFile(reportPath, 'basic report\n')
await writeFile(join(directory, 'operations.jsonl'), '{}\n')
const hook = join(directory, 'hook.mjs')
await writeFile(hook, `import fs from 'node:fs/promises';
import { syncBuiltinESMExports } from 'node:module';
import { parentPort } from 'node:worker_threads';
const original = fs.open;
fs.open = async (...args) => {
const handle = await original(...args);
parentPort.postMessage('opened');
await new Promise(resolve => parentPort.once('message', resolve));
return handle;
};
syncBuiltinESMExports();
`)
const input = { reportPath, directory, journal: null,
limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 } }
const script = join(directory, 'cancel.mjs')
await writeFile(script, `import { Worker } from 'node:worker_threads';
const worker = new Worker(${JSON.stringify(fileURLToPath(worker))}, {
workerData: ${JSON.stringify(input)}, execArgv: ['--import', ${JSON.stringify(pathToFileURL(hook).href)}]
});
worker.on('message', message => {
if (message === 'opened') worker.postMessage('cancel');
else console.log(JSON.stringify(message));
});
worker.on('error', error => { throw error });
worker.on('exit', code => { process.exitCode = code });
`)
const result = await execa(process.execPath, [script], { timeout: 30000, reject: false })
expect(result.exitCode, result.stderr).toBe(0)
expect(result.stdout).toBe('false')
expect(await readFile(reportPath, 'utf8')).toBe('basic report\n')
})
@@ -0,0 +1,73 @@
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished } from 'vitest'
import { appendOperationReport } from '../src/operation-report.ts'
import { writeCrashReport, type CrashReportInput } from '../src/crash-report.ts'
const input: CrashReportInput = {
operationHistoryPlanned: true, source: 'host', phase: 'startup', error: new Error('startup failed'),
rendererConsole: [], time: new Date('2026-10-19T00:00:00Z'),
app: { name: 'test', version: '1', platform: 'win32', arch: 'x64', electron: '44', node: '24', locale: 'zh-CN' },
}
const limits = { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 }
async function fixture() {
const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-report-'))
onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) })
const report = await writeCrashReport(directory, input)
if (report === undefined) throw new Error('Basic report fixture was not saved')
return { directory, report, basic: await readFile(report, 'utf8') }
}
it('preserves the independently saved basic report and appends whitelisted recent history', async () => {
const { directory, report, basic } = await fixture()
const record = { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z',
reason: 'bundle', phase: 'started', target: 'test-bundle', stage: 'enable', diagnostic: 'secret' } }
await writeFile(join(directory, 'operations.jsonl'), JSON.stringify(record) + '\n')
expect(await appendOperationReport(report, directory, limits, new AbortController().signal, null)).toBe(true)
const combined = await readFile(report, 'utf8')
expect(combined.startsWith(basic)).toBe(true)
expect(combined).toContain('test-bundle')
expect(combined).not.toContain('secret')
expect(combined).toContain('operation history collection complete')
await expect(combined.slice(basic.length)).toMatchFileSnapshot('./expected/operation-history.txt')
})
it('leaves basic bytes unchanged when collection is cancelled or fails before append', async () => {
const { directory, report, basic } = await fixture()
expect(await appendOperationReport(report, directory, limits, AbortSignal.abort(), null)).toBe(false)
expect(await appendOperationReport(report, directory, { ...limits, bytes: 0 }, new AbortController().signal, null)).toBe(false)
expect(await readFile(report, 'utf8')).toBe(basic)
expect(basic).toContain('unavailable or incomplete')
})
it('bounds the entire appended section and refuses a budget smaller than its metadata', async () => {
const { directory, report, basic } = await fixture()
expect(await appendOperationReport(report, directory, { ...limits, outputBytes: 1 }, new AbortController().signal, null)).toBe(false)
expect(await readFile(report, 'utf8')).toBe(basic)
expect(await appendOperationReport(report, directory, { ...limits, outputBytes: 512 }, new AbortController().signal, null)).toBe(true)
const summary = (await readFile(report, 'utf8')).slice(basic.length)
expect(Buffer.byteLength(summary)).toBeLessThanOrEqual(512)
expect(summary).toContain('"outputRecordsOmitted":0')
})
it('omits oldest records to fit the output budget, counting UTF-8 bytes and all metadata', async () => {
const { directory, report, basic } = await fixture()
const records = Array.from({ length: 20 }, (_, index) => ({
runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z',
reason: 'bundle', phase: 'started', target: `测试插件-${index}`, stage: 'enable' },
}))
await writeFile(join(directory, 'operations.jsonl'), records.map(record => JSON.stringify(record)).join('\n') + '\n')
expect(await appendOperationReport(report, directory, { ...limits, outputBytes: 1024 }, new AbortController().signal, null)).toBe(true)
const section = (await readFile(report, 'utf8')).slice(basic.length)
expect(Buffer.byteLength(section)).toBeLessThanOrEqual(1024)
const summary = JSON.parse(section.split('\n').find(line => line.startsWith('{'))!) as {
outputRecordsOmitted: number
records: { operation: { target: string } }[]
}
expect(summary.outputRecordsOmitted).toBeGreaterThan(0)
expect(summary.records.length + summary.outputRecordsOmitted).toBe(20)
expect(summary.records[0]?.operation.target).toBe('测试插件-19')
})
@@ -125,6 +125,42 @@ async function packageFixture(input: Awaited<ReturnType<typeof fixture>>) {
}).pack([{ src: mapping.from, destination: join(destination, 'dsh'), files, metadata }])
}
it('includes the diagnostic worker in the archive selected by the shipping file rules', async () => {
const root = await mkdtemp(join(tmpdir(), 'diagnostic-worker-asar-'))
roots.push(root)
const appDir = join(root, 'app')
const resources = join(root, 'resources')
const destination = join(resources, 'app')
await mkdir(join(appDir, 'lib'), { recursive: true })
await mkdir(resources)
const worker = join(appDir, 'lib', 'operation-report-worker.js')
const excluded = join(appDir, 'lib', 'not-shipped.js')
await writeFile(worker, 'export {}')
await writeFile(excluded, 'export {}')
const config = unsignedWindowsConfig('com.example.diagnostics', join(root, 'dsh'))
const filesConfig = config.files.map(entry => typeof entry === 'string' ? entry : { ...entry, filter: [...entry.filter] })
const matchers = getFileMatchers({ files: filesConfig }, 'files', destination, {
defaultSrc: appDir, globalOutDir: root, customBuildOptions: {}, macroExpander: value => value,
})!
const matcher = matchers.find(entry => entry.from === appDir)!
const filter = matcher.createFilter()
const files: string[] = []
const metadata = new Map<string, Stats>()
for (const file of [worker, excluded]) {
const stat = await lstat(file)
if (filter(file, stat)) {
files.push(file)
metadata.set(file, stat)
}
}
await new AsarPackager({ info: { getWorkspaceRoot: async () => root } }, {
defaultDestination: destination, resourcePath: resources, options: {}, unpackPattern: () => false,
}).pack([{ src: appDir, destination, files, metadata }])
const archive = await readAsar(join(resources, 'app.asar'))
expect(archive.getFile('lib/operation-report-worker.js').size).toBe(Buffer.byteLength('export {}'))
expect(() => archive.getFile('lib/not-shipped.js')).toThrow()
})
it.each([false, true])('unpacks PE files through builder source patterns (external=%s)', async (external) => {
const input = await fixture(external)
const files = await prepareWindowsAsarUnpack(input.context, input.source)
+3
View File
@@ -35,6 +35,9 @@
{
"path": "../../packages/client/product-analytics/tsconfig.host.json"
},
{
"path": "../../packages/boot/plugin-manager"
},
{
"path": "../../packages/util/file-drag"
}
+6
View File
@@ -33,6 +33,12 @@ if (clientVersion === undefined) throw new Error('desktop build: the client envi
const clientVersionDefine = { 'process.env.DSH_CLIENT_VERSION': JSON.stringify(clientVersion) }
export default defineConfig([
{
entry: ['lib/types/operation-report-worker.js'],
plugins: [packagedImportsPlugin({ packages: new Set(), nodeBuiltins: true })],
outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024',
fixedExtension: false, dts: false, clean: false, codeSplitting: false,
},
{
entry: ['lib/types/command-manager-entry.js'],
plugins: [packagedImportsPlugin({ packages: new Set(), nodeBuiltins: true })],
+5 -2
View File
@@ -288,8 +288,11 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass
})
mock.unary('session/attachment', (request: unknown) => {
request = recordValue(request, 'request')
const attachmentId = recordString(request, 'attachmentId')
return attachments.get(attachmentId) ?? {
const attachment = recordValue(request, 'attachment')
const attachmentId = recordString(attachment, 'attachmentId')
const stored = attachments.get(attachmentId)
if (stored !== undefined) return ok({ attachment, data: recordString(recordValue(stored, 'value'), 'data') })
return {
ok: false,
error: {
code: 'session/attachment-invalid',
+1 -1
View File
@@ -196,7 +196,7 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr
await panel.getByText(`v${bundleVersion}`, { exact: true }).waitFor()
await panel.getByText(bundleVersion, { exact: true }).waitFor()
// The bundle's detail document is shown between its components and its source.
await panel.locator('[data-detail-document]').getByRole('heading', { name: '使用方法', exact: true }).waitFor()
await panel.locator('[data-detail-document]').getByRole('img', { name: '展开的思考行从英文翻译成中文,并显示“查看原文”按钮', exact: true }).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'paid-choices.expected.md'),
await captureStableAria(settings, '[data-plugin-panel]', scaffold.workspaceCwd, {
replacements: [[BUNDLE, '{{bundle}}'], [bundleVersion, '{{version}}']],
+1 -1
View File
@@ -213,7 +213,7 @@ it.skipIf(MODE === 'record')('persists Bing reasoning translation across reopen
await panel.getByText(`v${bundleVersion}`, { exact: true }).waitFor()
await panel.getByText(bundleVersion, { exact: true }).waitFor()
// The bundle's detail document is shown between its components and its source.
await panel.locator('[data-detail-document]').getByRole('heading', { name: '使用方法', exact: true }).waitFor()
await panel.locator('[data-detail-document]').getByRole('img', { name: '展开的思考行从英文翻译成中文,并显示“查看原文”按钮', exact: true }).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'preferences.expected.md'),
await captureStableAria(settings, '[data-plugin-panel]', scaffold.workspaceCwd, {
replacements: [[BUNDLE, '{{bundle}}'], [bundleVersion, '{{version}}']],
+30 -15
View File
@@ -1,5 +1,5 @@
/** CUA follows PTC Agent scopes and changes the default only from its detail page. */
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -15,10 +15,11 @@ import { connectFreshWorkspaceZh, ZH_BROWSER_LOCALE } from './support.ts'
// The shipped bundle admits only macOS Hosts; unsupported Hosts are exercised in bundle-platform.e2e.ts.
it.skipIf(process.platform !== 'darwin').each([
{ selectedDefault: undefined, codingTools: false },
{ selectedDefault: undefined, codingTools: true },
{ selectedDefault: 'minimal', codingTools: true },
] as const)('preserves Coding Tools=$codingTools and default=$selectedDefault across CUA toggles', async ({ selectedDefault, codingTools }) => {
{ selectedDefault: undefined, codingTools: false, script: false },
{ selectedDefault: undefined, codingTools: true, script: false },
{ selectedDefault: 'minimal', codingTools: true, script: false },
{ selectedDefault: undefined, codingTools: true, script: true },
] as const)('preserves Coding Tools=$codingTools and default=$selectedDefault and Script=$script across CUA toggles', async ({ selectedDefault, codingTools, script }) => {
const directory = await mkdtemp(join(tmpdir(), 'cua-optin-web-'))
let ownedScaffold: WebScaffold | undefined
let browser: Browser | undefined
@@ -26,10 +27,18 @@ it.skipIf(process.platform !== 'darwin').each([
const patch = join(directory, 'native-fixture.yml')
// Permission inspection fails against this non-helper executable; activation still permits dismissing setup.
await writeFile(patch, JSON.stringify([{ id: 'cua', config: { helperPath: process.execPath } }]))
const defaults = join(directory, 'script-defaults')
if (script) {
await mkdir(defaults)
await writeFile(join(defaults, 'package.json'), JSON.stringify({ name: 'cua-script-defaults', version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } }))
await writeFile(join(defaults, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: vm-script\n scriptPersistence: false\n')
}
const harnessHome = join(directory, 'home')
const scaffold = ownedScaffold = await launchWebScaffold({ harnessHome, extraOverlayPath: [
fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), patch,
] })
const scaffold = ownedScaffold = await launchWebScaffold({
profile: { packages: script ? [{ dir: defaults, enabled: true }] : [] },
harnessHome, extraOverlayPath: [
fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), patch,
] })
const initialDefault = selectedDefault ?? 'standard'
if (selectedDefault !== undefined) await scaffold.ctx.settings.update('agent-preset-registry', { selectedDefault })
await scaffold.ctx.settings.update('ui-settings', { enabled: codingTools })
@@ -67,9 +76,12 @@ it.skipIf(process.platform !== 'darwin').each([
setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx, 'ptc') },
})).agent
expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(false)
const runtimeFiber = () => [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')?.fiber
const originalRuntimeFiber = runtimeFiber()
expect(originalRuntimeFiber).toBeDefined()
const originalRuntime = scaffold.ctx.ptcRuntime
expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault)
expect(originalRuntime.programFormat).toBe('function-body')
expect(originalRuntime.programFormat).toBe(script ? 'script' : 'function-body')
expect(scaffold.ctx.get('computerUse')).toBeUndefined()
const profileManifest = () => readProfileManifest('scaffold', join(scaffold.harnessHome, 'profiles/scaffold'))
const selected = () => profileManifest().dsh?.profile?.bundles
@@ -140,7 +152,8 @@ it.skipIf(process.platform !== 'darwin').each([
await child.dispose()
expect(scaffold.ctx.tools.schemas(child.agent).some(tool => tool.name === 'cua')).toBe(false)
expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault)
expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body')
expect(runtimeFiber() === originalRuntimeFiber).toBe(true)
expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'function-body')
await setup.waitFor()
expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1)
await setup.getByRole('button', { name: '稍后', exact: true }).click()
@@ -174,12 +187,14 @@ it.skipIf(process.platform !== 'darwin').each([
const beforePersistent = scaffold.ctx.ptcRuntime
await persistent.getByRole('button', { name: '设为持久化', exact: true }).click()
await persistent.getByRole('button', { name: '已设为持久化', exact: true }).waitFor()
expect(scaffold.ctx.ptcRuntime.programFormat).toBe('repl')
expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'repl')
expect(scaffold.ctx.ptcRuntime.retainsState).toBe(true)
expect(scaffold.ctx.ptcRuntime === beforePersistent).toBe(false)
saved = await readFile(settingsPath, 'utf8')
expect(saved).toContain('executionMode: persistent-in-memory')
expect(saved).toContain(`executionMode: ${script ? 'vm-script' : 'persistent-in-memory'}`)
expect(saved).toContain(`scriptPersistence: ${script}`)
const runtime = scaffold.ctx.ptcRuntime
const runtimeFiber = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')!.fiber
const persistentRuntimeFiber = runtimeFiber()
const owner = {}
const program = 'globalThis.counter = (globalThis.counter ?? 0) + 1'
expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(1)
@@ -187,7 +202,7 @@ it.skipIf(process.platform !== 'darwin').each([
await toggle.waitFor({ state: 'hidden' })
await card.waitFor({ state: 'hidden' })
expect(scaffold.ctx.get('computerUse')).toBeUndefined()
expect([...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')!.fiber === runtimeFiber).toBe(true)
expect(runtimeFiber() === persistentRuntimeFiber).toBe(true)
expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault)
expect(scaffold.ctx.agents.get(ptcAgent.id) === ptcAgent).toBe(true)
for (const agent of [ptcAgent, fresh]) {
@@ -226,7 +241,7 @@ it.skipIf(process.platform !== 'darwin').each([
})).agent
expect(scaffold.ctx.agentPresets.composedPreset(confirmed.ctx)).toBe('ptc')
expect(scaffold.ctx.tools.schemas(confirmed).some(tool => tool.name === 'cua')).toBe(true)
expect([...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')!.fiber === runtimeFiber).toBe(true)
expect(runtimeFiber() === persistentRuntimeFiber).toBe(true)
expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(true)
expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(3)
const confirmedSettings = await readFile(settingsPath, 'utf8')
@@ -1,5 +1,5 @@
- listitem:
- button "Siehe Automatische Autorisierungsüberprüfung": Automatische Autorisierungsüberprüfung
- text: Experimentell Fügen Sie einen Auto review-Berechtigungsmodus hinzu, der das Modell verwendet, um die Autorisierung vor jedem Toolaufruf zu bewerten.
- text: "Experimentell Fügt den Zugriffsmodus „Auto review“ hinzu: Vor jedem Tool-Aufruf prüft ein Modell den Aufruf anhand Ihrer Anforderung; zugelassene Aufrufe laufen sofort, abgelehnte Aufrufe warten auf Ihre Genehmigung."
- status
- switch "Aktivieren Sie Automatische Autorisierungsüberprüfung"
@@ -1,5 +1,5 @@
- listitem:
- button "Ver Revisión de autorización automática": Revisión de autorización automática
- text: Experimental Agregue un modo de permiso Auto review que utilice el modelo para evaluar la autorización antes de cada llamada a la herramienta.
- text: "Experimental Añade el modo de acceso “Auto review”: antes de cada llamada a una herramienta, un modelo comprueba la llamada frente a lo que usted pidió; las llamadas permitidas se ejecutan de inmediato y las denegadas esperan su aprobación."
- status
- switch "Habilitar Revisión de autorización automática"
@@ -1,5 +1,5 @@
- listitem:
- button "Voir Examen des autorisations automatiques": Examen des autorisations automatiques
- text: Expérimental Ajoutez un mode d'autorisation Auto review qui utilise le modèle pour évaluer l'autorisation avant chaque appel d'outil.
- text: "Expérimental Ajoute le mode d'accès « Auto review » : avant chaque appel d'outil, un modèle vérifie l'appel par rapport à ce que vous avez demandé ; les appels autorisés s'exécutent immédiatement et les appels refusés attendent votre approbation."
- status
- switch "Activer Examen des autorisations automatiques"
@@ -1,5 +1,5 @@
- listitem:
- button "Ver Revisão de autorização automática": Revisão de autorização automática
- text: Experimental Adicione um modo de permissão Auto review que usa o modelo para avaliar a autorização antes de cada chamada de ferramenta.
- text: "Experimental Adiciona o modo de acesso “Auto review”: antes de cada chamada de ferramenta, um modelo verifica a chamada em relação ao que você pediu; as chamadas permitidas são executadas imediatamente e as negadas aguardam sua aprovação."
- status
- switch "Ativar Revisão de autorização automática"
Loaded 100 of 500 files, more files were not shown because too many files have changed in this diff. Show more