Merge master and track system keyboard holds alongside mouse input

This commit is contained in:
creatixchu committed 2026-11-20 18:34:57 +08:00
commit 97ddb7e5be
952 files changed
+46712 -4116

No files matched your search

@@ -9,14 +9,14 @@
en: 01293500639c9d79
zh: 6d19e4843955c811
/agent-note-browser-launch-token-authentication/decision:
en: 0c437d201b8668d5
zh: 2c1b3e67b38a5012
en: 42fd63aa09083a10
zh: f2536e571c5fe4e2
/agent-note-browser-launch-token-authentication/verification:
en: 51fe0a5b45693654
zh: 69c82207975fa421
en: 99022b3decf8b596
zh: 8ff360a934ccfe5c
/agent-note-browser-launch-token-authentication/alternatives-considered:
en: 5275c87f19fe6eee
zh: ccb922367c4bb3e2
en: 226046f2546fceb7
zh: 2c03d95e2c16c2f5
/agent-note-browser-launch-token-authentication/consequences:
en: 5d69529b50c1ff32
zh: 5fc371b5cde4783e
en: 530a40576d8b3f9f
zh: 59f2dd4809ccbe37
@@ -18,6 +18,8 @@ The Token plugin generates one random launch token per Host root and retains it
The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. The HTTP listener omits `Secure`. There is no logout operation.
Browsers scope cookies by hostname and not by port, so each signed-in port adds its cookie to every request for that hostname, and Node.js answers 431 before any handler runs once request headers pass 16,384 bytes. A successful root exchange therefore expires the other authorities' generated-name cookies its request carries, except the 16 with the latest claimed issue time. The issue time is read without signature verification because another Harness home signs with a different secret; the claim only orders cookies for expiry and never authenticates. `/connect` exchanges expire nothing.
The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. The Token plugin loads or creates the record during activation and retains the secret for synchronous request verification. An active Token plugin continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority.
The in-page Web Worker preview exposes no network socket. Its page-owned `postMessage` tunnel enters the real route first, then retries a 401 or 403 through the worker-local fetch handler. This keeps Connection interceptors while limiting the authentication bypass to the page that created the Host worker.
@@ -26,7 +28,7 @@ The shipped CLI accepts concrete local bind addresses but rejects wildcard addre
## Verification
Unit coverage pins process-token retention across Token plugin reloads, one secret load per activation, synchronous verification without credential-provider reads, cookie attributes, HMAC and payload validation, authority and lifetime checks, record deletion taking effect on the next activation, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for generic RPC, Typert Remote HTTP, exact Fetch routes, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, the Token plugin, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `settings/describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart.
Unit coverage pins process-token retention across Token plugin reloads, one secret load per activation, synchronous verification without credential-provider reads, cookie attributes, HMAC and payload validation, authority and lifetime checks, record deletion taking effect on the next activation, invalid durable records, cleanup of obsolete token URLs backed by valid cookies, and expiry of other authorities' cookies beyond the 16 most recently issued. The Token Loader test sends a sign-in carrying 17 other ports' cookies to a real listener and receives one expiry. Host transport suites pin uniform 401/403 behavior for generic RPC, Typert Remote HTTP, exact Fetch routes, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, the Token plugin, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `settings/describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart.
## Alternatives considered
@@ -40,12 +42,16 @@ Unit coverage pins process-token retention across Token plugin reloads, one secr
**Add logout, TLS-proxy, and forwarding-header configuration.** None is required by the loopback Web application or the reported authentication gap. Adding them would define deployment contracts without current consumers. Browser site-data controls revoke one browser session; deleting the credential record and restarting the process revokes all sessions.
**Bound cookie growth with one shared cookie name, a shorter lifetime, or a larger header limit.** One name lets a sign-in on one port replace another port's cookie, so two ports cannot stay signed in together. A shorter lifetime does not bound how many ports one day adds. A larger limit on this listener leaves the cookies in place for every other server on that hostname and for browsers that keep an unbounded number per host. Expiring the earliest other cookies at sign-in keeps names, lifetime, and concurrently signed-in ports.
## Consequences
Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application exposes after Session creation. `Host` does not grant a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set.
The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Token verifier uses its loaded secret for each request. An HTTP listener permits plaintext cookie transmission if its authority is reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it.
One browser stays signed in to at most 17 authorities of one hostname: the latest sign-in and the 16 most recently issued others. A sign-in ranks the others by issue time, not by last use, so an authority in daily use loses its cookie once 17 other authorities have signed in after it, and needs its launch URL again.
The decision partially supersedes the authentication deferral and unauthenticated non-loopback consequences in the [browser trust note](2026-07-28-api-browser-trust-boundary.md). That note remains active authority for media-type, Host, Origin, Fetch-Metadata, and configured-authority validation. No active Agent Note is archived: the overlap is partial and both security rules retain future decision value.
The [native HTTPS listener decision](2026-09-23-native-https-web-listener.md) supersedes the HTTP-only transport and omitted-`Secure` assumptions here. Listener protocol now determines `Secure`; the token exchange, signed-cookie authority, and credential lifetime remain owned by this note.
@@ -18,6 +18,8 @@ Token 插件为每个 Host 根生成一个随机启动令牌,并跨插件重
cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。HTTP 监听器不设置 `Secure`。这里没有 logout 操作。
浏览器按 hostname 而非 port 划分 cookie,因此每个已登录 port 都会把自己的 cookie 加到发往该 hostname 的每个请求中;请求头超过 16,384 字节后,Node.js 会在任何 handler 运行前返回 431。成功的根路径交换因此让请求携带的其他 authority 的生成格式 cookie 过期,只保留声明的签发时间最新的 16 个。签发时间在不验证签名的情况下读取,因为其他 Harness home 使用不同的密钥签名;该声明只用于排列过期顺序,绝不用于认证。`/connect` 交换不让任何 cookie 过期。
HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Token 插件在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Token 插件继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。
页内 Web Worker preview 不暴露网络 socket。其由页面持有的 `postMessage` tunnel 先进入真实 route,收到 401 或 403 后再经 worker 本地 fetch handler 重试。这样既保留 Connection interceptor,又把认证绕过限制在创建 Host worker 的页面内。
@@ -26,7 +28,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session`
## 验证
单元覆盖 Token 插件重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定通用 RPC、Typert Remote HTTP、精确 Fetch 路由和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、Token 插件、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `settings/describe`,观测新的进程令牌,并在重启后复用旧 cookie。
单元覆盖 Token 插件重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录、用有效 cookie 清理过时令牌 URL,以及让签发时间最新的 16 个之外的其他 authority cookie 过期。Token Loader 测试向真实 listener 发送携带 17 个其他 port cookie 的登录请求,并收到一条过期指令。Host 传输套件固定通用 RPC、Typert Remote HTTP、精确 Fetch 路由和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、Token 插件、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `settings/describe`,观测新的进程令牌,并在重启后复用旧 cookie。
## 曾考虑的替代方案
@@ -40,12 +42,16 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session`
**增加 logout、TLS 代理和转发 header 配置。** loopback Web 应用与已报告认证缺口都不需要这些能力;加入它们会在没有当前 consumer 时定义部署约定。浏览器站点数据控制会撤销单个浏览器会话;删除凭据记录并重启进程会撤销全部会话。
**用单一共享 cookie 名称、更短的有效期或更大的请求头上限来限制 cookie 增长。** 单一名称会让某个 port 的登录替换另一个 port 的 cookie,两个 port 无法同时保持登录。更短的有效期无法限制一天内新增的 port 数量。提高本 listener 的上限后,这些 cookie 仍会发给该 hostname 上的其他服务,在不限制每个 host cookie 数量的浏览器中也会继续增长。在登录时让最早的其他 cookie 过期,可以保留名称、有效期和同时登录的 port。
## 后果
持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后暴露的 authority 一致。`Host` 不授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。
持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Token 验证器在每个请求上使用已加载的密钥。如果 HTTP listener 的 authority 经未加密网络可达,cookie 就可能以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。
同一浏览器在同一 hostname 下最多保持 17 个 authority 的登录:最近一次登录的 authority,以及签发时间最新的另外 16 个。登录时按签发时间而非最近使用排列其他 authority,因此每天都在使用的 authority,在另外 17 个 authority 于其后登录时会失去 cookie,需要重新打开其启动 URL。
本决策部分取代[浏览器信任说明](2026-07-28-api-browser-trust-boundary.zh.md)中的认证延期与未认证非 loopback 后果。该说明仍是媒体类型、Host、Origin、Fetch-Metadata 和配置 authority 校验的有效权威。没有 active Agent Note 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。
[原生 HTTPS 监听器决策](2026-09-23-native-https-web-listener.zh.md)取代本说明仅支持 HTTP 传输及不设置 `Secure` 的前提。`Secure` 由监听器协议决定;令牌交换、签名 cookie 的 authority 与凭据有效期仍由本说明定义。
@@ -9,8 +9,8 @@
en: 66ac3d7ce7eb8e15
zh: abb9d41b71900bbf
/agent-note-sandboxed-node-execution-for-ptc/decision:
en: d6b9c22603a4f933
zh: f324b91830078d9a
en: 3dac0013b3577b16
zh: 066e9b55fc3f457e
/agent-note-sandboxed-node-execution-for-ptc/decision/resolved-inputs-and-policy:
en: e544f1a5b7f5b0ec
zh: 3195e0008313a5c6
@@ -18,8 +18,8 @@
en: a8897bae00f5f674
zh: 2c959353c5a885a4
/agent-note-sandboxed-node-execution-for-ptc/decision/resource-limits:
en: 3f1d8a30f6d48243
zh: faa7c01d7c959893
en: 9fc1a3c6e06ab156
zh: 7fcf818c3411eff4
/agent-note-sandboxed-node-execution-for-ptc/alternatives-considered:
en: 8ffcc2b32a2243d7
zh: 81d48d38947abc76
@@ -12,7 +12,7 @@ The [PTC foundation](../feature/2026-06-15-ptc.md) remains responsible for regis
## Decision
`dsh-ptc-runtime-node` in its default `per-call` mode runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains after a per-call execution.
`dsh-ptc-runtime-node` in its `per-call` mode runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains after a per-call execution.
The host preserves `ELECTRON_RUN_AS_NODE` for child startup; the bootstrap removes it from the native environment before evaluation, and model-visible `process.env` stays empty. Nested Electron launches require their own explicit Node-mode selection. Desktop uses Electron as its Node executable; removing this selector launches Electron's application path instead of the PTC bootstrap. Sandbox permission changes cannot repair that launch mismatch. The macOS Desktop regression uses real Electron to verify binding writes, direct workspace writes, and rejection of writes outside the workspace under restricted policy. It requires an installed Electron binary; ordinary runtime tests cover environment filtering without that dependency.
@@ -32,7 +32,7 @@ For temporary executions, program completion, timeout, cancellation and protocol
The default elapsed deadline is 120 seconds, capped at 600 seconds by default. Trusted service consumers may request `timeoutMs: null` to disable this timer; [workflow sandbox reuse](2026-09-13-workflow-ptc-sandbox-reuse.md) owns that caller-controlled lifetime. Omitted and numeric requests, including model-facing `run_code`, retain the numeric defaults and caps. An enabled deadline includes runtime setup and nested tool or approval waits. V8 old-generation memory, serialized outer output and control traffic have separate configured bounds. The heap limit excludes native allocations and descendant memory, and elapsed time is not a process-tree CPU budget.
The opt-in [in-memory execution mode](2026-09-23-best-effort-persistent-ptc.md) retains disposable memory under the same file policy; [retained-process permissions](2026-10-08-persistent-ptc-sandbox.md) govern policy changes and temporary escalation.
The default [in-memory execution mode](2026-09-23-best-effort-persistent-ptc.md) retains disposable memory under the same file policy; [retained-process permissions](2026-10-08-persistent-ptc-sandbox.md) govern policy changes and temporary escalation.
## Alternatives considered
@@ -12,7 +12,7 @@ Node worker 隔离 JavaScript 状态,但不应用调用 Session 的 OS 沙箱
## 决策
`dsh-ptc-runtime-node` 的默认 `per-call` 模式在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。逐次执行结束后不保留 worker 或持久内核。
`dsh-ptc-runtime-node` 的 `per-call` 模式在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。逐次执行结束后不保留 worker 或持久内核。
Host 在子进程启动时保留 `ELECTRON_RUN_AS_NODE`;bootstrap 在求值前将其从原生环境中删除,模型可见的 `process.env` 仍为空。嵌套启动 Electron 需要自行显式选择 Node 模式。桌面端使用 Electron 作为 Node 可执行文件;删除此选择变量会启动 Electron 应用路径,而不是 PTC bootstrap。更改沙箱权限无法修复这一启动模式不匹配。macOS 桌面端回归测试使用真实 Electron 验证绑定写入、直接工作区写入以及受限策略对工作区外写入的拒绝。该测试需要已安装的 Electron 二进制文件;普通运行时测试无需此依赖即可覆盖环境过滤。
@@ -32,7 +32,7 @@ Host 在子进程启动时保留 `ELECTRON_RUN_AS_NODE`;bootstrap 在求值前
默认经过时间截止为 120 秒,默认上限为 600 秒。可信服务消费方可以请求 `timeoutMs: null` 来禁用该定时器;[工作流沙箱复用](2026-09-13-workflow-ptc-sandbox-reuse.zh.md)负责这种由调用方控制的生命周期。省略 timeout 或使用数值的请求(包括面向模型的 `run_code`)保留数值默认值与上限。启用的截止包括运行时准备以及嵌套工具或审批等待。V8 老生代内存、序列化外层输出与控制通信具有独立配置的上限。堆限制不包含原生分配和后代内存,经过时间也不是进程树 CPU 预算。
显式启用的[内存保留执行模式](2026-09-23-best-effort-persistent-ptc.zh.md)在相同文件策略下保留可丢弃内存;[常驻进程权限](2026-10-08-persistent-ptc-sandbox.zh.md)负责策略切换和临时提权。
默认的[内存保留执行模式](2026-09-23-best-effort-persistent-ptc.zh.md)在相同文件策略下保留可丢弃内存;[常驻进程权限](2026-10-08-persistent-ptc-sandbox.zh.md)负责策略切换和临时提权。
## 考虑过的替代方案
@@ -9,8 +9,8 @@
en: 44615a7a0939054e
zh: b8efa721321ba0d7
/agent-note-creator-mode-installs-persistent-plugin-bundles/decision:
en: 013a2088d8f8c435
zh: 5491ff817716696b
en: bc4c98ac82cae462
zh: 17a1588f93b056a7
/agent-note-creator-mode-installs-persistent-plugin-bundles/alternatives-considered:
en: af527d8aabdfd59c
zh: 34388da992d2ab56
@@ -12,7 +12,7 @@ Agents need to install capabilities and use them during the same conversation. G
Creator mode enables the existing `plugin_manager` tool. Agents author packages and Loader YAML patches as workspace files, then install them through `install_bundle`. An MCP connection is a configuration-only bundle inserting the installed `dsh-mcp-client`; a UI bundle includes a Host entry and a Client artifact. Profile locking, package installation, enablement and HMR remain owned by the existing manager. The entire management tool requires `danger-full-access` or approval for one call: profile changes can load code with host permissions and affect other sessions. Each execution, including inventory reads, uses the shared sandbox escalation helper and approval service before accessing the manager. Under lower sandbox modes, `ask` requests approval and `never` denies; a full-access session needs no additional approval. A grant does not change session permissions, but its profile changes persist. This keeps shell-equivalent Host access explicit without requiring a permanent session-wide elevation. Human-operated Web and CLI controls retain their existing behavior.
The default Standard mode enables the same tool under the same profile condition and approval gate. Without it, Standard sessions did not install plugins directly and spent extra turns and tokens working around the missing tool; the change also moves Standard and Creator toward one capability set. A full-access Standard session can therefore install Host code without a separate prompt, as its shell already can. PTC and Minimal keep the tool disabled.
The default Standard mode enables the same tool under the same profile condition and approval gate. Without it, Standard sessions did not install plugins directly and spent extra turns and tokens working around the missing tool; the change also moves Standard and Creator toward one capability set. A full-access Standard session can therefore install Host code without a separate prompt, as its shell already can. PTC enables it under the same condition, and Minimal keeps the tool disabled.
Standard and Creator expose one read-only Cordis inspection tool, `cordis_inspect`. Omitting `query` discovers providers; supplying `query` reads one declared method. The shared entry keeps runtime discovery available in the default mode without duplicating tool descriptions. Generated-code define/run/stop/undefine and dynamic self-inspection tool APIs are absent. Existing runtime and Client consumers retain their services; historical session cards remain readable. This supersedes only the model-facing mutation workflow in the [self-referential toolset reference](../../../../packages/extensions/cordis-host-runner/README.md); its runtime ownership and sandbox rationale remain independently relevant. The [profile transaction decision](2026-09-14-current-profile-plugin-management.md) continues to govern locking, package installation, and partial failures.
@@ -12,7 +12,7 @@ agent 需要安装能力并在同一段对话中使用。生成代码工具在
创造模式启用现有的 `plugin_manager` 工具。agent 将包和 Loader YAML patch 写入工作区文件,再通过 `install_bundle` 安装。MCP 连接是插入已安装 `dsh-mcp-client` 的纯配置组合包;UI 组合包包含 Host 入口和 Client 产物。profile 锁、包安装、启停和 HMR 继续由现有管理器负责。 整个管理工具要求 `danger-full-access` 或单次调用的批准:profile 变更能以宿主权限加载代码,并影响其他会话。每次执行(包括查询列表)都会先使用共享沙箱提权函数和审批服务,再访问管理器。在较低沙箱模式下,`ask` 请求审批,`never` 拒绝;完整权限会话无需额外审批。批准不改变会话权限,但本次操作的 profile 变更会持久化。这让与 shell 等价的宿主访问需要明确授权,同时不必永久提升整个会话的权限。由用户直接操作的 Web 和 CLI 控件保持原有行为。
默认的标准模式以相同的 profile 条件和审批门槛启用同一工具。缺少该工具时,标准模式会话不会直接安装插件,而要额外花费轮次和 token 绕过;此改动也让标准模式和创造模式朝同一能力集收敛。因此,完整权限的标准模式会话无需单独审批即可安装 Host 代码,与其 shell 已有的能力一致。PTC 和 Minimal 仍禁用该工具。
默认的标准模式以相同的 profile 条件和审批门槛启用同一工具。缺少该工具时,标准模式会话不会直接安装插件,而要额外花费轮次和 token 绕过;此改动也让标准模式和创造模式朝同一能力集收敛。因此,完整权限的标准模式会话无需单独审批即可安装 Host 代码,与其 shell 已有的能力一致。PTC 以相同条件启用该工具,Minimal 仍禁用。
标准模式和创造模式提供一个只读 Cordis 检查工具 `cordis_inspect`。省略 `query` 以发现 provider;提供 `query` 以读取一个已声明的方法。共用此入口使默认模式能够进行运行时发现,同时避免重复的工具描述。不再提供生成代码的 define/run/stop/undefine 和动态自省工具 API。现有运行时和 Client 消费者保留其服务;历史会话卡片仍然可读。这仅取代[自引用工具集参考](../../../../packages/extensions/cordis-host-runner/README.zh.md)中的模型侧变更流程;其运行时所有权和沙箱依据仍有独立价值。[profile 事务决策](2026-09-14-current-profile-plugin-management.zh.md)继续规定锁、包安装和部分失败行为。
@@ -9,8 +9,8 @@
en: e42db40b879fdbf4
zh: 6017da9c4da17835
/agent-note-node-ptc-execution-modes-and-in-memory-state/decision:
en: 13a72b9728d25394
zh: 1f44510fe93836dc
en: 2d5306e76dc8170a
zh: eab993b4d2f3acf0
/agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered:
en: 396157a9fc293198
zh: a061f05b4423e26f
@@ -10,7 +10,7 @@ Interactive automation retains application objects, imported modules and helper
## Decision
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.
The existing `@deepseek-ai/dsh-ptc-runtime-node` plugin selects its execution mode through `executionMode`. The `per-call` mode starts a fresh process under the configured file policy. The default `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.
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.
@@ -10,7 +10,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)负责工具分派与模型请求日志。
现有 `@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` 名称描述各自固定的状态保留策略:只保留一次调用,或跨调用保留至进程或所有者结束。[Script 求值决策](2026-10-20-ptc-script-evaluation-and-retention.zh.md)在这两种模式之外增加独立配置的语法与保留方式。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。
@@ -21,8 +21,8 @@
en: ca6a5c372bb3cad1
zh: 1cd5028269b58c65
/agent-note-one-fold-motion-for-collapsing-on-the-next-message/testing:
en: 0423a607ee0589b5
zh: 61df892a01c5aa43
en: 6928ea8cc28112e5
zh: e9d69605558ea102
/agent-note-one-fold-motion-for-collapsing-on-the-next-message/alternatives-considered:
en: d8e1ea66e293cd93
zh: 0aaa9e693f441673
@@ -73,7 +73,7 @@ Let `start` be the scrollTop when the batch begins, `above` the height of closin
## Testing
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) covers 19 main-Session cases and 8 right-Sidebar child cases across reader position (bottom, middle of the body, top of the body, inside the steps, previous Turn), input source (composer, Turn failing before its message is recorded, another tab, queued delivery, steer, parent message, several Turns folding at once), body length, and Standard and "On completion" controls. The layout gap is the tallest band between the scrollport top and the composer that no visible row's box covers: at most 120 px once settled, and over that for at most one animation frame. It counts boxes, so a closing row that has faded but not finished shrinking still covers its space. Tail cases assert the floor landing; reader-content-still cases assert that the reader's anchor row moves at most 2 px on screen. Short-body cases assert only that no room remains after the reply arrives.
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) covers 19 main-Session cases and 8 right-Sidebar child cases across reader position (bottom, middle of the body, top of the body, inside the steps, previous Turn), input source (composer, Turn failing before its message is recorded, another tab, queued delivery, steer, parent message, several Turns folding at once), body length, and Standard and "On completion" controls. The layout gap is the tallest band between the scrollport top and the composer that no visible row's box covers: at most 120 px once settled, and over that for at most one animation frame. The probe reads the layout after the animation callbacks for each rendering opportunity, before paint. Identical gaps on consecutive frames count separately. It counts boxes, so a closing row that has faded but not finished shrinking still covers its space. Tail cases assert the floor landing; reader-content-still cases assert that the reader's anchor row moves at most 2 px on screen. Short-body cases assert only that no room remains after the reply arrives.
## Alternatives considered
@@ -73,7 +73,7 @@ Status: implemented
## Testing
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) 覆盖主会话 19 例与右侧栏子会话 8 例,维度包括读者位置(底部、正文中段、正文开头、步骤中间、上一轮)、输入来源(输入框、回合在写入消息前失败、另一个标签页、排队投递、steer、父消息、一次折叠多轮)、正文长短,以及 Standard 与「完成时收起」对照。布局空洞指视口顶部到输入框之间没有任何可见行的盒子覆盖的最大连续高度:落定后不超过 120 px,动画中至多 1 帧超过。它按盒子计算,已经淡出但尚未收完的收起行仍算作覆盖。「到底部」的用例断言落到底部;「内容不动」的用例断言读者锚定行的屏幕位置变化不超过 2 px。正文很短的用例只断言回复到达后不再留空。
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) 覆盖主会话 19 例与右侧栏子会话 8 例,维度包括读者位置(底部、正文中段、正文开头、步骤中间、上一轮)、输入来源(输入框、回合在写入消息前失败、另一个标签页、排队投递、steer、父消息、一次折叠多轮)、正文长短,以及 Standard 与「完成时收起」对照。布局空洞指视口顶部到输入框之间没有任何可见行的盒子覆盖的最大连续高度:落定后不超过 120 px,动画中至多 1 帧超过。探针在每次渲染机会的动画回调全部结束、绘制之前读取布局;相邻两帧的空洞即使相同,也分别计数。它按盒子计算,已经淡出但尚未收完的收起行仍算作覆盖。「到底部」的用例断言落到底部;「内容不动」的用例断言读者锚定行的屏幕位置变化不超过 2 px。正文很短的用例只断言回复到达后不再留空。
## Alternatives considered
@@ -12,8 +12,8 @@
en: a9124b9053b16a12
zh: 7d4005cbca138015
/agent-note-cua-programs-outside-the-ptc-preset/alternatives-considered:
en: b5d8e00cbe4b53ae
zh: 4ef81611150a8d75
en: a549b92ccdf837df
zh: e012821576eb54e2
/agent-note-cua-programs-outside-the-ptc-preset/consequences:
en: 22f25d54373ba06b
zh: ee335578caaf1ab3
@@ -22,7 +22,7 @@ This partially supersedes the exclusion of a CUA program entry in [native CUA ob
**A CUA-specific evaluator** duplicates execution lifecycle policy. Reusing the PTC factory and runtime keeps cancellation, limits, sandboxing, and result handling with their existing owners.
**The profile's shared runtime** couples CUA state to unrelated PTC and workflow settings. Its default per-call mode cannot retain objects. A separate CUA runtime preserves the profile's chosen execution mode.
**The profile's shared runtime** couples CUA state to unrelated PTC and workflow settings. A per-call mode selected there cannot retain objects. A separate CUA runtime preserves the profile's chosen execution mode.
**Global registration of both tool forms** exposes a program runner inside PTC programs and exposes raw CUA calls to other presets. Selecting one form per Agent keeps each mode's intended tool list. Binding every session tool inside `cua_run_code` would duplicate ordinary direct calls and their declarations.
@@ -22,7 +22,7 @@ CUA 在隔离运行时首次接纳运行前,通过 `registerEnvironmentInitial
**CUA 专用求值器**会重复实现执行生命周期策略。复用 PTC 工厂和运行时,使取消、限制、沙箱和结果处理继续由现有实现负责。
**profile 的共享运行时**会使 CUA 状态依赖无关的 PTC 和工作流设置。其默认逐次调用模式无法保留对象。独立的 CUA 运行时保留 profile 选定的执行模式。
**profile 的共享运行时**会使 CUA 状态依赖无关的 PTC 和工作流设置。在那里选择的逐次调用模式无法保留对象。独立的 CUA 运行时保留 profile 选定的执行模式。
**全局注册两种工具形态**会在 PTC 程序中暴露另一个程序执行器,并向其他 preset 暴露原始 CUA 调用。按 Agent 选择一种形态,可以保留各模式预期的工具列表。在 `cua_run_code` 内绑定所有会话工具,会重复普通的直接调用及其声明。
@@ -6,11 +6,11 @@
en: 677b522817e84e2f
zh: f8518a7033b0fd54
/agent-note-ci-failover-runbook-hosted-pools-in-house-pool/problem:
en: bcdd24f3c39d593c
zh: 3e576d09c8c3bfd4
en: 52c1c7d73dea8807
zh: 8ce9142d06cb4be6
/agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision:
en: fed13ca92e488b69
zh: 9e5c9cdc118ab84e
en: 072960364d4be488
zh: 861a856b7a5a5bf0
/agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision/release-rehearsals-share-the-linux-switch:
en: 01e74068e0a96375
zh: aa811861ce30cb47
@@ -21,8 +21,8 @@
en: f395af725d1deaf1
zh: 896cedbb36c13758
/agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision/switch-any-repository-writer-1-minute-no-merge:
en: 2e3829fd72d6b1b0
zh: 563f0abade7974f9
en: f5ec9b53f6fd483a
zh: f6a22f29bf13e66e
/agent-note-ci-failover-runbook-hosted-pools-in-house-pool/capacity-during-failover:
en: 3dffe12ecf2356c2
zh: 7e2385fcabab1398
@@ -6,11 +6,11 @@ English | [中文](2026-07-26-ci-failover-runbook.zh.md)
## Problem
The three required Linux worker jobs in [CI](../../../../.github/workflows/ci.yml) (`node 24 / static`, `node 24 / coverage`, `node 24 / snapshots and artifacts`) run on the hosted enterprise 32-core pools; the required verdict job that aggregates them (`all checks passed`) runs on standard `ubuntu-latest`; the [native Windows jobs](2026-08-08-native-windows-pull-request-ci.md) in [CI Windows](../../../../.github/workflows/ci-windows.yml) run on the hosted `dsh-windows-2025-16core` larger runner. When the enterprise pools degrade — jobs queue indefinitely or the enterprise labels vanish — every open pull request becomes unmergeable, and the ordinary recovery of merging a fix is itself deadlocked behind the very required checks that cannot run. **Scope: two independent switches, one per platform.** `DSH_CI_FAILOVER_LINUX` recovers an enterprise Linux-pool outage (the three required Linux workers plus the `all checks passed`, `windows checks passed`, and `python checks passed` verdicts); `DSH_CI_FAILOVER_WINDOWS` recovers a hosted Windows-pool outage (the native Windows jobs). A Linux-pool outage need not retarget Windows jobs and vice versa. The [Node compatibility jobs](../../../../.github/workflows/ci.yml) also follow the Linux switch with isolated setup; the verdict's `node-24-bench`, `python-sdk`, and `python-runtime` dependencies stay on standard hosted runners, as does CI Python's `python-runtime`; in a broader GitHub-hosted capacity failure that also takes out the standard pools, those dependencies still block the verdicts that require them. An outage therefore needs a switch any responder with repository write access can throw without merging anything.
The required Linux worker jobs in [CI](../../../../.github/workflows/ci.yml) (`node 24 / static`, `node 24 / coverage 1/2` and `2/2`, `node 24 / coverage report`, `node 24 / build`, `node 24 / snapshots and artifacts`, `node 24 / web snapshots 1/2` and `2/2`) run on the hosted enterprise pools; the required verdict job that aggregates them (`all checks passed`) runs on standard `ubuntu-latest`; the [native Windows jobs](2026-08-08-native-windows-pull-request-ci.md) in [CI Windows](../../../../.github/workflows/ci-windows.yml) run on the hosted `dsh-windows-2025-16core` larger runner. When the enterprise pools degrade — jobs queue indefinitely or the enterprise labels vanish — every open pull request becomes unmergeable, and the ordinary recovery of merging a fix is itself deadlocked behind the very required checks that cannot run. **Scope: two independent switches, one per platform.** `DSH_CI_FAILOVER_LINUX` recovers an enterprise Linux-pool outage (the required Linux workers plus the `all checks passed`, `windows checks passed`, and `python checks passed` verdicts); `DSH_CI_FAILOVER_WINDOWS` recovers a hosted Windows-pool outage (the native Windows jobs). A Linux-pool outage need not retarget Windows jobs and vice versa. The [Node compatibility jobs](../../../../.github/workflows/ci.yml) also follow the Linux switch with isolated setup; the verdict's `node-24-bench`, `python-sdk`, and `python-runtime` dependencies stay on standard hosted runners, as does CI Python's `python-runtime`; in a broader GitHub-hosted capacity failure that also takes out the standard pools, those dependencies still block the verdicts that require them. An outage therefore needs a switch any responder with repository write access can throw without merging anything.
## Decision
The three primary Linux jobs (`node-24`, `node-24-coverage`, `node-24-consumers`), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes.
The primary Linux jobs (`node-24`, both `node-24-coverage` shard matrix entries and the `node-24-coverage-report` job that merges them, `node-24-build`, `node-24-consumers`, which restores the `node-24-build` output, and both entries of the `node-24-web-snapshot` shard matrix), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes.
The [superseded-CI cancellation policy](../../../../.github/workflows/ci.yml) governs master pushes and manual runs in the same workflow/ref group, including standby drills. Rapid master updates can starve a drill before it reaches a verdict. Use the latest completed standby verdict and check its age and commit before treating it as readiness evidence; a cancelled or merely scheduled run is not proof of readiness.
@@ -32,7 +32,7 @@ The two switches are independent: flip only the one whose platform is degraded.
1. Repository **Settings → Secrets and variables → Actions → Variables → New repository variable**: name `DSH_CI_FAILOVER_LINUX` (Linux pool outage) or `DSH_CI_FAILOVER_WINDOWS` (Windows pool outage), value `selfhosted`.
2. Retrigger the required jobs so they re-resolve their pool. Jobs already **queued** for the hosted labels do not retarget and cannot be re-run in place, so for the documented indefinite-queue outage, cancel the stuck run and re-run all jobs, or push a new commit; "Re-run failed jobs" only helps once a job has actually failed rather than queued.
3. That is the entire switch. Under the `selfhosted` Linux failover value the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Self-hosted coverage uses four single-worker instrumented partitions and two exempt workers; isolated hosted runners derive worker defaults from available CPUs. The Windows switch selects the native Windows pool and retains explicit worker limits on shared self-hosted runners.
3. That is the entire switch. Under the `selfhosted` Linux failover value the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Self-hosted coverage runs two shard lanes of four single-worker instrumented partitions each, and the first shard also runs the exempt suites with two workers; isolated hosted runners derive worker defaults from available CPUs. The Windows switch selects the native Windows pool and retains explicit worker limits on shared self-hosted runners.
**Dependabot exception.** Both switches' `selfhosted` legs deliberately exclude `dependabot[bot]`: under self-hosted failover, Dependabot PRs stay queued for the hosted pool rather than executing dependency-supplied code on the persistent VMs. A Dependabot PR that remains queued during an outage is expected behavior, not a failed switch; it completes when the hosted pool recovers. The `blacksmith` value's branches carry no such exclusion, because Blacksmith runners are ephemeral (see the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md)).
@@ -6,11 +6,11 @@ Status: implemented
## 问题
[CI](../../../../.github/workflows/ci.yml) 中三个必需的 Linux 工作作业(`node 24 / static`、`node 24 / coverage`、`node 24 / snapshots and artifacts`)运行在托管的企业级 32 核池上;聚合它们的必需判定作业(`all checks passed`)运行在标准 `ubuntu-latest` 上;[原生 Windows 作业](2026-08-08-native-windows-pull-request-ci.zh.md)(位于 [CI Windows](../../../../.github/workflows/ci-windows.yml))运行在托管的 `dsh-windows-2025-16core` 大型运行器上。当企业池发生故障——作业无限排队或企业标签消失——所有开启的拉取请求都无法合并,而"合并一个修复"这一常规恢复手段本身正被那些无法运行的必需检查死锁。**适用范围:两个独立开关,每个平台一个。**`DSH_CI_FAILOVER_LINUX` 恢复企业级 Linux 池故障(三个必需的 Linux 工作作业加 `all checks passed`、`windows checks passed` 与 `python checks passed` 判定作业);`DSH_CI_FAILOVER_WINDOWS` 恢复托管 Windows 池故障(原生 Windows 作业)。Linux 池故障无需重定向 Windows 作业,反之亦然。[Node 兼容性作业](../../../../.github/workflows/ci.yml)也通过隔离设置跟随 Linux 开关;判定作业的 `node-24-bench`、`python-sdk` 和 `python-runtime` 依赖仍留在标准托管运行器上,CI Python 的 `python-runtime` 也是如此;若更大范围的 GitHub 托管容量故障连标准池一并击倒,这些依赖仍会阻塞要求它们的判定。因此故障需要一个任何具备仓库写权限的响应者都能在不合并任何代码的情况下触发的开关。
[CI](../../../../.github/workflows/ci.yml) 中必需的 Linux 工作作业(`node 24 / static`、`node 24 / coverage 1/2` 与 `2/2`、`node 24 / coverage report`、`node 24 / build`、`node 24 / snapshots and artifacts`、`node 24 / web snapshots 1/2` 与 `2/2`)运行在托管的企业级池上;聚合它们的必需判定作业(`all checks passed`)运行在标准 `ubuntu-latest` 上;[原生 Windows 作业](2026-08-08-native-windows-pull-request-ci.zh.md)(位于 [CI Windows](../../../../.github/workflows/ci-windows.yml))运行在托管的 `dsh-windows-2025-16core` 大型运行器上。当企业池发生故障——作业无限排队或企业标签消失——所有开启的拉取请求都无法合并,而"合并一个修复"这一常规恢复手段本身正被那些无法运行的必需检查死锁。**适用范围:两个独立开关,每个平台一个。**`DSH_CI_FAILOVER_LINUX` 恢复企业级 Linux 池故障(必需的 Linux 工作作业加 `all checks passed`、`windows checks passed` 与 `python checks passed` 判定作业);`DSH_CI_FAILOVER_WINDOWS` 恢复托管 Windows 池故障(原生 Windows 作业)。Linux 池故障无需重定向 Windows 作业,反之亦然。[Node 兼容性作业](../../../../.github/workflows/ci.yml)也通过隔离设置跟随 Linux 开关;判定作业的 `node-24-bench`、`python-sdk` 和 `python-runtime` 依赖仍留在标准托管运行器上,CI Python 的 `python-runtime` 也是如此;若更大范围的 GitHub 托管容量故障连标准池一并击倒,这些依赖仍会阻塞要求它们的判定。因此故障需要一个任何具备仓库写权限的响应者都能在不合并任何代码的情况下触发的开关。
## 决策
三个主要 Linux 作业(`node-24`、`node-24-coverage`、`node-24-consumers`)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。
主要 Linux 作业(`node-24`、`node-24-coverage` 分片矩阵的两个条目及合并它们的 `node-24-coverage-report`、`node-24-build`、恢复 `node-24-build` 产物的 `node-24-consumers`,以及 `node-24-web-snapshot` 分片矩阵的两个条目)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。
[被取代 CI 的取消策略](../../../../.github/workflows/ci.yml) 管理同一工作流/引用组内的 master 推送和手动运行,包括热备演练。master 快速更新可能让演练因反复被取消而始终无法得出结论。判断就绪状态时,使用最近一次已完成的热备结论,并核对其时间和提交;已取消或仅被调度的运行不构成就绪证据。
@@ -32,7 +32,7 @@ Status: implemented
1. 仓库 **Settings → Secrets and variables → Actions → Variables → New repository variable**:名称 `DSH_CI_FAILOVER_LINUX`(Linux 池故障)或 `DSH_CI_FAILOVER_WINDOWS`(Windows 池故障),值 `selfhosted`。
2. 重新触发必需作业,使其重新解析运行器池。已经为托管标签**排队**的作业不会重定向,也无法原地 re-run,因此对于本手册所述的无限排队故障,应取消卡住的运行并 re-run all jobs,或推送一个新提交;“Re-run failed jobs”只有在作业真正失败(而非仍在排队)时才有用。
3. 切换到此完成。在 `selfhosted` 的 Linux 故障切换取值下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。自托管覆盖率使用 4 个单 worker 插桩分区与 2 个豁免 worker;独占的托管运行器根据可用 CPU 计算默认 worker 数。Windows 开关选择原生 Windows 运行器池,并在共享的自托管运行器上保留显式 worker 限制。
3. 切换到此完成。在 `selfhosted` 的 Linux 故障切换取值下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。自托管覆盖率分两条分片车道,每条 4 个单 worker 插桩分区,第一片另用 2 个 worker 运行豁免套件;独占的托管运行器根据可用 CPU 计算默认 worker 数。Windows 开关选择原生 Windows 运行器池,并在共享的自托管运行器上保留显式 worker 限制。
**Dependabot 例外。**两个开关的 `selfhosted` 腿都刻意排除 `dependabot[bot]`:自托管故障切换期间,Dependabot 拉取请求继续在托管池排队,而不是把依赖项提供的代码放到持久化虚拟机上执行。故障期间 Dependabot PR 持续排队是预期行为而非切换失败;托管池恢复后它会自行完成。`blacksmith` 取值下的分支不带此类排除,因为 Blacksmith 运行器是临时的(见 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md))。
@@ -3,8 +3,8 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md
/agent-note-native-github-stacks-and-optional-pr-rebases:
en: 9427ca53db68d50b
zh: 9e72b34deee3bb9f
en: b20dd8917f43b935
zh: c9d6f3d2a04da072
/agent-note-native-github-stacks-and-optional-pr-rebases/problem:
en: 21312af191207fa6
zh: 86306b4c6dd08a0c
@@ -4,6 +4,8 @@ Status: implemented
English | [中文](2026-08-02-native-github-stacks-and-optional-rebases.zh.md)
The equal choice between merge-forward and rebase below is superseded by [rebase with rerere](2026-11-19-prefer-rebase-with-rerere.md), which keeps merge-forward for an explicit PR author request. Stack linkage, landing, lease protection, and post-rewrite audits remain current.
## Problem
A dependent PR chain represented only by base branches has no official stack identity. Landing it requires manually merging one PR at a time, preserving intermediate branches, retargeting every child, and reconstructing whether the chain survived. GitHub's native stacked-PR feature instead carries the order, applies trunk rules and CI to every layer, and owns bottom-up merges and retargeting.
@@ -4,6 +4,8 @@ Status: implemented
[English](2026-08-02-native-github-stacks-and-optional-rebases.md) | 中文
下文在 merge-forward 与 rebase 之间同等选择的规定已被 [使用 rerere 的 rebase](2026-11-19-prefer-rebase-with-rerere.zh.md) 取代,后者仅在 PR 作者明确要求时保留 merge-forward。堆叠关联、落地、lease 保护和改写后的审计仍然有效。
## 问题
仅以 base 分支表示的依赖 PR(Pull Request)链没有官方的堆叠身份。要让它落地,就必须逐个手动合并 PR、保留中间分支、调整每个子 PR 的 base,并重新查证这条链是否仍然完整。GitHub 原生的堆叠 PR 功能则会承载顺序,对每一层应用 trunk 规则和 CI,并负责自底向上的合并与 base 调整。
@@ -21,8 +21,8 @@
en: 6a1b4ed0d9910133
zh: f32c6882208ded71
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/callers:
en: 895968956b86a9d2
zh: 5218d9ab8c60a53a
en: 130636aa0395c746
zh: 0314fe0490f64410
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/measurements:
en: b3a753ac2aab6073
zh: 19cbd0e32751896f
@@ -50,12 +50,13 @@ Each command does only its own job.
| `typecheck` (run by the pre-push hook) | `build.ts --scope typecheck`: host-typert (the source-only Typert pass `generate-typert.ts`) → package compilation, with `tsc -b tsconfig.{host,client}.json` after each face's package compilation; no bundle | Yes |
| `dev:web` ([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts)), `dev:desktop` (`apps/desktop/scripts/dev.ts`) | `build:artifacts` | None before launch; after `dev:web` launches, its `tsc -b tsconfig.client.json --watch` keeps checking the Client aggregate root program |
| Prerequisite step of `lint`, `lint:fix`, `doc-typecheck`, and the CI Typert contracts gate | Source-only Typert generation before Host package compilation (`compile-referenced-projects.ts host-contracts`), without any bundle | None |
| CI node 24 / snapshots and artifacts (`check:ci:consumers`), windows node 24 / build & observational (`check:ci:windows-blocking`) | `build` | Yes, the two required lanes |
| CI node 24 / build (`check:ci:build`), whose restored output `node 24 / snapshots and artifacts` (`check:ci:consumers-prebuilt`) and `node 24 / web snapshots <shard>/2` consume, windows node 24 / build & observational (`check:ci:windows-blocking`) | `build` | Yes, the two required lanes |
| CI node-compat 24.9 | `build:artifacts` (through run-gates) | None |
| CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | None |
| PR rehearsals in `e2e.yml` and `release.yml` | `pnpm run build:artifacts --profile official` | None |
| `build-preview-cloudflare.yml` | `pnpm run build:artifacts` | None |
| CI node 24 / benchmarks | `run-ci-bench.ts` (`tsc -b --noCheck`) | None |
| CI node 24 / benchmarks 1/2 and 2/2 | None: they restore the `node 24 / build` output and bundle only `benchmarks/.dsh-build/` workers | None |
| `check:ci:bench` | `run-ci-bench.ts` (`tsc -b --noCheck`) | None |
| PR rehearsal in `release-vendor.yml` | `compile-referenced-projects.ts host-libraries` | None |
| Non-PR branch of `release-vendor.yml`, `release-vendor-publish.yml` | `build:lib:host` | Host aggregate root program only |
@@ -50,12 +50,13 @@ Status: implemented
| `typecheck`(pre-push hook 运行它) | `build.ts --scope typecheck`:host-typert(只读源码的 Typert 生成 `generate-typert.ts`)→ 包编译,各 face 包编译后运行 `tsc -b tsconfig.{host,client}.json`;不含任何 bundle | 有 |
| `dev:web`([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts))、`dev:desktop`(`apps/desktop/scripts/dev.ts`) | `build:artifacts` | 启动前无;`dev:web` 启动后的 `tsc -b tsconfig.client.json --watch` 持续检查 Client 聚合根程序 |
| `lint`、`lint:fix`、`doc-typecheck` 与 CI 的 Typert contracts gate 的前置步骤 | 仅源码 Typert 生成后进行 Host 包编译(`compile-referenced-projects.ts host-contracts`),不含任何 bundle | 无 |
| CI node 24 / snapshots and artifacts(`check:ci:consumers`)、windows node 24 / build & observational(`check:ci:windows-blocking`) | `build` | 有,两个必需 lane |
| CI node 24 / build(`check:ci:build`,`node 24 / snapshots and artifacts`(`check:ci:consumers-prebuilt`)与 `node 24 / web snapshots <shard>/2` 恢复并消费其产物)、windows node 24 / build & observational(`check:ci:windows-blocking`) | `build` | 有,两个必需 lane |
| CI node-compat 24.9 | `build:artifacts`(经 run-gates) | 无 |
| CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | 无 |
| `e2e.yml`、`release.yml` 的 PR 演练 | `pnpm run build:artifacts --profile official` | 无 |
| `build-preview-cloudflare.yml` | `pnpm run build:artifacts` | 无 |
| CI node 24 / benchmarks | `run-ci-bench.ts`(`tsc -b --noCheck`) | 无 |
| CI node 24 / benchmarks 1/2 与 2/2 | 无:恢复 `node 24 / build` 产物,只打包 `benchmarks/.dsh-build/` worker | 无 |
| `check:ci:bench` | `run-ci-bench.ts`(`tsc -b --noCheck`) | 无 |
| `release-vendor.yml` 的 PR 演练 | `compile-referenced-projects.ts host-libraries` | 无 |
| `release-vendor.yml` 的非 PR 分支、`release-vendor-publish.yml` | `build:lib:host` | 仅 Host 聚合根程序 |
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-19-prefer-rebase-with-rerere.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/process/2026-11-19-prefer-rebase-with-rerere.md
/agent-note-prefer-rebase-with-rerere-for-pr-refreshes:
en: bee37c92f02c4b62
zh: da3f086fc09072b3
/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/problem:
en: 3c585b97c13a98b1
zh: 040d30dcaadfbdf2
/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/decision:
en: 8c6753ecfaf6b246
zh: d6850cd7ee0afb2a
/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/alternatives-considered:
en: 35d2f27bc5712a11
zh: 5bd1eaaaa200666f
/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/consequences:
en: c29ffb478f78ddfe
zh: 4d11a569f2e1c5d7
@@ -0,0 +1,32 @@
# Agent Note: Prefer rebase with rerere for PR refreshes
Status: implemented
English | [中文](2026-11-19-prefer-rebase-with-rerere.zh.md)
## Problem
The [native stack decision](2026-08-02-native-github-stacks-and-optional-rebases.md) allows merge-forward and rebase equally for standalone and stacked PR branches. Agents therefore pick a history per refresh, and long-lived branches accumulate merge commits that reviewers must skip. Rebasing also asks again for conflict resolutions already made when a rebase is aborted and retried, when a stack child is rebased after its parent was rewritten, or when several commits of one rebase touch the same hunk.
## Decision
Agents refresh standalone and stacked PR branches by rebase, including after review. Before rebasing, the agent enables, once per clone, Git's reuse of recorded resolutions with `git config rerere.enabled true`, so Git records each resolved conflict and applies the recorded resolution when the same conflict recurs in a later rebase. The agent leaves `rerere.autoUpdate` unset, so Git leaves a replayed resolution unstaged for inspection; the agent reviews and stages it before continuing the rebase.
Merge-forward is used only when the PR author explicitly asks for it. The incremental merge-forward procedure and its rule to preserve an in-progress checkpoint before taking a newer base remain available for that case.
Lease protection is unchanged: a standalone rewrite publishes with `--force-with-lease=<branch>:<observed-oid>`, `gh stack push` and `gh stack sync` supply lease protection for their managed branches, and raw `--force` is forbidden. The native stack decision continues to own stack linkage, landing, and post-rewrite review audits.
## Alternatives considered
**Keep merge-forward and rebase equally allowed.** This leaves the history choice to each refresh and keeps the merge commits the rebase preference removes.
**Require rebase without exception.** A PR author can have a reason to keep merge checkpoints, such as preserving a large completed conflict resolution as a recovery point; the author request keeps that option.
**Rebase without rerere.** Retried rebases and stack cascades would ask for conflict resolutions already made, which costs time and can produce inconsistent resolutions.
## Consequences
- PR branches keep linear history, and reviewers see the branch's own commits on top of the current base.
- Every refresh rewrites commit OIDs, so the post-rewrite audit of heads, review threads, approvals, mergeability, and checks applies to every refresh.
- A recorded resolution can apply to a conflict whose correct resolution changed; the agent still inspects every replayed resolution before staging it.
- Recorded resolutions live in `rr-cache` under the repository's common Git directory, so linked worktrees of one clone share them and other clones do not.
@@ -0,0 +1,32 @@
# Agent Note: 以启用 rerere 的 rebase 刷新 PR 分支
Status: implemented
[English](2026-11-19-prefer-rebase-with-rerere.md) | 中文
## 问题
[原生堆叠决策](2026-08-02-native-github-stacks-and-optional-rebases.zh.md)对独立 PR 分支和堆叠 PR 分支同等允许 merge-forward 与 rebase。因此 agent 每次刷新都要选择一种历史,长期存在的分支会积累评审者必须跳过的合并提交。中止后重试 rebase、在父层被改写后 rebase 堆叠子层,或一次 rebase 中多个提交改动同一 hunk 时,rebase 还会要求重新解决已经解决过的冲突。
## 决策
agent 以 rebase 刷新独立 PR 分支和堆叠 PR 分支,包括评审后。rebase 前,agent 在每个克隆中用 `git config rerere.enabled true` 启用一次 Git 的已记录冲突解决复用(rerere),Git 会记录每个已解决的冲突,并在之后的 rebase 中再次出现相同冲突时应用记录的解决结果。agent 不设置 `rerere.autoUpdate`,因此 Git 把复用的解决结果留在未暂存状态以供检查;agent 检查并暂存后再继续 rebase。
只有 PR 作者明确要求时才使用 merge-forward。增量 merge-forward 流程,以及在合入更新的 base 之前保留进行中检查点的规则,仍可用于这种情况。
lease 保护不变:独立分支的改写以 `--force-with-lease=<branch>:<observed-oid>` 发布,`gh stack push` 与 `gh stack sync` 为其管理的分支提供 lease 保护,禁止直接使用 `--force`。原生堆叠决策继续负责堆叠关联、落地,以及改写后的评审审计。
## 曾考虑的替代方案
**继续同等允许 merge-forward 与 rebase。** 这会把历史选择留给每次刷新,并保留 rebase 优先所消除的合并提交。
**无例外地要求 rebase。** PR 作者可能有理由保留合并检查点,例如把一次已完成的大规模冲突解决保留为恢复点;作者要求这一例外保留了该选项。
**不启用 rerere 的 rebase。** 重试的 rebase 和堆叠级联 rebase 会要求重新解决已经解决过的冲突,既耗时,也可能产生不一致的解决结果。
## 后果
- PR 分支保持线性历史,评审者看到的是位于当前 base 之上的分支自身提交。
- 每次刷新都会改写 commit OID,因此每次刷新后都要审计 head、评审线程、批准状态、可合并性和检查结果。
- 记录的解决结果可能应用到正确解决方式已经变化的冲突上;agent 仍要在暂存前检查每个复用的解决结果。
- 记录的解决结果存放在仓库公共 Git 目录下的 `rr-cache` 中,因此同一克隆的关联 worktree 共享这些记录,其他克隆则不共享。
@@ -27,8 +27,8 @@
en: c529437d4fbaeeb3
zh: fe13551e56cba7df
/agent-note-keyless-browser-e2e-lane-for-the-web-gui/decision/ci-stance:
en: a4ed258cd19db1c0
zh: 913e079a6250d7d7
en: 2e5329f8291bd365
zh: fb8c72b71232847d
/agent-note-keyless-browser-e2e-lane-for-the-web-gui/prior-art:
en: 7472e212043721dd
zh: 61dd9f5a8e12730b
@@ -50,7 +50,7 @@ The lane covers three behavior families. Live-turn scenarios pin ordinary tool e
### CI stance
The lane is a required compare-only gate for Linux pull requests under the [browser snapshot CI reference](../../../../docs/testing.md). The `node 24 / snapshots and artifacts` consumer job owns the [single Linux build](../../archived/process/2026-07-30-independent-ci-consumer-build.md), installs the lockfile-selected Chromium and WebKit, restores their OS-and-lockfile-keyed cache, and runs the lane with `DSH_SNAPSHOT=replay`. This is an intentional plane split: the host and specs use the [tsx source-launch contract](../architecture/2026-07-29-dsh-source-launch-tsx-esm.md), while the browser consumes `apps/web/dist` and package `lib/client.js` artifacts, so the gate depends on `build` for those client artifacts. The self-hosted default-branch Linux serial standby runs the same gate; there is no hosted Linux serial producer of the browser cache consumed by pull requests, and the persistent self-hosted pool needs no hosted cache. CI never records or refreshes goldens. Scenarios remain POSIX-oriented and stay outside the Windows and macOS matrices.
The lane is a required compare-only gate for Linux pull requests under the [browser snapshot CI reference](../../../../docs/testing.md). The `node 24 / build` job owns the single Linux build and publishes its output; the two entries of the `node 24 / web snapshots <shard>/2` matrix job restore that output, install the lockfile-selected Chromium and WebKit from their OS-and-lockfile-keyed cache, and each run one weighted shard of the lane with `DSH_SNAPSHOT=replay`. The longest files run as round-robin test slices, one Vitest project per slice, so no single file bounds a shard ([slice plan](../../../../scripts/web-snapshot-projects.ts)). The recorded-session corpus in `node 24 / snapshots and artifacts` does not run the Web adapters under `apps/web/tests/`. This is an intentional plane split: the host and specs use the [tsx source-launch contract](../architecture/2026-07-29-dsh-source-launch-tsx-esm.md), while the browser consumes `apps/web/dist` and package `lib/client.js` artifacts, so the gate depends on `build` for those client artifacts. The self-hosted default-branch Linux serial standby runs the same gate; there is no hosted Linux serial producer of the browser cache consumed by pull requests, and the persistent self-hosted pool needs no hosted cache. CI never records or refreshes goldens. Scenarios remain POSIX-oriented and stay outside the Windows and macOS matrices.
High-cardinality performance diagnostics use the separate opt-in `apps/web/tests/**/*.perf.ts` inventory selected only by `vitest.web.perf.config.ts`. The isolated `complex-history.perf.ts` cases reuse the real scaffold: the workspace case seeds 1,000 compact sessions plus one 500-turn history containing 500 tool calls, exhausts and remounts that history in Chat, and reports Chromium main-thread, DOM, listener, heap, paging, search, and Trajectory measurements. Two continuation cases seed the same long history but compare the default 24-turn Chat window with all 500 turns expanded before each continues eight identical turns through the real composer, agent loop, SSE wire, tools, and persistence; two turns execute a real `bash` call and assert its durable result, while the final turn fills an 8,232-character mixed-language prompt and replays 120 paced text deltas. A separate soak case starts from a blank session, drives 100 consecutive real composer turns with a `bash` call and result every tenth turn, forces GC every ten turns, and reports ten-turn latency windows plus retained browser state. It then submits a 101st text-only turn with a trusted browser click and measures browser-clock send-to-transcript-DOM and send-to-post-paint latency, excluding the composer's draft mirrors, separately from full-turn completion. Per-turn diagnostics cover composer fill, click-to-user-echo, click-to-first-chunk, completion, browser mutations, persisted chunks, and tool events; the synthetic replay model has enough context capacity to keep fixture cardinality stable instead of consuming scripted calls through compaction. Structural assertions pin the intended load, stream, and tool shapes, but timing remains threshold-free because machine speed is not a correctness contract. The required `vitest.web.config.ts` inventory remains limited to `*.e2e.ts` and `*.snapshot.ts`, so neither `test:web:built` nor its CI gate collects performance cases.
@@ -50,7 +50,7 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu
### CI 立场
根据[浏览器快照 CI 说明](../../../../docs/testing.zh.md),该车道是 Linux 拉取请求必需的只比较门禁。`node 24 / snapshots and artifacts` 消费方任务在[消费方独立构建](../../archived/process/2026-07-30-independent-ci-consumer-build.md)中负责唯一一次 Linux 构建,安装锁文件选定的 Chromium 和 WebKit,恢复以操作系统和锁文件为键的缓存,并用 `DSH_SNAPSHOT=replay` 运行该车道。这是有意的平面切分:host 与 spec 使用 [tsx 源码启动约定](../architecture/2026-07-29-dsh-source-launch-tsx-esm.zh.md),浏览器则消费 `apps/web/dist` 和包的 `lib/client.js` 产物,因此门禁依赖 `build` 提供这些客户端产物。自托管的默认分支 Linux 串行热备运行同一门禁;不存在托管 Linux 串行生产者生成供 PR 消费的浏览器缓存,持久化自托管池则不需要托管侧缓存。CI 从不录制或刷新预期输出。场景仍面向 POSIX,并继续置于 Windows 和 macOS 矩阵之外。
根据[浏览器快照 CI 说明](../../../../docs/testing.zh.md),该车道是 Linux 拉取请求必需的只比较门禁。`node 24 / build` 任务负责唯一一次 Linux 构建并发布其产物;`node 24 / web snapshots <shard>/2` 矩阵任务的两个条目恢复该产物,从以操作系统和锁文件为键的缓存安装锁文件选定的 Chromium 和 WebKit,并各自用 `DSH_SNAPSHOT=replay` 运行该车道的一个加权分片。最长的几个文件按测试轮转拆成切片,每个切片是一个 Vitest 项目,因此单个文件不会决定一个分片的耗时([切片计划](../../../../scripts/web-snapshot-projects.ts))。`node 24 / snapshots and artifacts` 中的录制会话语料不运行 `apps/web/tests/` 下的 Web 适配器。这是有意的平面切分:host 与 spec 使用 [tsx 源码启动约定](../architecture/2026-07-29-dsh-source-launch-tsx-esm.zh.md),浏览器则消费 `apps/web/dist` 和包的 `lib/client.js` 产物,因此门禁依赖 `build` 提供这些客户端产物。自托管的默认分支 Linux 串行热备运行同一门禁;不存在托管 Linux 串行生产者生成供 PR 消费的浏览器缓存,持久化自托管池则不需要托管侧缓存。CI 从不录制或刷新预期输出。场景仍面向 POSIX,并继续置于 Windows 和 macOS 矩阵之外。
高基数性能诊断使用单独按需启用的 `apps/web/tests/**/*.perf.ts` 清单,并且只由 `vitest.web.perf.config.ts` 选中。`complex-history.perf.ts` 的隔离用例复用真实 scaffold:工作区用例播种 1,000 个紧凑会话以及一份包含 500 次工具调用的 500 轮次历史,在 Chat 中穷尽并重新挂载该历史,并报告 Chromium 主线程、DOM、监听器、堆内存、分页、搜索和 Trajectory 测量结果。两个续聊用例播种同一份长历史,但比较默认的 24 轮次 Chat 窗口与展开全部 500 轮次的状态,然后各自通过真实输入框、agent loop、SSE wire、工具和持久化继续进行 8 个相同轮次;其中两轮执行真实 `bash` 调用并断言其持久化结果,最后一轮则填入一条包含 8,232 个字符的混合语言提示词,并回放 120 个带节奏的文本增量。一个单独的 soak 用例从空白会话开始,通过真实输入框连续驱动 100 轮,每第 10 轮执行一次 `bash` 调用并产生结果,每 10 轮强制执行一次 GC,并报告每 10 轮的延迟窗口及保留的浏览器状态。随后它通过受信任的浏览器点击提交第 101 个纯文本轮次,并使用浏览器时钟分别测量发送到 transcript DOM 和发送到绘制后的延迟,排除输入框的草稿镜像,并与完整轮次完成时间分开。逐轮诊断涵盖输入框填入、点击到用户消息回显、点击到首个分片、完成、浏览器变更、持久化分片和工具事件;合成回放模型拥有足够的上下文容量,可使 fixture 基数保持稳定,而不会因压缩(compaction)消耗脚本化调用。结构性断言钉住预期的负载、流和工具形状,但时间仍不设阈值,因为机器速度不属于正确性约定。必需的 `vitest.web.config.ts` 清单仍仅限 `*.e2e.ts` 和 `*.snapshot.ts`,因此 `test:web:built` 及其 CI 门禁都不会收集性能用例。
@@ -9,8 +9,8 @@
en: 00ba1f66195351e2
zh: a738b81adceda351
/agent-note-required-ci-performance-gate-for-opening-large-sessions/decision:
en: 4f94b61c48cceaf4
zh: dbb51bfe1fb0f681
en: 70b42dc07ef01b87
zh: 3a04fd4225ac5d34
/agent-note-required-ci-performance-gate-for-opening-large-sessions/calibration-evidence:
en: f1001a139470f6b7
zh: b7b46f96b84b1271
@@ -12,7 +12,7 @@ Measuring only `SessionPersistence.open()` does not stably describe the result f
## Decision
Linux pull requests run a required `node 24 / benchmarks` job that executes `pnpm run check:ci:bench` → `scripts/run-ci-bench.ts`. Its disposable library build omits repeated TypeScript diagnostics under the [PR artifact build policy](../process/2026-10-05-pr-artifact-typechecks.md); required full builds retain them. The private `@deepseek-ai/dsh-benchmarks` workspace owns benchmark-only dependencies. The command first builds workspace libraries and dedicated workers under `benchmarks/.dsh-build/`, then invokes `vitest.bench.config.ts`. The [standard hosted runner reference](../../../../.github/workflows/ci.yml) owns runner selection and the outer job timeout. The job runs the benchmark lane alone; Vitest runs one file at a time and only prepares input, starts measurement children, aggregates results, and enforces budgets. Every timed Node CPU path executes compiled JavaScript under plain Node with `NODE_OPTIONS` removed and no TypeScript loader; bare workspace imports therefore resolve from `benchmarks/node_modules` through package exports to built `lib/` entries.
Linux pull requests run the required `node 24 / benchmarks 1/2` and `2/2` jobs, one per suite phase, through `pnpm run check:ci:bench-prebuilt` → `scripts/run-ci-bench.ts --phase`. They restore the libraries, native addon, and Web assets from `node 24 / build` and build only the benchmark workers; `pnpm run check:ci:bench` keeps the self-contained disposable library build, which omits repeated TypeScript diagnostics under the [PR artifact build policy](../process/2026-10-05-pr-artifact-typechecks.md). The private `@deepseek-ai/dsh-benchmarks` workspace owns benchmark-only dependencies. The command first builds workspace libraries and dedicated workers under `benchmarks/.dsh-build/`, then invokes `vitest.bench.config.ts`. The [standard hosted runner reference](../../../../.github/workflows/ci.yml) owns runner selection and the outer job timeout. The job runs the benchmark lane alone; Vitest runs one file at a time and only prepares input, starts measurement children, aggregates results, and enforces budgets. Every timed Node CPU path executes compiled JavaScript under plain Node with `NODE_OPTIONS` removed and no TypeScript loader; bare workspace imports therefore resolve from `benchmarks/node_modules` through package exports to built `lib/` entries.
Required performance gates live under top-level `benchmarks/`, grouped by measured user path rather than package ownership. Host files use `*.bench.ts`, Client-face files use `*.bench.client.ts`, and scenario-specific workers and fixtures stay beside their benchmark without a benchmark suffix. Package-local `.perf.ts` files remain non-gating diagnostics; `scripts/` owns orchestration rather than benchmark cases.
@@ -12,7 +12,7 @@ Session format v2 的推出改变了两条成本随模型输出增长的路径
## 决定
Linux pull request 运行必需的 `node 24 / benchmarks` job,执行 `pnpm run check:ci:bench` → `scripts/run-ci-bench.ts`。其临时 library 构建按 [PR 产物构建政策](../process/2026-10-05-pr-artifact-typechecks.zh.md)省略重复的 TypeScript 诊断;必需的完整构建保留这些诊断。私有 `@deepseek-ai/dsh-benchmarks` workspace 拥有 benchmark 专属依赖。该命令先构建 workspace library 和 `benchmarks/.dsh-build/` 下的专用 worker,再调用 `vitest.bench.config.ts`。[标准托管运行器说明](../../../../.github/workflows/ci.yml)拥有运行器选择及外层 job 超时。该 job 单独运行 benchmark lane;Vitest 逐文件运行,只负责准备输入、启动测量子进程、汇总结果和执行预算断言。每条被计时的 Node CPU 路径都以纯 Node 执行编译后的 JavaScript,并移除 `NODE_OPTIONS` 且不加载 TypeScript runtime;workspace 裸导入因此从 `benchmarks/node_modules` 通过 package exports 解析到构建后的 `lib/` 入口。
Linux pull request 运行必需的 `node 24 / benchmarks 1/2` 与 `2/2` job,每个对应一个套件阶段,经 `pnpm run check:ci:bench-prebuilt` → `scripts/run-ci-bench.ts --phase` 运行。它们恢复 `node 24 / build` 的 library、原生插件与 Web 资源,只构建 benchmark worker;`pnpm run check:ci:bench` 保留自带的临时 library 构建,按 [PR 产物构建政策](../process/2026-10-05-pr-artifact-typechecks.zh.md)省略重复的 TypeScript 诊断。私有 `@deepseek-ai/dsh-benchmarks` workspace 拥有 benchmark 专属依赖。该命令先构建 workspace library 和 `benchmarks/.dsh-build/` 下的专用 worker,再调用 `vitest.bench.config.ts`。[标准托管运行器说明](../../../../.github/workflows/ci.yml)拥有运行器选择及外层 job 超时。该 job 单独运行 benchmark lane;Vitest 逐文件运行,只负责准备输入、启动测量子进程、汇总结果和执行预算断言。每条被计时的 Node CPU 路径都以纯 Node 执行编译后的 JavaScript,并移除 `NODE_OPTIONS` 且不加载 TypeScript runtime;workspace 裸导入因此从 `benchmarks/node_modules` 通过 package exports 解析到构建后的 `lib/` 入口。
必需性能 gate 位于顶层 `benchmarks/`,按被测用户路径而非 package 归属组织。Host 文件使用 `*.bench.ts`,Client 面文件使用 `*.bench.client.ts`,场景专属 worker 与 fixture 留在对应 benchmark 旁且不带 benchmark 后缀。包内 `.perf.ts` 文件仍是非门禁诊断;`scripts/` 负责编排而不承载 benchmark case。
@@ -24,5 +24,5 @@
en: 9011ce1b4702608d
zh: 214f38794afe13fd
/agent-note-scaled-machine-and-memory-pressure-benchmark-report/consequences:
en: af04c3e97e85f1e3
zh: 533a73e06f708c9d
en: 29a1c6d9f4d55f0d
zh: 2cdf8e50c810059e
@@ -40,4 +40,4 @@ Long-Session `first`, `input`, and `streamWall` include paced replay waits and a
## Consequences
Readers can see each endpoint on reviewed machines with measured defaults, and adjust the storage share, without changing any gate. The page depends on reviewed constants: cross-ISA ratings, shared vCPUs, and disk latency classes are coarse, so results are estimates rather than measurements. The memory view does not measure swap or reclaim costs. The `node 24 / benchmarks` job publishes the page as the `benchmark-report` artifact.
Readers can see each endpoint on reviewed machines with measured defaults, and adjust the storage share, without changing any gate. The page depends on reviewed constants: cross-ISA ratings, shared vCPUs, and disk latency classes are coarse, so results are estimates rather than measurements. The memory view does not measure swap or reclaim costs. The `node 24 / benchmark report` job renders the page from the results of both benchmark phase jobs and publishes it as the `benchmark-report` artifact.
@@ -40,4 +40,4 @@ Session 语料的列表、搜索和 fork 用例报告最大合成工作集的整
## 影响
读者可以在经审阅的机器上查看每个端点及其实测默认值,并调整存储占比,而不改变任何门禁。页面依赖经审阅的常量:跨指令集评分、共享 vCPU 和磁盘延迟等级都较粗略,因此结果是估计值而不是测量值。内存视图不测量交换和回收成本。`node 24 / benchmarks` job 将该页面作为 `benchmark-report` 产物发布。
读者可以在经审阅的机器上查看每个端点及其实测默认值,并调整存储占比,而不改变任何门禁。页面依赖经审阅的常量:跨指令集评分、共享 vCPU 和磁盘延迟等级都较粗略,因此结果是估计值而不是测量值。内存视图不测量交换和回收成本。`node 24 / benchmark report` job 用两个基准阶段 job 的结果渲染该页面,并作为 `benchmark-report` 产物发布。
@@ -21,8 +21,8 @@
en: f07bb6fbbdd01fe4
zh: 9313a0ef2a22af12
/agent-note-linear-credential-matching-and-performance-gates-for-user-text/decision/performance-gate:
en: 3ceb80f455e9a47d
zh: 89d8bd11b42d31b0
en: df973db37213319a
zh: 0a87f164f8dec4f9
/agent-note-linear-credential-matching-and-performance-gates-for-user-text/alternatives-considered:
en: b5bfb4cfa231ce0f
zh: 631b9f2978241bc1
@@ -38,7 +38,7 @@ English | [中文](2026-10-11-user-text-credential-matching.zh.md)
### Performance gate
[benchmarks/user-text](../../../../benchmarks/user-text/user-text.bench.client.ts) runs in the required `node 24 / benchmarks` lane. Its compiled worker uses the production UserText registry and every shipped matcher (session, file, folder, skill, command, whitespace, credential) under plain Node, in two processes: timing and allocation.
[benchmarks/user-text](../../../../benchmarks/user-text/user-text.bench.client.ts) runs in the required `node 24 / benchmarks 2/2` lane. Its compiled worker uses the production UserText registry and every shipped matcher (session, file, folder, skill, command, whitespace, credential) under plain Node, in two processes: timing and allocation.
| Item | Content |
|---|---|
@@ -38,7 +38,7 @@ Status: implemented
### 性能门禁
[benchmarks/user-text](../../../../benchmarks/user-text/user-text.bench.client.ts) 在 `node 24 / benchmarks` 必跑 lane 中运行。编译后的 worker 使用生产的 UserText 注册表和全部已发布匹配器(会话、文件、文件夹、skill、命令、空白、凭据),在纯 Node 下分两个进程运行:计时与分配。
[benchmarks/user-text](../../../../benchmarks/user-text/user-text.bench.client.ts) 在 `node 24 / benchmarks 2/2` 必跑 lane 中运行。编译后的 worker 使用生产的 UserText 注册表和全部已发布匹配器(会话、文件、文件夹、skill、命令、空白、凭据),在纯 Node 下分两个进程运行:计时与分配。
| 项 | 内容 |
|---|---|
@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-11-20-rightbar-drag-restyle-budget.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/testing/2026-11-20-rightbar-drag-restyle-budget.md
/agent-note-right-sidebar-drag-restyle-budget:
en: a467dea2219bda57
zh: 7bcd04d8a6dd8481
/agent-note-right-sidebar-drag-restyle-budget/problem:
en: 693e8d1e4423b78f
zh: c63608002d762c12
/agent-note-right-sidebar-drag-restyle-budget/decision:
en: 83d40f59669f4d33
zh: 1e8de8d1b7e62861
/agent-note-right-sidebar-drag-restyle-budget/calibration:
en: 843539a8446bbe65
zh: 806c97cb8fecdb61
/agent-note-right-sidebar-drag-restyle-budget/alternatives-considered:
en: 721cbfb3276fcb5b
zh: 9557ee132f77f5a6
/agent-note-right-sidebar-drag-restyle-budget/consequences:
en: 8efe7bc510ccabc8
zh: 7c3bca6253797e40
@@ -0,0 +1,43 @@
# Agent Note: Right Sidebar drag restyle budget
Status: implemented
English | [中文](2026-11-20-rightbar-drag-restyle-budget.zh.md)
## Problem
Dragging the right Sidebar beside a long transcript stalled for hundreds of milliseconds per frame. The Conversation body published measured widths as unregistered, inherited custom properties on an ancestor of the whole transcript, so every frame restyled every transcript element, even when the resolved content width did not change; later resize observers that read geometry forced that work synchronously. Existing browser benchmarks open, page, and stream a long Session, but none resizes it, so the regression had no gate.
## Decision
The [right Sidebar drag benchmark](../../../../benchmarks/rightbar-drag-browser/README.md) joins the serial browser inventory. It loads a 120-turn synthetic Session completely, opens the right Sidebar, and drags its handle 40 trusted 8px mouse steps outward and back in a 1680×1000 viewport, in two fresh scaffold worlds and browsers. At that width the transcript column stays below the 680px content-width floor, and each drag asserts it, so the drag changes the column but not the resolved content width.
The restyle ratio is a dimensionless count: the elements reported by every `UpdateLayoutTree` trace event during one drag, divided by the page's element count. The 1680px case budgets the upper median per direction at 1. A second case keeps the rendered column at 720px and crosses the hidden Session panel's reserve-room threshold. It budgets each direction at 0.10: a single transcript-wide recalculation matters even if it happens on only one of the 40 steps. Neither count scales with CPU speed, and no wall-clock endpoint is budgeted or passed to the scaling report.
## Calibration
Local Linux x64 Chromium samples, 40-step drags:
| Workload | Widen | Narrow |
|---|---:|---:|
| 200 turns, before the width axis change | 1,479,947 / 28,895 = 51.2 | 1,909,568 / 28,895 = 66.1 |
| 200 turns, after | 2,622 / 28,895 = 0.09 | 3,368 / 28,895 = 0.12 |
| 120 turns, after (both samples) | 2,622 / 18,383 = 0.14 | 3,368 / 18,383 = 0.18 |
The restyled count after the change is identical across samples and history lengths, so the ratio leaves more than five times headroom at 120 turns, while the pre-change behavior exceeds the budget fifty-fold. The case's first test replays these recorded values as its negative control.
In the 120-turn Chromium trace, 40 `Layout` events per direction ran inside script before the geometry-read fix and none afterwards. A second budget allows 20 script-nested layouts per drag: it rejects repeated synchronous layout without requiring every callback to be layout-free or penalizing normal reflow after script returns.
At 2560px with 120 turns and a 720px rendered column, the required benchmark traces the full drag against built Web artifacts, including the press and release. Before the fix, widening restyled 18,239 / 18,428 = 0.98974, failing the 0.10 budget. A diagnostic trace attributed 14,911 restyled elements to a single reserve-room flip. After the fix, widening restyled 380 / 18,428 = 0.02062 and narrowing restyled 379 / 18,428 = 0.02057. The Sidebar moved 80px each way, the column stayed at 720px, and the probe switched in both directions. The budget allows 1,842 restyles: nearly five times either passing count, but less than 40 updates of 82 elements even without the single large recalculation.
The fixed-column peak has an absolute budget of 512 elements in any one completed `UpdateLayoutTree` event. In a 120-turn local widening trace, 40 passes visited one element each, 40 visited three each, two visited four each, and one visited 212 (380 total). Restoring only inheritance of the dock probe's room value into the message flow in the same browser workload left the small buckets unchanged but replaced the 212-element peak with 14,911. The budget leaves more than twice the healthy peak without growing with the size of unrelated page content. A separate control with 600 total visits passes the cumulative budget either way: 200 passes of three pass the peak budget, one pass of 600 fails it.
## Alternatives considered
- Budget frame gaps or style milliseconds. Rejected for the gate: they need browser-runner calibration that does not exist yet, and they also include the transcript reflow at each new column width, which a resize legitimately pays. They remain diagnostics.
- Add the drag to the manual `apps/web` performance lane. Rejected: that lane runs only on request, and this regression must fail CI.
- Budget a viewport where the content width changes during the drag. Rejected: inherited width changes legitimately restyle descendants, so the count would measure the content width's consumers rather than the regression.
## Consequences
A regression that again publishes per-frame inputs to the transcript fails CI within one benchmark run, with no timing calibration. The case does not cap total layout or paint cost, nor does it cover window resizing, the Conversation's own width handles, or a docked Session panel, whose end reserve can change the content inset during a drag. Chromium's element counting may change across browser versions; an upgrade that moves the counts re-records the calibration values above and in the negative control.
@@ -0,0 +1,43 @@
# Agent Note:右侧栏拖动样式重算预算
Status: implemented
[English](2026-11-20-rightbar-drag-restyle-budget.md) | 中文
## 问题
在长会话旁拖动右侧栏时,每帧会卡住数百毫秒。Conversation 主体把测得的宽度作为未注册、可继承的自定义属性写在整段记录的祖先元素上,因此即使解析后的正文宽度不变,每一帧也要重算整段记录所有元素的样式;随后读取几何值的 ResizeObserver 又迫使这些工作同步完成。现有浏览器基准覆盖打开、分页和流式输出长会话,但没有一个调整它的宽度,所以这一回归没有门禁。
## 决定
[右侧栏拖动基准](../../../../benchmarks/rightbar-drag-browser/README.zh.md)加入串行浏览器清单。它完整加载一个 120 轮合成会话,打开右侧栏,在 1680×1000 视口中把拖拽条向外拖 40 个 8px 的真实鼠标步再拖回,在两个全新的脚手架环境和浏览器中各做一次。该宽度下正文列始终窄于 680px 的正文宽度下限,每次拖动都会断言这一点,因此拖动改变的是列宽,而不是解析后的正文宽度。
样式重算比值是一个无量纲计数:一次拖动期间所有 `UpdateLayoutTree` 追踪事件报告的元素数之和,除以页面元素数。1680px 用例按方向取上中位数,最多为 1。另一个用例让实际渲染的正文列保持 720px,同时跨越隐藏会话面板的空间预留阈值。其每个方向的比值不得超过 0.10:在 40 步中,即使只有一步重算整段记录的样式,也不能忽略。两种计数都不随 CPU 速度缩放;没有为墙钟终点设置预算,也不将其传给缩放报告。
## 校准
本地 Linux x64 Chromium 样本,每次拖动 40 步:
| 负载 | 加宽 | 缩窄 |
|---|---:|---:|
| 200 轮,宽度轴改动前 | 1,479,947 / 28,895 = 51.2 | 1,909,568 / 28,895 = 66.1 |
| 200 轮,改动后 | 2,622 / 28,895 = 0.09 | 3,368 / 28,895 = 0.12 |
| 120 轮,改动后(两个样本相同) | 2,622 / 18,383 = 0.14 | 3,368 / 18,383 = 0.18 |
改动后重算的元素数在各样本和不同历史长度下完全相同,因此 120 轮时比值留有五倍以上余量,而改动前的行为超出预算五十倍。用例的第一个测试回放这些记录值作为负对照。
在 120 轮负载的 Chromium 追踪中,几何读取修复前每个方向都有 40 次 `Layout` 发生在脚本执行期间,修复后均为 0 次。第二项预算允许每次拖动最多 20 次脚本内布局:它能拦住反复触发同步布局的回归,而不要求每个回调都没有布局,也不惩罚脚本返回后的正常重排。
在 2560px 视口中完整加载 120 轮、正文实际列宽固定为 720px 时,必需基准使用构建后的 Web 产物,追踪包含按下和松开鼠标的整个拖动过程。修复前,加宽方向的重算比值为 18,239 / 18,428 = 0.98974,超过 0.10 的预算。诊断追踪显示,仅一次预留状态翻转就重算了 14,911 个元素。修复后,加宽方向为 380 / 18,428 = 0.02062,缩窄方向为 379 / 18,428 = 0.02057。两个方向的侧栏都移动了 80px,正文列保持 720px,探针均发生翻转。预算允许重算 1,842 个元素,接近两个实测值的五倍;即使没有那次大幅重算,每步重算 82 个元素、连续 40 步也会超限。
正文列固定时,单个完整 `UpdateLayoutTree` 事件最多可重算 512 个元素。在本地 120 轮的加宽追踪中,40 次各重算 1 个元素,40 次各重算 3 个,2 次各重算 4 个,1 次重算 212 个(累计 380 个)。在相同浏览器负载中,只恢复消息流对停靠探针空间标记的继承,小规模重算的分布不变,峰值却从 212 变为 14,911。预算为健康峰值留出两倍以上余量,且不随页面上无关内容的增多而放宽。另一组对照的累计计数同为 600,两者均满足累计预算:分成 200 次、每次 3 个满足峰值预算,集中在一次重算 600 个则失败。
## 备选方案
- 为帧间隔或样式毫秒数设预算。门禁不采用:它们需要尚不存在的浏览器 runner 校准,而且还包含按每个新列宽重排正文的成本,这是缩放本应付出的。它们保留为诊断输出。
- 把拖动加入 `apps/web` 的手动性能通道。不采用:该通道只按需运行,而这一回归必须让 CI 失败。
- 选一个拖动中正文宽度会变化的视口设预算。不采用:继承的宽度变化本来就会重算后代样式,计数测到的会是正文宽度的使用者,而不是这一回归。
## 影响
再次把逐帧变化的输入传给整段记录的回归会在一次基准运行内让 CI 失败,不需要任何计时校准。本用例不为布局或绘制的总成本设限,也不覆盖窗口缩放、Conversation 自身的宽度拖拽条,也不测量停靠的 Session 面板,因为它的末端预留可能在拖动中改变正文内边距。Chromium 的元素计数方式可能随浏览器版本变化;改变计数的升级需要重新记录上面的校准值和负对照中的值。
@@ -5,7 +5,7 @@ description: Use when landing a stack of dependent GitHub PRs (A ← B ← C, wh
# Landing an official GitHub PR stack
Land dependent PRs through GitHub's native stack object and `gh stack merge`. Do not reproduce stack semantics by merging and retargeting individual PRs with `gh pr merge` and `gh pr edit`. The root [AGENTS.md](../../../AGENTS.md) owns the allowed merge-forward and rebase histories; the [stack review guide](../../../docs/cookbook/responding-to-pr-review-on-a-stack.md) owns review-fix propagation.
Land dependent PRs through GitHub's native stack object and `gh stack merge`. Do not reproduce stack semantics by merging and retargeting individual PRs with `gh pr merge` and `gh pr edit`. The root [AGENTS.md](../../../AGENTS.md) owns the rebase-with-rerere default and the author-requested merge-forward exception; the [stack review guide](../../../docs/cookbook/responding-to-pr-review-on-a-stack.md) owns review-fix propagation.
## Require native stack support
@@ -67,10 +67,10 @@ Never dissolve, reorder, or rebuild an existing stack automatically; `gh stack l
## Refresh only when needed
Do not rewrite branches merely because a refresh mechanism exists. When the live merge state or repository rules require an updated trunk, choose either allowed history:
Do not rewrite branches merely because a refresh mechanism exists. When the live merge state or repository rules require an updated trunk, enable rerere (`git config rerere.enabled true`), then rebase; inspect each replayed resolution before staging it. Use merge-forward only when the PR author explicitly asks for it:
- **Native cascading rebase:** check out the remote stack with `gh stack checkout <pr-or-stack>` when it is not tracked locally, then run `gh stack sync`. The command may rebase and lease-protected force-push every active layer before local validation. Immediately inspect the rewritten scope, run the relevant checks for every affected layer, and do not merge or claim readiness until they pass. If sync detects a rebase conflict, use `gh stack rebase`, resolve and validate it, then publish with `gh stack push`. If checkout or sync reports divergent local and remote stack compositions, cancel and ask rather than deleting or recreating the remote stack automatically.
- **Incremental merge-forward:** merge the trunk into the bottom affected branch, then propagate each updated parent into its child in bottom-to-top order and push normally. If the base advances during an in-progress merge, preserve that checkpoint before merging the newer tip.
- **Incremental merge-forward, on the PR author's explicit request:** merge the trunk into the bottom affected branch, then propagate each updated parent into its child in bottom-to-top order and push normally. If the base advances during an in-progress merge, preserve that checkpoint before merging the newer tip.
Any history rewrite is allowed after review, but it invalidates commit-OID assumptions. Re-fetch exact heads and re-audit unresolved review threads, approvals, mergeability, and checks after the push. Never use raw `--force` or overwrite a concurrently advanced remote head.
+1 -1
View File
@@ -80,7 +80,7 @@ Run the complete local approximation only when the user explicitly requests it,
## Protect history-rewriting pushes
Rebase is allowed for standalone and stacked PR branches, including after review. Before a standalone history rewrite, fetch the current remote branch and record its exact OID; publish with `--force-with-lease=<branch>:<observed-oid>` so a concurrent update aborts the push. `gh stack push` and `gh stack sync` supply lease protection for their managed branches. Raw `--force` is never allowed.
Rebase is the default refresh for standalone and stacked PR branches, including after review; the root [AGENTS.md](../../../AGENTS.md) owns that choice and its rerere setting. Before a standalone history rewrite, fetch the current remote branch and record its exact OID; publish with `--force-with-lease=<branch>:<observed-oid>` so a concurrent update aborts the push. `gh stack push` and `gh stack sync` supply lease protection for their managed branches. Raw `--force` is never allowed.
After any rewritten push, fetch the live heads again and re-audit unresolved review threads, approvals, mergeability, and checks. Commit hashes and inline-comment anchors from before the rewrite are not current evidence.
-1
View File
@@ -1 +0,0 @@
__pycache__/
+518 -50
View File
@@ -56,16 +56,18 @@ jobs:
run: node --import tsx tests/isolated-install.mjs
# Three enterprise jobs isolate coverage, static analysis, and the
# build-backed consumer tail. The consumer job owns the only Linux build so
# all three jobs enter runner allocation independently.
# Enterprise jobs isolate coverage, static analysis, and the build-backed
# tail. Coverage runs two file shards on separate runners and merges them on
# one small report runner. The build job
# owns the only Linux artifact build; the consumer job and the two web
# snapshot shards restore its output instead of rebuilding.
#
# FAILOVER (Linux): each Linux enterprise job resolves its pool through the
# DSH_CI_FAILOVER_LINUX repository variable. Unset (normal), the expressions
# pick the hosted enterprise pools below. Setting the variable to
# 'selfhosted' (repo Settings → Actions → Variables; writer-manageable
# repository state — not PR-editable, no merge required) retargets all
# three onto the in-house
# repository state — not PR-editable, no merge required) retargets them
# all onto the in-house
# vm-backup pool and re-running the failed jobs is the entire switch —
# see .agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md.
# Setting the variable to 'blacksmith' instead routes the same jobs onto
@@ -149,8 +151,16 @@ jobs:
&& github.event.pull_request.user.login != 'dependabot[bot]'
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|| 'dsh-ubuntu-24-04-16core' }}
name: node 24 / coverage
# Two instrumented file shards run on separate runners; the first also
# runs the uninstrumented heavy suites. node-24-coverage-report merges the
# shard blobs and owns the thresholds and the duration history.
strategy:
fail-fast: false
matrix:
shard: [1, 2]
name: node 24 / coverage ${{ matrix.shard }}/2
env:
DSH_COVERAGE_SHARD: ${{ matrix.shard }}/2
# Shared hosts expose host CPUs, not an isolated allocation.
DSH_COVERAGE_MAX_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }}
DSH_COVERAGE_PARTITIONS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '4' || '' }}
@@ -248,8 +258,92 @@ jobs:
path: ~/.cache/dsh-ci/bubblewrap
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
- name: Run exhaustive coverage
run: pnpm run check:ci:coverage
- name: Run coverage shard
run: pnpm run check:ci:coverage-shard
- name: Upload coverage shard blobs
uses: actions/upload-artifact@v7.0.1
with:
name: coverage-blobs-${{ matrix.shard }}
path: coverage/shard/
# A re-run of this shard replaces the previous attempt's output.
overwrite: true
if-no-files-found: error
include-hidden-files: true
retention-days: 30
# Merging blobs and checking thresholds runs after both coverage shards
# succeed. The merge converts every shard's V8 coverage to per-file reports
# and needs several GB of heap: a 2-vCPU runner took 154s against ~30s on the
# former 16-vCPU lane (run 44667701311), so this job uses an 8-vCPU runner.
# A failed shard skips this job, and the skipped result fails all-checks-passed.
node-24-coverage-report:
needs: node-24-coverage
if: github.event_name == 'pull_request'
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-8vcpu-ubuntu-2404'
|| vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
&& github.event.pull_request.user.login != 'dependabot[bot]'
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|| 'dsh-ubuntu-24-04-8core' }}
name: node 24 / coverage report
steps:
# Runner cleanup owns tool caches and fixtures, including cancelled runs.
- name: Use runner-owned temporary storage
run: |
echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
# Redirect the Node compile cache (enabled by pnpm and TypeScript) off
# the root partition's /tmp before the first pnpm call in this lane.
- name: Redirect Node compile cache to runner temp
run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
- uses: pnpm/action-setup@v5.0.0
with:
dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: ${{ env.PRIMARY_NODE_VERSION }}
- name: Configure pnpm store path
id: pnpm-store
run: |
store_root="$HOME/.local/share/pnpm/store"
echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
echo "path=$store_path" >> "$GITHUB_OUTPUT"
# Self-hosted runners reuse the shared persistent pnpm store.
# Hosted runners restore the remote cache into their ephemeral store.
- uses: actions/cache/restore@v6.1.0
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Download coverage shard blobs
uses: actions/download-artifact@v8.0.1
with:
pattern: coverage-blobs-*
path: ${{ runner.temp }}/coverage-shards
# Node sizes its default heap from host memory; merging the whole
# inventory exceeded the ~2 GB default of a 2-vCPU runner (run
# 44664262449), so the merge states its heap instead of inheriting one.
- name: Merge coverage shards and check thresholds
env:
NODE_OPTIONS: --max-old-space-size=4096
run: pnpm run test:coverage:merge-shards "$RUNNER_TEMP/coverage-shards"
- name: Save coverage duration history
if: ${{ !cancelled() }}
@@ -323,17 +417,33 @@ jobs:
- name: Run lint and duplication
run: pnpm run check:ci:lint:contracts-ready
# The two suite phases run on separate idle runners from the shared build
# output: phase `first` holds the corpus cases that tolerate a sibling and
# phase `last` the browser, animation-frame, and fresh-child cases that need
# an idle runner (SERIAL_BENCH_FILES in scripts/run-bench-suite.ts).
node-24-bench:
needs: node-24-build
if: github.event_name == 'pull_request'
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
|| 'ubuntu-24.04' }}
name: node 24 / benchmarks
# Wall-clock budgets need an otherwise idle runner, so this job runs the
# benchmark lane alone instead of joining a concurrent gate aggregate, and
# keeps its own two-file parallelism inside that runner. The self-hosted
# failover pool is shared, so the benchmarks stay on hosted Linux there.
strategy:
fail-fast: false
matrix:
include:
- shard: 1
phase: first
- shard: 2
phase: last
name: node 24 / benchmarks ${{ matrix.shard }}/2
# Wall-clock budgets need an otherwise idle runner, so each phase runs
# alone on its runner instead of joining a concurrent gate aggregate; the
# first phase keeps its own two-file parallelism inside that runner. The
# self-hosted failover pool is shared, so the benchmarks stay on hosted
# Linux there.
timeout-minutes: 20
env:
DSH_BENCH_PHASE: ${{ matrix.phase }}
steps:
- uses: actions/checkout@v7.0.1
with:
@@ -365,18 +475,95 @@ jobs:
- name: Install (immutable)
run: pnpm install --frozen-lockfile
- name: Download build output
uses: actions/download-artifact@v8.0.1
with:
name: build-output
path: ${{ runner.temp }}/build-output
- name: Unpack build output
run: |
set -o pipefail
archive="$RUNNER_TEMP/build-output/build-output.tar.zst"
# -m stamps restored files with the extraction time: newer than this
# checkout and never in the future.
zstd -dc -T0 "$archive" | tar -xmf -
test -f apps/cli/lib/bin.js && test -f apps/web/dist/index.html && test -f .dsh-build/client-build-environment.json
# node-24-build can run on another pool (vm-backup under self-hosted
# failover) while the benchmarks stay on hosted Linux, so the restored
# Node-API addon is loaded here and rebuilt on this runner if it fails.
- name: Rebuild the native addon if the restored one does not load
run: |
addon=native/system/packages/linux-x64/bin/glibc/system.node
if node -e 'process.dlopen({ exports: {} }, process.argv[1])' "$addon"; then
echo "Restored native addon loads on this runner."
else
echo "::notice::Restored native addon does not load on this runner; rebuilding it."
pnpm run build:native-system
node -e 'process.dlopen({ exports: {} }, process.argv[1])' "$addon"
fi
- name: Install benchmark browser and hosted dependencies
run: pnpm --filter @deepseek-ai/dsh-benchmarks exec playwright install --with-deps chromium
- name: Run performance benchmarks
env:
DSH_GATE_VERBOSE: '1'
run: pnpm run check:ci:bench
run: pnpm run check:ci:bench-prebuilt
# The report global teardown writes results.jsonl and environment.json
# after the run, including after a failing budget assertion; the report
# job renders both phases into one report. A phase that fails before
# recording any timing has no results, so missing files warn.
- name: Upload benchmark results
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v7.0.1
with:
name: benchmark-results-${{ matrix.shard }}
path: benchmarks/.dsh-report/
include-hidden-files: true
if-no-files-found: warn
retention-days: 7
# A re-run of this phase replaces the previous attempt's results.
overwrite: true
# Bookkeeping only: renders one scaled report from both phases, including
# after a failing budget. The benchmark verdict comes from node-24-bench, so
# this job stays out of all-checks-passed.
node-24-bench-report:
needs: node-24-bench
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-2vcpu-ubuntu-2404'
|| 'ubuntu-latest' }}
name: node 24 / benchmark report
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@v7.0.0
with:
node-version: ${{ env.PRIMARY_NODE_VERSION }}
- name: Download benchmark results
uses: actions/download-artifact@v8.0.1
with:
pattern: benchmark-results-*
path: ${{ runner.temp }}/benchmark-results
# The renderer runs under Node type stripping and needs no install.
- name: Render scaled benchmark report
run: |
shopt -s nullglob
phases=("$RUNNER_TEMP"/benchmark-results/*/)
if (( ${#phases[@]} == 0 )); then
echo "::warning::No benchmark phase uploaded results."
exit 0
fi
node scripts/render-benchmark-report.ts benchmarks/.dsh-report "${phases[@]}"
# The report global teardown renders benchmarks/.dsh-report after the run,
# including after a failing budget assertion. A run that fails before
# recording any timing has no report, so missing files warn instead of
# failing the benchmark job a second time.
- name: Upload scaled benchmark report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v7.0.1
@@ -387,7 +574,117 @@ jobs:
if-no-files-found: warn
retention-days: 7
# Build the artifacts once, run the cheap readers, and publish the output
# for the downstream consumer and web snapshot jobs, which restore it
# instead of rebuilding.
node-24-build:
if: github.event_name == 'pull_request'
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404'
|| vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
&& github.event.pull_request.user.login != 'dependabot[bot]'
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|| 'dsh-ubuntu-24-04-16core' }}
name: node 24 / build
env:
# Shared hosts expose host CPUs, not an isolated allocation.
DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }}
DSH_PUBLINT_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }}
# A failing gate aborts its running siblings.
DSH_GATE_FAIL_FAST: '1'
steps:
# Runner cleanup owns tool caches and fixtures, including cancelled runs.
- name: Use runner-owned temporary storage
run: |
echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
# Redirect the Node compile cache (enabled by pnpm and TypeScript) off
# the root partition's /tmp before the first pnpm call in this lane.
- name: Redirect Node compile cache to runner temp
run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
- uses: pnpm/action-setup@v5.0.0
with:
dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: ${{ env.PRIMARY_NODE_VERSION }}
- name: Configure pnpm store path
id: pnpm-store
run: |
store_root="$HOME/.local/share/pnpm/store"
echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
echo "path=$store_path" >> "$GITHUB_OUTPUT"
# Pull requests restore the pnpm store without paying compression and
# upload on the required path. Self-hosted runners reuse the shared
# persistent store instead of restoring the remote archive.
- uses: actions/cache/restore@v6.1.0
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Everything the build adds to the ignored or untracked set is its output.
- name: Record files before the build
run: git status --porcelain=v1 --ignored --untracked-files=normal > "$RUNNER_TEMP/files-before.txt"
- name: Build artifacts and run the cheap readers
run: pnpm run check:ci:build
- name: Pack build output
env:
# Compression costs well under a second at -T0; a smaller archive
# shortens the upload and every download.
ZSTD_LEVEL: '9'
run: |
set -o pipefail
out="$RUNNER_TEMP/build-output"
mkdir -p "$out"
git status --porcelain=v1 --ignored --untracked-files=normal > "$RUNNER_TEMP/files-after.txt"
comm -13 <(sort "$RUNNER_TEMP/files-before.txt") <(sort "$RUNNER_TEMP/files-after.txt") \
| sed -n -E 's/^(!!|\?\?) //p' \
| grep -v -E '(^|/)(node_modules|\.node-next-types-[^/]*|\.doc-typecheck-[^/]*|\.oxlint-contract-[^/]*|\.typert-[^/]*|\.cache)/?$' \
| sed 's#/$##' > "$out/paths.txt"
echo "build output entries: $(wc -l < "$out/paths.txt")"
du -sch $(cat "$out/paths.txt") | tail -1
tar -cf - -T "$out/paths.txt" | zstd -q -T0 -"$ZSTD_LEVEL" -o "$out/build-output.tar.zst"
zstd -dc "$out/build-output.tar.zst" | tar -tf - > "$out/contents.txt"
for required in apps/cli/lib/bin.js apps/web/dist/index.html .dsh-build/client-build-environment.json; do
grep -qx "$required" "$out/contents.txt" || { echo "::error::build output is missing $required"; exit 1; }
done
echo "archive entries: $(wc -l < "$out/contents.txt")"
rm "$out/contents.txt"
- name: Upload build output
uses: actions/upload-artifact@v7.0.1
with:
name: build-output
path: |
${{ runner.temp }}/build-output/build-output.tar.zst
${{ runner.temp }}/build-output/paths.txt
# Re-running a failed downstream job does not rebuild; keep the output
# for GitHub's 30-day re-run window.
retention-days: 30
compression-level: 0
if-no-files-found: error
# A re-run of this job replaces the previous attempt's output.
overwrite: true
node-24-consumers:
needs: node-24-build
if: github.event_name == 'pull_request'
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404'
@@ -399,14 +696,152 @@ jobs:
env:
# Shared hosts expose host CPUs, not an isolated allocation.
DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }}
DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }}
DSH_PUBLINT_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }}
DSH_WEB_SNAPSHOT_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }}
DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }}
DSH_NODE_COMPAT_SKIP_TYPECHECK: '1'
# A failing gate aborts its running siblings: a failing build stops the
# independent Node compatibility smoke, and a failing reader (e.g.
# publint) stops the remaining artifact consumers.
# A failing gate aborts its running siblings.
DSH_GATE_FAIL_FAST: '1'
steps:
# Runner cleanup owns tool caches and fixtures, including cancelled runs.
- name: Use runner-owned temporary storage
run: |
echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
# Redirect the Node compile cache (enabled by pnpm and TypeScript) off
# the root partition's /tmp before the first pnpm call in this lane.
- name: Redirect Node compile cache to runner temp
run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
- uses: pnpm/action-setup@v5.0.0
with:
dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: ${{ env.PRIMARY_NODE_VERSION }}
- name: Configure pnpm store path
id: pnpm-store
run: |
store_root="$HOME/.local/share/pnpm/store"
echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
echo "path=$store_path" >> "$GITHUB_OUTPUT"
# Pull requests restore the pnpm store without paying compression and
# upload on the required path. Self-hosted runners reuse the shared
# persistent store instead of restoring the remote archive.
- uses: actions/cache/restore@v6.1.0
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
# The persistent self-hosted pool keeps ~/.cache between jobs on its own
# layout, so the archive cache follows the hosted-only pnpm store guard.
- name: Restore verified bubblewrap archive
id: bubblewrap-cache
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
uses: actions/cache/restore@v6.1.0
with:
path: ~/.cache/dsh-ci/bubblewrap
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
- name: Install dependencies and prepare bubblewrap
run: |
pnpm install --frozen-lockfile &
install_pid=$!
bash scripts/prepare-ci-bubblewrap.sh &
sandbox_pid=$!
install_status=0
wait "$install_pid" || install_status=$?
sandbox_status=0
wait "$sandbox_pid" || sandbox_status=$?
if (( install_status != 0 )); then exit "$install_status"; fi
exit "$sandbox_status"
- name: Save verified bubblewrap archive
if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6.1.0
with:
path: ~/.cache/dsh-ci/bubblewrap
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
# Restore the build job's output after the install, so no install or
# postinstall step can replace restored files. The fixed artifact name
# resolves within this run, including a re-run of this job alone.
- name: Download build output
uses: actions/download-artifact@v8.0.1
with:
name: build-output
path: ${{ runner.temp }}/build-output
- name: Unpack build output
run: |
set -o pipefail
archive="$RUNNER_TEMP/build-output/build-output.tar.zst"
# -m stamps restored files with the extraction time: newer than this
# checkout and never in the future. Build-time mtimes ahead of the
# clock make HMR treat freshly loaded lib/ modules as changed.
zstd -dc -T0 "$archive" | tar -xmf -
test -f apps/cli/lib/bin.js && test -f apps/web/dist/index.html && test -f .dsh-build/client-build-environment.json
# No gate reads the Office runtime output, so it builds beside the gates.
# GitHub runners keep a background process started in one step alive for
# the later steps of the same job; the final step collects its status.
- name: Start the Linux Office runtime build
id: office-runtime
run: |
(
status=0
CI=true pnpm run prepare:primary-runtime --target linux-x64 --output "$RUNNER_TEMP/office-runtime" --cache "$RUNNER_TEMP/office-runtime-downloads" || status=$?
echo "$status" > "$RUNNER_TEMP/office-runtime.status"
) > "$RUNNER_TEMP/office-runtime.log" 2>&1 &
echo "$!" > "$RUNNER_TEMP/office-runtime.pid"
- name: Run compatibility, snapshot, and artifact gates
run: pnpm run check:ci:consumers-prebuilt
- name: Wait for the Linux Office runtime
if: ${{ !cancelled() && steps.office-runtime.outcome == 'success' }}
run: |
pid=$(cat "$RUNNER_TEMP/office-runtime.pid")
while kill -0 "$pid" 2>/dev/null; do sleep 1; done
cat "$RUNNER_TEMP/office-runtime.log"
status=$(cat "$RUNNER_TEMP/office-runtime.status" 2>/dev/null || echo missing)
if [[ "$status" != 0 ]]; then
echo "::error::Linux Office runtime build failed with status $status"
exit 1
fi
node-24-web-snapshot:
needs: node-24-build
if: github.event_name == 'pull_request'
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404'
|| vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
&& github.event.pull_request.user.login != 'dependabot[bot]'
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|| 'dsh-ubuntu-24-04-16core' }}
strategy:
fail-fast: false
matrix:
shard: [1, 2]
name: node 24 / web snapshots ${{ matrix.shard }}/2
env:
# Shared hosts expose host CPUs, not an isolated allocation.
DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }}
DSH_WEB_SNAPSHOT_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }}
DSH_WEB_SNAPSHOT_SHARD: ${{ matrix.shard }}/2
# Every shard reads these shares. Each shard runs alone on its
# machine; the last shard also runs the ~40s of serial files first.
DSH_WEB_SNAPSHOT_SHARD_SHARES: '0.54,0.46'
# A failing gate aborts its running siblings.
DSH_GATE_FAIL_FAST: '1'
steps:
# Runner cleanup owns tool caches and fixtures, including cancelled runs.
@@ -440,11 +875,9 @@ jobs:
store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
echo "path=$store_path" >> "$GITHUB_OUTPUT"
# Pull requests restore the pnpm store and Playwright caches without paying
# compression and upload on the required path. No master job saves these
# hosted cache keys, so each restore-keys fallback hits the matching archived
# entry until it evicts, after which the store is cold. Self-hosted runners
# reuse the shared persistent store instead of restoring the remote archive.
# Pull requests restore the pnpm store without paying compression and
# upload on the required path. Self-hosted runners reuse the shared
# persistent store instead of restoring the remote archive.
- uses: actions/cache/restore@v6.1.0
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
with:
@@ -492,9 +925,11 @@ jobs:
path: ~/.cache/dsh-ci/bubblewrap
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
# Blacksmith's Ubuntu HTTP archive endpoints can be unreachable while HTTPS works.
- name: Use HTTPS for Ubuntu archives on Blacksmith
if: vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
# Ubuntu HTTP archive mirrors can stall for tens of seconds per package
# (Blacksmith lists http://azure.archive.ubuntu.com first), so every
# ephemeral runner fetches the archive over HTTPS before Playwright's apt.
- name: Use HTTPS for Ubuntu archives
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
run: |
sudo python3 - <<'PY'
from pathlib import Path
@@ -507,29 +942,60 @@ jobs:
for source in sources:
if source.is_file():
source.write_text(re.sub(
r'http://((?:[a-z]{2}\.)?archive\.ubuntu\.com|security\.ubuntu\.com)/',
r'https://\1/', source.read_text()))
r'http://(?:[a-z0-9-]+\.)*(archive|security)\.ubuntu\.com/',
r'https://\1.ubuntu.com/', source.read_text()))
PY
- name: Install Playwright Chromium, WebKit, and hosted dependencies
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
# Ephemeral runner images can carry Ubuntu mirrors whose HTTP endpoints are unreachable.
# The browser install overlaps the artifact download and unpack. GitHub
# runners keep a background process started in one step alive for the
# later steps of the same job, and the wait step below collects its exit
# status. The persistent VM image owns Playwright's Linux system packages,
# so the failover pool skips apt instead of mutating the shared host.
- name: Start Playwright browser install
env:
PLAYWRIGHT_INSTALL_MODE: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && 'browsers' || 'with-deps' }}
run: |
sudo find /etc/apt -maxdepth 2 -type f \( -name '*.list' -o -name '*.sources' \) -exec sed -i -E 's@http://([a-z]{2}\.)?archive\.ubuntu\.com/ubuntu@https://archive.ubuntu.com/ubuntu@g; s@http://security\.ubuntu\.com/ubuntu@https://security.ubuntu.com/ubuntu@g' {} +
pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install --with-deps chromium webkit
deps=()
if [[ "$PLAYWRIGHT_INSTALL_MODE" == with-deps ]]; then deps=(--with-deps); fi
(
status=0
pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install "${deps[@]}" chromium webkit || status=$?
echo "$status" > "$RUNNER_TEMP/playwright-install.status"
) > "$RUNNER_TEMP/playwright-install.log" 2>&1 &
echo "$!" > "$RUNNER_TEMP/playwright-install.pid"
# The persistent VM image owns Playwright's Linux system packages; do
# not mutate the shared host with apt on every failover run.
- name: Install Playwright Chromium and WebKit on the failover VM
if: vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]'
run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install chromium webkit
# Restore the build job's output after the install, so no install or
# postinstall step can replace restored files. The fixed artifact name
# resolves within this run, including a re-run of this job alone.
- name: Download build output
uses: actions/download-artifact@v8.0.1
with:
name: build-output
path: ${{ runner.temp }}/build-output
- name: Build and execute the Linux Office runtime
run: CI=true pnpm run prepare:primary-runtime --target linux-x64 --output "$RUNNER_TEMP/office-runtime" --cache "$RUNNER_TEMP/office-runtime-downloads"
- name: Unpack build output
run: |
set -o pipefail
archive="$RUNNER_TEMP/build-output/build-output.tar.zst"
# -m stamps restored files with the extraction time: newer than this
# checkout and never in the future. Build-time mtimes ahead of the
# clock make HMR treat freshly loaded lib/ modules as changed.
zstd -dc -T0 "$archive" | tar -xmf -
test -f apps/cli/lib/bin.js && test -f apps/web/dist/index.html && test -f .dsh-build/client-build-environment.json
- name: Run compatibility, snapshot, and artifact gates
run: pnpm run check:ci:consumers
- name: Wait for Playwright browsers
run: |
pid=$(cat "$RUNNER_TEMP/playwright-install.pid")
while kill -0 "$pid" 2>/dev/null; do sleep 1; done
cat "$RUNNER_TEMP/playwright-install.log"
status=$(cat "$RUNNER_TEMP/playwright-install.status" 2>/dev/null || echo missing)
if [[ "$status" != 0 ]]; then
echo "::error::Playwright browser install failed with status $status"
exit 1
fi
- name: Run web browser snapshot shard
run: pnpm run check:ci:web-snapshot-prebuilt
node-compat:
needs: publisher-isolated
@@ -640,7 +1106,9 @@ jobs:
# Single stable required check for branch protection: require "all checks
# passed" instead of enumerating matrix legs whose names change as lanes and
# node versions evolve. Every blocking job in THIS workflow must be listed in
# `needs`. `needs` cannot cross workflow files: native Windows jobs report
# `needs` or be needed by a listed job: a failed node-24-coverage shard skips
# node-24-coverage-report, and a skipped need fails this verdict. `needs`
# cannot cross workflow files: native Windows jobs report
# the separate "windows checks passed" verdict from ci-windows.yml, Python
# jobs report "python checks passed" from ci-python.yml, and Wine plus the
# master-only runtime targets live in ci-master.yml.
@@ -663,7 +1131,7 @@ jobs:
&& github.event.pull_request.user.login != 'dependabot[bot]'
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|| 'ubuntu-latest' }}
needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat]
needs: [publisher-isolated, node-24, node-24-coverage-report, node-24-lint, node-24-bench, node-24-build, node-24-consumers, node-24-web-snapshot, node-compat]
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
steps:
- name: Fail if any needed job did not succeed
+1 -2
View File
@@ -34,9 +34,8 @@ dist-exe/
apps/desktop/.desktop-build/
apps/desktop/.desktop-dev/
python/sdk-runtime/src/deepseek_harness_runtime/runtime/
python/**/__pycache__/
__pycache__/
python/**/.pytest_cache/
packages/**/__pycache__/
apps/web/dist/
apps/cli/docs/
.artifacts/
+1 -1
View File
@@ -163,7 +163,7 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and
- **Design each tool's UI presentation up front.** Host presenters stay pure; Web cards derive from raw events and persisted result metadata ([cookbook](docs/cookbook/adding-a-tool.md)).
- **Plan unit, e2e, and snapshot coverage** for capability seams, lifecycle paths, and transcript output; include missing snapshot-harness support in the same change.
- **Both SDKs project the loop.** Agent-loop, session-lifecycle, and `SessionEventMap` changes update the TypeScript and Python SDK expected outputs in the same PR; `pnpm run test` covers neither ([surfaces](docs/testing.md#when-a-snapshot-test-is-required)).
- **Choose PR history deliberately.** Split independent changes and fix the introducing PR before propagation. Standalone/stack branches may merge-forward or rebase. Rewrites use `--force-with-lease`, abort on remote movement, never raw `--force`; preserve an in-progress merge-forward checkpoint before taking a newer base ([rationale](.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md)).
- **Choose PR history deliberately.** Split independent changes and fix the introducing PR before propagation. Rebase branches with `rerere.enabled`; merge-forward only on the PR author's explicit request, keeping in-progress checkpoints. Rewrites use `--force-with-lease`, abort on remote movement, never raw `--force` ([rationale](.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md)).
- **Labels:** one PR `kind/*`, all material `area/*`, and native Issue Type ([taxonomy](.agents/notes/implemented/process/2026-08-08-unified-github-label-taxonomy.md)).
- **PR descriptions:** write and update every PR description with [dsh-pr-description](.agents/skills/dsh-pr-description/SKILL.md).
- TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)).
+1
View File
@@ -137,6 +137,7 @@ External packages installed for runtime use or embedded in distributed Host or b
| [`papaparse`](https://github.com/mholt/PapaParse) | MIT |
| [`pdfjs-dist`](https://github.com/mozilla/pdf.js) | Apache-2.0 |
| [`picomatch`](https://github.com/micromatch/picomatch) | MIT |
| [`qrcode.react`](https://github.com/zpao/qrcode.react) | ISC |
| [`react`](https://github.com/facebook/react) | MIT |
| [`react-dom`](https://github.com/facebook/react) | MIT |
| [`readable-stream`](https://github.com/nodejs/readable-stream) | MIT |
@@ -9,7 +9,7 @@ Signatures show resolved return values after await. ActionResult = { dispatched:
Supported modifier names depend on the platform and the operation; see the platform guidance.
Setup and discovery:
- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions.
- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions.
- cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp.
- cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches.
- cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation.
@@ -21,7 +21,7 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
import NodeRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh-ptc-runtime-node'
import Sandbox from '@deepseek-ai/dsh-sandbox-local'
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
@@ -43,6 +43,15 @@ const PERSONA = 'You are a coding agent. You work by writing TypeScript programs
+ 'batch related tool work into one program and inspect ONLY the findings that matter.'
const WORKSPACE_PROBE = 'dragonfruit-8675309'
/** Node runtime program formats the keyless cases run under; their programs end with inspect, so both formats accept them unchanged. */
const PTC_MODES = [
{ mode: 'per-call', config: { executionMode: 'per-call' } },
{ mode: 'scoped REPL', config: { executionMode: 'persistent-in-memory', replScoped: true } },
] as const satisfies readonly { mode: string; config: NodeRuntimeConfig }[]
type PtcMode = typeof PTC_MODES[number]
/** The with-key model cases keep function-body programs. */
const PER_CALL: PtcMode = PTC_MODES[0]
let ctx: Context | undefined
let workdir: string | undefined
@@ -70,7 +79,7 @@ async function ptcModeHarness(cwd: string): Promise<Context> {
await harness.plugin(BashEnvPlugin)
await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 })
await harness.plugin(ToolBash)
await mountRuntime(harness)
await mountRuntime(harness, PER_CALL)
return harness
}
@@ -87,7 +96,7 @@ async function workspacePtcModeHarness(): Promise<Context> {
await harness.plugin(AgentLoop, { agents: [] })
await harness.plugin(DeepSeekAuth)
await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
await mountRuntime(harness)
await mountRuntime(harness, PER_CALL)
return harness
}
@@ -123,7 +132,7 @@ function completion(result: ToolExecutionResult): unknown {
return JSON.parse(text)
}
async function mountRuntime(harness: Context): Promise<void> {
async function mountRuntime(harness: Context, mode: PtcMode): Promise<void> {
onTestFinished(async () => { await harness.fiber.dispose() })
if (!harness.get('sessions')) await harness.plugin(SessionStore)
if (!harness.get('fs')) await harness.plugin(LocalFileSystem)
@@ -131,20 +140,20 @@ async function mountRuntime(harness: Context): Promise<void> {
if (!harness.get('sandbox')) await harness.plugin(Sandbox, {})
if (!harness.get('sessionProjections')) await harness.plugin(SessionProjectionRegistry)
if (!harness.get('sandboxPolicy')) await harness.plugin(SandboxPolicy, { mode: 'danger-full-access' })
await harness.plugin(NodeRuntime, {})
await harness.plugin(NodeRuntime, mode.config)
}
/** Keyless real-process harness for direct typed-binding acceptance tests. */
async function typedPtcModeHarness(): Promise<Context> {
async function typedPtcModeHarness(mode: PtcMode): Promise<Context> {
const harness = new Context()
await mountAgentLoopTestDependencies(harness, { workingDirectory: true, tools: { mode: 'ptc' } })
await mountRuntime(harness)
await mountRuntime(harness, mode)
return harness
}
/** Keyless real-process harness with the task-owned bash lifecycle. */
async function backgroundPtcModeHarness(cwd: string): Promise<Context> {
const harness = await typedPtcModeHarness()
async function backgroundPtcModeHarness(mode: PtcMode, cwd: string): Promise<Context> {
const harness = await typedPtcModeHarness(mode)
await harness.plugin(LocalJobRegistry)
await harness.plugin(ToolJobs, {})
if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime)
@@ -154,12 +163,12 @@ async function backgroundPtcModeHarness(cwd: string): Promise<Context> {
return harness
}
describe('PTC mode typed values: keyless real-process contracts', () => {
describe.each(PTC_MODES)('PTC mode typed values ($mode): keyless real-process contracts', (mode) => {
it('returns formatted read content from inspect through the real outer run_code result', async () => {
workdir = await realpath(await mkdtemp(join(tmpdir(), 'dsh-ptc-inspect-read-')))
const path = join(workdir, 'a.txt')
await writeFile(path, 'alpha\nbeta\n')
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
await ctx.plugin(ToolFs)
const formatted = `<path>${path}</path>\n<type>file</type>\n<content>\n1: alpha\n2: beta\n\n(End of file - total 2 lines)\n</content>`
@@ -179,7 +188,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
})
it.each(['renderer', 'policy'])('keeps an empty %s output silent while preserving program data', async (source) => {
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
ctx.tools.register(defineTool({
name: 'silent_result', description: 'Return data without display text.', parameters: {},
output: {
@@ -200,7 +209,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
})
it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => {
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
ctx.tools.register(defineTool({
name: 'large_value',
description: 'Return a large canonical string.',
@@ -254,7 +263,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
it('returns a background job id, settles the outer run, and polls that id to completion', async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-background-'))
ctx = await backgroundPtcModeHarness(workdir)
ctx = await backgroundPtcModeHarness(mode, workdir)
const jobId = completion(await runCode(ctx, `
const started = await tools.bash({
@@ -277,7 +286,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
it('pre-abort spawns nothing; post-publication abort leaves job_kill as the cancellation owner', { timeout: 15_000, retry: 0 }, async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-task-cancel-'))
ctx = await backgroundPtcModeHarness(workdir)
ctx = await backgroundPtcModeHarness(mode, workdir)
const pre = new AbortController()
pre.abort('pre-aborted')
@@ -327,7 +336,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
it('keeps foreground bash coupled to the outer signal', async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-foreground-cancel-'))
ctx = await backgroundPtcModeHarness(workdir)
ctx = await backgroundPtcModeHarness(mode, workdir)
const controller = new AbortController()
const startedAt = Date.now()
const pending = runCode(ctx, `
@@ -341,7 +350,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
}, 15_000)
it('uses runtime inspection results directly through PTC', async () => {
ctx = await typedPtcModeHarness()
ctx = await typedPtcModeHarness(mode)
await ctx.plugin(CordisHostRunner)
await ctx.plugin(CordisInspectProviders)
await ctx.plugin(ToolCordis)
@@ -136,8 +136,7 @@ it.for(['standard', 'ptc'] as const)('compares the shipped %s tool sets and perm
expect(sdk.names).toContain('plugin_manager')
const optOut = await collect('sdk', mode, [{ id: 'tool-plugin-manager', disabled: true }])
expect(optOut.names).not.toContain('plugin_manager')
expect(() => { assertToolParity(mode, optOut.names, desktop.names) }).toThrow(
mode === 'ptc' ? 'Stale exceptions: sdk:plugin_manager' : 'Missing from SDK: plugin_manager')
expect(() => { assertToolParity(mode, optOut.names, desktop.names) }).toThrow('Missing from SDK: plugin_manager')
})
it.for(['standard', 'ptc'] as const)('detects missing shared tools in %s', async (mode, test) => {
@@ -18,8 +18,6 @@ export const toolParityExceptions: Record<ToolMode, readonly Exception[]> = {
ptc: [
{ tool: 'list_subagent_models', side: 'desktop',
reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' },
{ tool: 'plugin_manager', side: 'sdk',
reason: 'SDK PTC changes are persisted for restart without replacing active bindings because HMR is disabled; Desktop PTC excludes management in its HMR-enabled preset.' },
{ tool: 'workflow', side: 'sdk',
reason: 'The SDK PTC overlay changes only the executor so existing base workflow callers keep working; Desktop PTC uses run_code orchestration and omits the separate workflow surface.' },
],
@@ -23,7 +23,7 @@ it.each([
requests.push(JSON.parse(body) as Record<string, unknown>)
const tool = mode === 'ptc' ? {
type: 'tool_use', id: 'question-call', name: 'run_code', input: {
code: `return await tools.ask_user_question(${JSON.stringify({ questions })});`, description: 'Ask which output format to use',
code: `await tools.ask_user_question(${JSON.stringify({ questions })});`, description: 'Ask which output format to use',
},
} : { type: 'tool_use', id: 'question-call', name: 'ask_user_question', input: { questions } }
response.writeHead(200, { 'content-type': 'text/event-stream' })
+3
View File
@@ -723,6 +723,9 @@ describe('the shipped Web composition', () => {
const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? ''
expect(sdk).not.toContain('str_replace_editor')
expect(sdk).toContain('web_search')
// Like `standard`, PTC manages plugins when the Host provides an editable profile.
expect(toolNames(ctx, coded.agent)).toContain('plugin_manager')
expect(sdk).toContain('plugin_manager')
// The presentation is this agent's alone: the deployment default is
// native, and the session composed from `standard` still sees it.
+4 -4
View File
@@ -24,8 +24,8 @@
en: bb35a022c37955c9
zh: ab2ef22d398d83a0
/deepseek-harness-desktop/key-technical-decisions:
en: 3724c53da4f7647b
zh: 76ae549d43c99bb4
en: 19642526da04f108
zh: 506ea427d46bb38f
/deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies:
en: 764bdc09fa8f5701
zh: da7897e14434b43c
@@ -33,8 +33,8 @@
en: 372297005b57a08b
zh: 074a635ac17e4362
/deepseek-harness-desktop/installation-ownership:
en: 575d82acb5d61018
zh: b1064786f63863f7
en: 3d3b0e92079a4ef7
zh: 4ab572bf57f4c55c
/deepseek-harness-desktop/installation-ownership/runtime-and-plugin-activation:
en: 4951cd3ee659eb33
zh: 96bdd6358dad587a
+2 -2
View File
@@ -93,7 +93,7 @@ The original artwork lives in `resources/icon.png` and `resources/icon.svg`; pla
Shortcut overrides are stored in `app.getPath('userData')/keybindings.json`, separately from `DSH_HOME`. The main process validates and serializes changes before publishing accepted bindings. Failed reads retain the last accepted bindings and block edits, including Restore All; unreadable and future-version files remain unchanged. Development can isolate these preferences with `DSH_DESKTOP_USER_DATA_DIR`; the launcher prints its resolved path. See the [shortcut service](../../packages/client/shortcuts/README.md) for format and conflict semantics.
The macOS File menu displays the accepted single-key binding, including arrow keys, and routes Close Page or Window through the client page owner. On Windows and macOS, all complete accepted bindings are intercepted before main-document, embedded-frame, and browser-guest input, including editing and terminal input. Recording and input-method composition remain protected. Update overlays block product shortcuts and editing-key delivery to the parent window and its browser guests from creation until the last overlay closes. Every overlay opening or closing invalidates pending chord state. The main process shares one overlay owner between update dialogs and shortcut input through explicit creation and input-state capabilities. Two-key chords leave the first key’s initial press available to the page and do not intercept its release; complete chords and their repeats are consumed. The renderer leaves configurable binding dispatch to the native adapter. Chords have no native menu accelerator. Accepted commands are forwarded once through the trusted preload. Linux dispatches main-document shortcuts through the DOM and forwards accepted embedded-frame bindings to the client resolver. Closing the last window preserves macOS application lifetime; Windows exits the desktop instance and stops its tasks. The [close decision](../../.agents/notes/implemented/architecture/2026-09-21-desktop-page-close-shortcuts.md) records this lifecycle choice.
The application menu's **Settings…** command toggles Settings in the active workspace and displays the accepted single-key binding; it stays disabled before the workspace opens and during mandatory updates, and restores a hidden or minimized workspace window first. The macOS File menu displays the accepted single-key binding, including arrow keys, and routes Close Page or Window through the client page owner. On Windows and macOS, all complete accepted bindings are intercepted before main-document, embedded-frame, and browser-guest input, including editing and terminal input. Recording and input-method composition remain protected. Update overlays block product shortcuts and editing-key delivery to the parent window and its browser guests from creation until the last overlay closes. Every overlay opening or closing invalidates pending chord state. The main process shares one overlay owner between update dialogs and shortcut input through explicit creation and input-state capabilities. Two-key chords leave the first key’s initial press available to the page and do not intercept its release; complete chords and their repeats are consumed. The renderer leaves configurable binding dispatch to the native adapter. Chords have no native menu accelerator. Accepted commands are forwarded once through the trusted preload. Linux dispatches main-document shortcuts through the DOM and forwards accepted embedded-frame bindings to the client resolver. Closing the last window preserves macOS application lifetime; Windows exits the desktop instance and stops its tasks. The [close decision](../../.agents/notes/implemented/architecture/2026-09-21-desktop-page-close-shortcuts.md) records this lifecycle choice.
The macOS PNG uses an inset rounded background for legacy ICNS packaging, with representations up to 1024 pixels. It is a flattened icon, not an Icon Composer document. Apple's [app icon guidance](https://developer.apple.com/design/human-interface-guidelines/app-icons) describes unmasked layers for Icon Composer; those inputs require a separate macOS export and must not reuse the rounded ICNS artwork. Verify Finder and Dock appearance on supported macOS versions before release.
@@ -165,7 +165,7 @@ Electron chooses typed shell copy in the eight [shipped Client languages](../../
Windows and macOS relay native fullscreen transitions and the state after each page load to the renderer, so overlays can adapt their caption clearance.
Windows uses a 40-DIP caption with native window controls and colors synchronized from the application palette. Localized Application and Edit entries beside the sidebar toggle open native popup menus. They mount only after the application frame publishes its shell overlay seat, and remain absent during startup loading. Application provides Check for Updates and Exit; Edit provides undo, redo, cut, copy, paste, delete, and select all by sending the corresponding keys to the focused editor, independently of custom shortcut bindings. Plugin management uses the main application's Plugins page. No separate native menu row appears on Alt. Other platforms retain their native menus. Editable fields retain keyboard commands and a context menu without shortcut labels; Chromium supplies command availability, and selected read-only text offers Copy.
Windows uses a 40-DIP caption with native window controls and colors synchronized from the application palette. Localized Application and Edit entries beside the sidebar toggle open native popup menus. They mount only after the application frame publishes its shell overlay seat, and remain absent during startup loading. Application provides About, Settings, Check for Updates, Manage dsh Command, Developer tools, and Exit; Edit provides undo, redo, cut, copy, paste, delete, and select all by sending the corresponding keys to the focused editor, independently of custom shortcut bindings. Plugin management uses the main application's Plugins page. No separate native menu row appears on Alt. Other platforms retain their native menus. Editable fields retain keyboard commands and a context menu without shortcut labels; Chromium supplies command availability, and selected read-only text offers Copy.
On macOS the custom menu retains Electron's standard Window menu and application hide commands, including Minimize (⌘M) and Hide (⌘H). Its Edit menu copies Electron's, binds Paste and Match Style to ⇧⌘V, and keeps Electron's ⌥⇧⌘V as a hidden alias; the Substitutions and Speech titles come from the desktop locale, while the other items keep Electron's English labels. Linux keeps the application and Edit menus.
+2 -2
View File
@@ -93,7 +93,7 @@ Windows 在整个运行期间常驻托盘图标。悬停提示为产品名,单
快捷键覆盖保存在 `app.getPath('userData')/keybindings.json`,与 `DSH_HOME` 分离。主进程校验并串行保存修改后才发布已接受键位。读取失败保留上次接受的键位并阻止编辑,包括全部恢复;不可读和未来版本的文件保持不变。开发时可通过 `DSH_DESKTOP_USER_DATA_DIR` 隔离这些偏好,启动器会输出解析后的路径。格式和冲突语义见[快捷键服务](../../packages/client/shortcuts/README.zh.md)。
macOS“文件”菜单显示已接受的单键绑定(包括方向键),并通过 Client 页面 owner 路由“关闭页面或窗口”。Windows 和 macOS 在主文档、内嵌 frame 和浏览器 guest 输入之前拦截所有已接受的完整绑定,包括编辑和终端输入。录制和输入法组合状态仍受保护。更新蒙层从创建到最后一个蒙层关闭期间阻挡父窗口及其浏览器 guest 的产品快捷键和编辑按键递送。每次打开或关闭蒙层都会作废待完成的组合键状态。主进程通过显式的创建能力和输入状态读取能力,让更新对话框与快捷键输入共享同一个蒙层管理实例。双键组合会将首键的初次按下事件交给页面,且不拦截其松开事件;完整组合及其重复事件会被消费。渲染进程将可配置绑定的分发交给原生适配器。双键组合不注册原生菜单快捷键。已接受的命令通过可信 preload 转发一次。Linux 通过 DOM 分发主文档快捷键,并将已接受的内嵌 frame 绑定转发给 Client 解析器。关闭最后一个窗口后 macOS 保留应用生命周期;Windows 退出桌面实例并停止其任务。[关窗决策](../../.agents/notes/implemented/architecture/2026-09-21-desktop-page-close-shortcuts.zh.md)记录了这一生命周期选择。
应用菜单中的**设置…**在已打开的工作区中切换设置面板并显示已接受的单键绑定;工作区打开前和强制更新期间保持禁用,窗口隐藏或最小化时先恢复窗口。macOS“文件”菜单显示已接受的单键绑定(包括方向键),并通过 Client 页面 owner 路由“关闭页面或窗口”。Windows 和 macOS 在主文档、内嵌 frame 和浏览器 guest 输入之前拦截所有已接受的完整绑定,包括编辑和终端输入。录制和输入法组合状态仍受保护。更新蒙层从创建到最后一个蒙层关闭期间阻挡父窗口及其浏览器 guest 的产品快捷键和编辑按键递送。每次打开或关闭蒙层都会作废待完成的组合键状态。主进程通过显式的创建能力和输入状态读取能力,让更新对话框与快捷键输入共享同一个蒙层管理实例。双键组合会将首键的初次按下事件交给页面,且不拦截其松开事件;完整组合及其重复事件会被消费。渲染进程将可配置绑定的分发交给原生适配器。双键组合不注册原生菜单快捷键。已接受的命令通过可信 preload 转发一次。Linux 通过 DOM 分发主文档快捷键,并将已接受的内嵌 frame 绑定转发给 Client 解析器。关闭最后一个窗口后 macOS 保留应用生命周期;Windows 退出桌面实例并停止其任务。[关窗决策](../../.agents/notes/implemented/architecture/2026-09-21-desktop-page-close-shortcuts.zh.md)记录了这一生命周期选择。
macOS PNG 使用带留白的圆角底板,供传统 ICNS 打包使用,包含最高 1024 像素的表示。它是扁平图标,并非 Icon Composer 文档。Apple 的[应用图标指南](https://developer.apple.com/design/human-interface-guidelines/app-icons)要求向 Icon Composer 提供未遮罩的图层;这些输入需要在 macOS 上单独导出,不能复用已做圆角的 ICNS 图案。发布前须在支持的 macOS 版本中验收 Finder 和 Dock 的显示效果。
@@ -165,7 +165,7 @@ Electron 根据应用语言选择类型化的八种[内置 Client 语言](../../
Windows 和 macOS 会在原生全屏切换及每次页面加载后向渲染器同步全屏状态,让浮层调整顶栏避让距离。
Windows 使用 40 DIP 顶栏,保留原生窗口按钮,颜色随应用调色板同步。侧栏开关旁的本地化“应用”和“编辑”入口打开原生弹出菜单。仅当应用框架发布 shell overlay 席位后才挂载菜单,启动加载期间不显示。“应用”提供检查更新和退出;“编辑”向当前编辑器发送对应按键,提供撤销、重做、剪切、复制、粘贴、删除和全选,不受自定义快捷键绑定影响。插件管理使用主应用的“插件”页面。按 Alt 不会出现额外的原生菜单行。其他平台保留原生菜单。可编辑区域保留快捷键和不带快捷键标注的右键菜单;命令可用状态由 Chromium 提供,选中的只读文本提供“复制”命令。
Windows 使用 40 DIP 顶栏,保留原生窗口按钮,颜色随应用调色板同步。侧栏开关旁的本地化“应用”和“编辑”入口打开原生弹出菜单。仅当应用框架发布 shell overlay 席位后才挂载菜单,启动加载期间不显示。“应用”提供关于、设置、检查更新、管理 dsh 命令、开发者工具和退出;“编辑”向当前编辑器发送对应按键,提供撤销、重做、剪切、复制、粘贴、删除和全选,不受自定义快捷键绑定影响。插件管理使用主应用的“插件”页面。按 Alt 不会出现额外的原生菜单行。其他平台保留原生菜单。可编辑区域保留快捷键和不带快捷键标注的右键菜单;命令可用状态由 Chromium 提供,选中的只读文本提供“复制”命令。
macOS 上自定义菜单保留 Electron 的标准 Window 菜单及应用隐藏命令,包括 Minimize(⌘M)和 Hide(⌘H)。其 Edit 菜单复制 Electron 的默认菜单,把 Paste and Match Style 绑定到 ⇧⌘V,并保留 Electron 默认的 ⌥⇧⌘V 作为隐藏别名;Substitutions 和 Speech 标题取自桌面端语言包,其余条目保留 Electron 的英文标签。Linux 保留应用菜单和 Edit 菜单。
+54 -12
View File
@@ -11,7 +11,7 @@ import { DESKTOP_IPC, assertDesktopSender } from './ipc.ts'
* @param getWindow - current product window.
* @param userData - Electron-resolved device preference directory.
* @param platform - local device platform.
* @param updateMenu - rebuild the application menu when the close accelerator or availability changes.
* @param updateMenu - rebuild the application menu when a menu shortcut accelerator or availability changes.
* @param overlayInput - Current shell-owned input blocking state for the product window.
* @returns menu construction, editor key delivery, window attachment, and teardown operations.
*/
@@ -20,6 +20,7 @@ export function installDesktopShortcuts(
overlayInput: (window: BrowserWindow) => { readonly revision: number; readonly blocked: boolean },
): {
fileMenu(labels: { fileMenu: string; closePage: string }): MenuItemConstructorOptions
settingsMenuItem(label: string, available?: boolean, focusWindow?: () => void): MenuItemConstructorOptions
/**
* Send a native Edit action to the editor without matching user shortcuts.
* @param keyCode - edit key.
@@ -41,12 +42,14 @@ export function installDesktopShortcuts(
let recording = false
let revision: ShortcutRevision | undefined
let closeBinding: NormalizedBinding | null = null
let settingsBinding: NormalizedBinding | null = null
let settingsEnabled = false
let editingInput: BrowserWindow['webContents'] | undefined
const scopedDesktop = platform === 'windows' || platform === 'macos'
const disposers = new Set<() => void>()
const guestInputs = new Map<WebContents, { window: BrowserWindow; reset(): void }>()
const closeAccelerator = (): string | undefined => presentBinding(closeBinding, platform).aria
?.replace('Meta+', 'Command+').replace(/Arrow(Up|Down|Left|Right)$/u, '$1')
const menuAccelerator = (binding: NormalizedBinding | null): string | undefined => presentBinding(binding, platform).aria
?.replace('Meta+', platform === 'macos' ? 'Command+' : 'Super+').replace(/Arrow(Up|Down|Left|Right)$/u, '$1')
const sendMenuClose = (): void => {
const window = getWindow()
if (window === undefined || window.isDestroyed() || !window.isFocused() || !window.isEnabled()
@@ -55,15 +58,25 @@ export function installDesktopShortcuts(
}
let keys = new Set<string>()
const publish = (snapshot: ShortcutConfigSnapshot): void => {
const wasEnabled = revision !== undefined
const previousAccelerator = closeAccelerator()
const wasCloseEnabled = revision !== undefined
const wasSettingsEnabled = settingsEnabled
const previousClose = menuAccelerator(closeBinding)
const previousSettings = menuAccelerator(settingsBinding)
revision = definitions.length === 0 || snapshot.status === 'loading' ? undefined : snapshot.revision
settingsEnabled = revision !== undefined && definitions.some(entry => entry.id === 'settings.open')
const rows = snapshot.status === 'loading' ? [] : effectiveShortcuts(definitions, snapshot.document, 'desktop', platform)
keys = new Set(rows.flatMap(row => row.binding !== null && row.issue === null && row.conflicts.length === 0
? [bindingKey(row.binding)] : []))
const close = rows.find(row => row.id === 'page.close')
closeBinding = close?.issue === null && close.conflicts.length === 0 ? close.binding : null
if (wasEnabled !== (revision !== undefined) || previousAccelerator !== closeAccelerator()) updateMenu()
const activeBinding = (id: string): NormalizedBinding | null => {
const row = rows.find(entry => entry.id === id)
return row?.issue === null && row.conflicts.length === 0 ? row.binding : null
}
closeBinding = activeBinding('page.close')
settingsBinding = activeBinding('settings.open')
if (wasCloseEnabled !== (revision !== undefined)
|| wasSettingsEnabled !== settingsEnabled
|| previousClose !== menuAccelerator(closeBinding)
|| previousSettings !== menuAccelerator(settingsBinding)) updateMenu()
const window = getWindow()
if (window !== undefined && !window.isDestroyed() && window.webContents.mainFrame.url.startsWith('dsh-app://app/')) {
window.webContents.send(DESKTOP_IPC.shortcutsChanged, snapshot)
@@ -119,7 +132,7 @@ export function installDesktopShortcuts(
const clear = (): void => {
resetInput()
if (guestName !== undefined) return
definitions = []; keys.clear(); recording = false
definitions = []; keys.clear(); recording = false; settingsEnabled = false
persistence.setDefinitions(null)
}
const navigation = (event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>): void => {
@@ -146,8 +159,16 @@ export function installDesktopShortcuts(
const modifiers = (['control', 'alt', 'shift', 'meta'] as const).filter(modifier => input[modifier])
const key = bindingKey({ code: input.code, modifiers })
const match = keys.has(key)
const menuMatch = closeBinding !== null && closeBinding.secondCode === undefined && modifiers.join('+') === closeBinding.modifiers.join('+')
&& input.key.toUpperCase() === (closeBinding.code.startsWith('Key') ? closeBinding.code.slice(3) : input.code === closeBinding.code ? input.key.toUpperCase() : '')
const matchesMenuKey = (binding: NormalizedBinding | null): boolean => {
if (binding === null || binding.secondCode !== undefined || modifiers.join('+') !== binding.modifiers.join('+')) return false
if (binding.code.startsWith('Key')) return input.key.toUpperCase() === binding.code.slice(3)
if (binding.code.startsWith('Digit')) return input.key === binding.code.slice(5)
const acceleratorKey = menuAccelerator(binding)?.split('+').at(-1)
return acceleratorKey !== undefined && acceleratorKey.length === 1
? input.key.toUpperCase() === acceleratorKey.toUpperCase()
: input.code === binding.code
}
const menuMatch = matchesMenuKey(closeBinding) || matchesMenuKey(settingsBinding)
contents.setIgnoreMenuShortcuts(recording || match || menuMatch)
const frame = contents.focusedFrame
const composing = input.isComposing || input.key === 'Dead' || deadKey || input.modifiers.includes('altgr')
@@ -240,13 +261,34 @@ export function installDesktopShortcuts(
}
},
fileMenu: (labels) => {
const accelerator = closeAccelerator()
const accelerator = menuAccelerator(closeBinding)
return { label: labels.fileMenu, submenu: [{
id: 'dsh-page-close', label: labels.closePage, enabled: revision !== undefined,
...accelerator === undefined ? {} : { accelerator },
click: sendMenuClose,
}] }
},
settingsMenuItem(label, available = true, focusWindow) {
const accelerator = menuAccelerator(settingsBinding)
return {
id: 'dsh-settings-open',
label,
enabled: available && settingsEnabled,
...accelerator === undefined ? {} : { accelerator },
click: () => {
if (!available || !settingsEnabled || revision === undefined || recording) return
const current = getWindow()
if (current === undefined || current.isDestroyed() || !current.isEnabled() || overlayInput(current).blocked) return
focusWindow?.()
const window = getWindow()
if (window === undefined || window.isDestroyed() || (focusWindow === undefined && !window.isFocused()) || !window.isEnabled()
|| overlayInput(window).blocked) return
window.webContents.send(DESKTOP_IPC.shortcutsInput, {
kind: 'menu', commandId: 'settings.open', revision,
})
},
}
},
attach(window) { attachInput(window, window.webContents) },
attachGuest: attachInput,
dispose() {
+8
View File
@@ -32,6 +32,7 @@ export const en = {
fileMenu: 'File',
closePage: 'Close Page or Window',
aboutMenu: 'About DeepSeek Harness',
settingsMenu: 'Settings…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: 'Version V{version}',
hideApplication: 'Hide DeepSeek Harness',
@@ -227,6 +228,7 @@ export const zh = {
fileMenu: '文件',
closePage: '关闭页面或窗口',
aboutMenu: '关于 DeepSeek Harness',
settingsMenu: '设置…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: '版本 V{version}',
hideApplication: '隐藏 DeepSeek Harness',
@@ -420,6 +422,7 @@ export const ja = {
fileMenu: 'ファイル',
closePage: 'ページまたはウィンドウを閉じる',
aboutMenu: 'DeepSeek Harness について',
settingsMenu: '設定…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: 'バージョン V{version}',
hideApplication: 'DeepSeek Harness を隠す',
@@ -613,6 +616,7 @@ export const es = {
fileMenu: 'Archivo',
closePage: 'Cerrar página o ventana',
aboutMenu: 'Acerca de DeepSeek Harness',
settingsMenu: 'Configuración…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: 'Versión V{version}',
hideApplication: 'Ocultar DeepSeek Harness',
@@ -806,6 +810,7 @@ export const fr = {
fileMenu: 'Fichier',
closePage: 'Fermer la page ou la fenêtre',
aboutMenu: 'À propos de DeepSeek Harness',
settingsMenu: 'Paramètres…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: 'VersionV{version}',
hideApplication: 'Masquer DeepSeek Harness',
@@ -999,6 +1004,7 @@ export const de = {
fileMenu: 'Datei',
closePage: 'Seite oder Fenster schließen',
aboutMenu: 'Über DeepSeek Harness',
settingsMenu: 'Einstellungen…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: 'Version V{version}',
hideApplication: 'DeepSeek Harness ausblenden',
@@ -1192,6 +1198,7 @@ export const ru = {
fileMenu: 'Файл',
closePage: 'Закрыть страницу или окно',
aboutMenu: 'О DeepSeek Harness',
settingsMenu: 'Настройки…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: 'Версия V{version}',
hideApplication: 'Скрыть DeepSeek Harness',
@@ -1385,6 +1392,7 @@ export const pt = {
fileMenu: 'Arquivo',
closePage: 'Fechar página ou janela',
aboutMenu: 'Sobre DeepSeek Harness',
settingsMenu: 'Configurações…',
aboutProduct: 'DeepSeek Harness',
aboutVersion: 'Versão V{version}',
hideApplication: 'Ocultar DeepSeek Harness',
+17 -3
View File
@@ -573,7 +573,10 @@ async function main(): Promise<void> {
if (previousAccountStatus === 'credential-stored' && state.status === 'signed-out') {
void readWelcomeState().then(async (value) => {
if (needsWelcome(value) && !quitting) {
enteredWorkspace = false
if (enteredWorkspace) {
enteredWorkspace = false
refreshApplicationMenu()
}
await showWelcome()
if (welcomeWindow !== undefined && !welcomeWindow.isDestroyed()) welcomeWindow.webContents.send(WELCOME_IPC.state, state)
}
@@ -587,7 +590,10 @@ async function main(): Promise<void> {
void readWelcomeState().then(async (value) => {
if (!needsWelcome(value) || quitting) return
pendingWelcomeNotice = 'session-expired'
enteredWorkspace = false
if (enteredWorkspace) {
enteredWorkspace = false
refreshApplicationMenu()
}
await showWelcome()
const state = await accountBackend.state()
if (welcomeWindow !== undefined && !welcomeWindow.isDestroyed()) welcomeWindow.webContents.send(WELCOME_IPC.state, state)
@@ -1208,6 +1214,9 @@ async function main(): Promise<void> {
click: () => { void showAbout().catch((error: unknown) => { console.error(error) }) } }
: { label: currentDesktopLocale().messages.aboutMenu, role: 'about' },
{ type: 'separator' },
shortcuts.settingsMenuItem(currentDesktopLocale().messages.settingsMenu,
enteredWorkspace && !isMandatory(), () => { focusPrimaryWindow() }),
{ type: 'separator' },
{ label: currentDesktopLocale().messages.checkUpdatesMenu, click: () => { void openUpdatePrompt(true) } },
...process.platform === 'darwin' || process.platform === 'win32'
? [{ label: currentDesktopLocale().messages.cliCommandMenu, click: () => { void commandManager.show() } }] : [],
@@ -1375,7 +1384,9 @@ async function main(): Promise<void> {
if (process.platform === 'win32') window.setBackgroundColor(chromeFallbackFill())
if (activate) window.show()
else window.showInactive()
const wasInWorkspace = enteredWorkspace
enteredWorkspace = true
if (!wasInWorkspace) refreshApplicationMenu()
if (welcomeWindow !== undefined) {
welcomeWindow.close()
window.webContents.send(DESKTOP_IPC.enterWorkspace)
@@ -1572,7 +1583,10 @@ async function main(): Promise<void> {
}
mandatoryUI?.sync()
if (state.blocking && !wasBlocking) void updateSchedule.check(false, true).catch((error: unknown) => { console.error(error) })
wasBlocking = state.blocking
if (state.blocking !== wasBlocking) {
wasBlocking = state.blocking
refreshApplicationMenu()
}
}, policyAuth?.request, () => desktopClientMetadata(locale.id))
const policy = mandatoryPolicy
mandatoryUI = new DesktopMandatoryUpdateWindow({
@@ -6,6 +6,14 @@
{
"type": "separator"
},
{
"id": "dsh-settings-open",
"label": "Settings…",
"enabled": false
},
{
"type": "separator"
},
{
"label": "Check for Updates…"
},
@@ -6,6 +6,14 @@
{
"type": "separator"
},
{
"id": "dsh-settings-open",
"label": "设置…",
"enabled": false
},
{
"type": "separator"
},
{
"label": "检查更新…"
},
+97
View File
@@ -828,3 +828,100 @@ it('delivers Windows Edit actions to the focused browser guest without invoking
f.keyboard.sendEditingKey('C', ['control'])
expect(f.contents.sendInputEvent).toHaveBeenCalledTimes(2)
})
it.each([
['macos', 'Command+,'],
['windows', 'Control+,'],
['linux', 'Control+,'],
] as const)('builds and updates %s Settings menu availability, accelerator, and guards', async (platform, expectedAccelerator) => {
const f = await fixture(platform)
const initialMenu = f.keyboard.settingsMenuItem('Settings…')
expect(initialMenu).toMatchObject({ id: 'dsh-settings-open', label: 'Settings…', enabled: false })
expect(initialMenu).not.toHaveProperty('accelerator')
await f.call<ShortcutConfigSnapshot>(DESKTOP_IPC.shortcutsGet, f.definitions)
expect(f.updateMenu).toHaveBeenCalledOnce()
expect(f.keyboard.settingsMenuItem('Settings…').enabled).toBe(false)
const settingsDefinition: ShortcutDefinition = {
id: 'settings.open' as ShortcutCommandId,
defaults: desktopDefaults({ code: 'Comma', modifiers: ['primary'] }),
}
const initial = await f.call<ShortcutConfigSnapshot>(DESKTOP_IPC.shortcutsGet, [...f.definitions, settingsDefinition])
expect(f.updateMenu).toHaveBeenCalledTimes(2)
expect(f.keyboard.settingsMenuItem('Settings…')).toMatchObject({
id: 'dsh-settings-open', label: 'Settings…', enabled: true, accelerator: expectedAccelerator,
})
const meta = platform === 'macos'
f.contents.emit('before-input-event', { preventDefault: vi.fn() }, {
type: 'keyDown', code: 'KeyW', key: ',', modifiers: [meta ? 'meta' : 'control'],
meta, control: !meta, alt: false, shift: false, isAutoRepeat: false, isComposing: false,
})
expect(f.contents.setIgnoreMenuShortcuts).toHaveBeenLastCalledWith(true)
let currentRevision = initial.revision
if (platform === 'windows') {
const metaSaved = await f.call<ShortcutSaveResult>(DESKTOP_IPC.shortcutsEdit,
{ type: 'set', id: 'settings.open', binding: { code: 'Comma', modifiers: ['meta'] } }, currentRevision)
expect(metaSaved.status).toBe('saved')
currentRevision = metaSaved.snapshot.revision
expect(f.keyboard.settingsMenuItem('Settings…').accelerator).toBe('Super+,')
}
const unbound = await f.call<ShortcutSaveResult>(DESKTOP_IPC.shortcutsEdit,
{ type: 'set', id: 'settings.open', binding: null }, currentRevision)
expect(unbound.status).toBe('saved')
expect(f.updateMenu).toHaveBeenCalledTimes(platform === 'windows' ? 4 : 3)
const unboundMenu = f.keyboard.settingsMenuItem('Settings…')
expect(unboundMenu).toMatchObject({ enabled: true })
expect(unboundMenu).not.toHaveProperty('accelerator')
let activeRevision = unbound.snapshot.revision
if (platform !== 'linux') {
const chorded = await f.call<ShortcutSaveResult>(DESKTOP_IPC.shortcutsEdit,
{ type: 'set', id: 'settings.open', binding: { code: 'KeyG', secondCode: 'KeyS', modifiers: [] } }, activeRevision)
expect(chorded.status).toBe('saved')
activeRevision = chorded.snapshot.revision
const chordedMenu = f.keyboard.settingsMenuItem('Settings…')
expect(chordedMenu).toMatchObject({ enabled: true })
expect(chordedMenu).not.toHaveProperty('accelerator')
}
const focusWindow = vi.fn()
f.window.isFocused.mockReturnValue(false)
f.contents.send.mockClear()
;(f.keyboard.settingsMenuItem('Settings…').click as () => void)()
expect(f.contents.send).not.toHaveBeenCalled()
;(f.keyboard.settingsMenuItem('Settings…', false, focusWindow).click as () => void)()
expect(focusWindow).not.toHaveBeenCalled()
expect(f.contents.send).not.toHaveBeenCalled()
;(f.keyboard.settingsMenuItem('Settings…', true, focusWindow).click as () => void)()
expect(focusWindow).toHaveBeenCalledOnce()
expect(f.contents.send).toHaveBeenCalledExactlyOnceWith(DESKTOP_IPC.shortcutsInput, {
kind: 'menu', commandId: 'settings.open', revision: activeRevision,
})
await f.call(DESKTOP_IPC.shortcutsRecording, true)
focusWindow.mockClear(); f.contents.send.mockClear()
;(f.keyboard.settingsMenuItem('Settings…', true, focusWindow).click as () => void)()
expect(focusWindow).not.toHaveBeenCalled()
expect(f.contents.send).not.toHaveBeenCalled()
await f.call(DESKTOP_IPC.shortcutsRecording, false)
f.window.isEnabled.mockReturnValue(false)
;(f.keyboard.settingsMenuItem('Settings…', true, focusWindow).click as () => void)()
expect(focusWindow).not.toHaveBeenCalled()
expect(f.contents.send).not.toHaveBeenCalled()
f.window.isEnabled.mockReturnValue(true)
const overlay = updateOverlayFixture(f)()
;(f.keyboard.settingsMenuItem('Settings…', true, focusWindow).click as () => void)()
expect(focusWindow).not.toHaveBeenCalled()
expect(f.contents.send).not.toHaveBeenCalled()
overlay.destroy()
await f.call<ShortcutConfigSnapshot>(DESKTOP_IPC.shortcutsGet, f.definitions)
expect(f.keyboard.settingsMenuItem('Settings…').enabled).toBe(false)
})
+80 -7
View File
@@ -9,6 +9,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync,
import { tmpdir } from 'node:os'
import type { MenuItemConstructorOptions, MessageBoxOptions } from 'electron'
import { DESKTOP_IPC, type DesktopUpdateState } from '../src/ipc.ts'
import { WELCOME_IPC } from '../src/welcome-api.ts'
import { MANDATORY_IPC } from '../src/mandatory-update-ipc.ts'
import { DesktopHostFatalError, DesktopHostUncleanExitError } from '../src/host-process.ts'
import { en, zh } from '../src/locale.ts'
@@ -122,7 +123,11 @@ const harness = await vi.hoisted(async () => {
isMinimized() { return this.minimized }
visible = true
isVisible() { return this.visible }
isFocused() { return true }
enabled = true
isEnabled() { return this.enabled }
focused = true
isFocused() { return this.focused }
async loadFile() {}
async loadURL(url: string) {
this.urls.push(url)
this.webContents.mainFrame.url = url
@@ -447,8 +452,9 @@ function invoke(channel: string, origin = channel === DESKTOP_IPC.boot ? 'app' :
}
function applicationMenuItems(): MenuItemConstructorOptions[] {
const native = harness.menu.mock.calls[0]?.[0][0]?.submenu
if (Array.isArray(native)) return native
const native = [...harness.menu.mock.calls].reverse().map(call => call[0][0]?.submenu)
.find((submenu): submenu is MenuItemConstructorOptions[] => Array.isArray(submenu))
if (native !== undefined) return native
const sender = harness.windows[0]!.webContents
void harness.handlers.get(DESKTOP_IPC.windowsMenu)!({ sender, senderFrame: sender.mainFrame }, 'application', 0, 0)
return harness.menu.mock.lastCall![0]
@@ -821,7 +827,7 @@ describe('desktop main startup', () => {
const menu = applicationMenuItems()
const visible = menu.filter(item => item.visible !== false)
expect(visible.map(item => item.role === 'quit' ? 'quit' : item.label ?? item.type)).toEqual([
messages.aboutMenu, 'separator', messages.checkUpdatesMenu,
messages.aboutMenu, 'separator', messages.settingsMenu, 'separator', messages.checkUpdatesMenu,
...platform === 'linux' ? [] : [messages.cliCommandMenu],
'separator', ...packaged ? [] : [messages.reloadPageMenu, messages.restartAppHostMenu],
messages.toggleDevToolsMenu, 'separator',
@@ -1391,7 +1397,7 @@ describe('desktop main startup', () => {
expect(() => handler(event, 'application', NaN, 34)).toThrow('invalid popup request')
const application = handler(event, 'application', 48, 34)
expect(harness.menu.buildFromTemplate.mock.lastCall![0].map(item => item.label ?? item.type)).toEqual([
'关于 DeepSeek Harness', 'separator', '检查更新…', '管理 dsh 命令…', 'separator', zh.toggleDevToolsMenu, 'separator', '退出',
'关于 DeepSeek Harness', 'separator', '设置…', 'separator', '检查更新…', '管理 dsh 命令…', 'separator', zh.toggleDevToolsMenu, 'separator', '退出',
])
expect(harness.popup.mock.lastCall![0]).toMatchObject({ window, x: 48, y: 34 })
expect(harness.popup.mock.lastCall![0].callback).toBeTypeOf('function')
@@ -1439,8 +1445,8 @@ describe('desktop main startup', () => {
: undefined)
const application = template[0]!.submenu as MenuItemConstructorOptions[]
expect(application.filter(item => item.visible !== false).map(describeItem)).toEqual(platform === 'darwin'
? ['about', 'separator', en.checkUpdatesMenu, en.cliCommandMenu, 'separator', 'toggleDevTools', 'separator', 'hide', 'hideOthers', 'unhide', 'separator', 'quit']
: ['about', 'separator', en.checkUpdatesMenu, 'separator', 'toggleDevTools', 'separator', 'quit'])
? ['about', 'separator', en.settingsMenu, 'separator', en.checkUpdatesMenu, en.cliCommandMenu, 'separator', 'toggleDevTools', 'separator', 'hide', 'hideOthers', 'unhide', 'separator', 'quit']
: ['about', 'separator', en.settingsMenu, 'separator', en.checkUpdatesMenu, 'separator', 'toggleDevTools', 'separator', 'quit'])
expect(harness.menu.setApplicationMenu).toHaveBeenCalledOnce()
})
@@ -1460,6 +1466,73 @@ describe('desktop main startup', () => {
} finally { harness.app.name = originalName }
})
it.each([
['darwin', 'Command+,'],
['win32', 'Control+,'],
] as const)('gates Settings menu availability across welcome, workspace, window restore, sign-out, and mandatory updates (%s)', async (platform, expectedAccelerator) => {
vi.spyOn(process, 'platform', 'get').mockReturnValue(platform)
harness.embeddedPolicy = { origin: 'https://policy.example.com', allowedPageOrigins: ['https://downloads.example.com'] }
const policyFetch = vi.fn<typeof fetch>()
.mockImplementation(async () => Response.json({ code: 0, data: { biz_code: 0, biz_data: null } }))
vi.stubGlobal('fetch', policyFetch)
await import('../src/main.ts')
await harness.preparing.promise
harness.prepared.resolve()
await harness.hostStarted.promise
const host = harness.hosts[0]!
host.fetch.mockResolvedValueOnce(Response.json({ loggedIn: false, hasApiKey: false, writable: true, localePreference: null, themePreference: 'system' }))
host.ready.resolve()
await vi.waitFor(() => { expect(harness.windows).toHaveLength(2) })
const mainWindow = harness.windows[0]!
const welcomeWindow = harness.windows[1]!
const registered = await Promise.resolve(invoke(DESKTOP_IPC.shortcutsGet, 'app', [
{ id: 'settings.open', defaults: { 'desktop:macos': { code: 'Comma', modifiers: ['primary'] }, 'desktop:windows': { code: 'Comma', modifiers: ['primary'] } } },
])) as { revision: string }
const settingsItem = () => applicationMenuItems().find(item => item.id === 'dsh-settings-open')!
expect(settingsItem()).toMatchObject({ label: en.settingsMenu, enabled: false, accelerator: expectedAccelerator })
mainWindow.show.mockClear()
mainWindow.webContents.send.mockClear()
;(settingsItem().click as () => void)()
expect(mainWindow.show).not.toHaveBeenCalled()
expect(mainWindow.webContents.send).not.toHaveBeenCalled()
await harness.handlers.get(WELCOME_IPC.skip)!({ sender: welcomeWindow.webContents, senderFrame: welcomeWindow.webContents.mainFrame })
expect(settingsItem()).toMatchObject({ label: en.settingsMenu, enabled: true, accelerator: expectedAccelerator })
mainWindow.minimized = true
mainWindow.visible = false
mainWindow.focused = false
mainWindow.restore.mockClear()
mainWindow.show.mockClear()
mainWindow.focus.mockClear().mockImplementationOnce(() => { mainWindow.focused = true })
mainWindow.webContents.send.mockClear()
;(settingsItem().click as () => void)()
expect(mainWindow.restore).toHaveBeenCalledOnce()
expect(mainWindow.show).toHaveBeenCalledOnce()
expect(mainWindow.focus).toHaveBeenCalledOnce()
expect(mainWindow.webContents.send).toHaveBeenCalledWith(DESKTOP_IPC.shortcutsInput, {
kind: 'menu', commandId: 'settings.open', revision: registered.revision,
})
host.fetch.mockResolvedValueOnce(Response.json({ loggedIn: false, hasApiKey: false }))
harness.publishAccount({ status: 'credential-stored', attempt: null, links: { usageUrl: '', topUpUrl: '' } })
harness.publishAccount({ status: 'signed-out', attempt: null, links: { usageUrl: '', topUpUrl: '' } })
await vi.waitFor(() => { expect(settingsItem().enabled).toBe(false) })
expect(harness.windows.length).toBeGreaterThanOrEqual(3)
const reopenedWelcome = harness.windows[2]!
await harness.handlers.get(WELCOME_IPC.skip)!({
sender: reopenedWelcome.webContents, senderFrame: reopenedWelcome.webContents.mainFrame,
})
expect(settingsItem().enabled).toBe(true)
policyFetch.mockResolvedValueOnce(Response.json({ code: 40005,
data: { show_content: { title: 'Update', detail: 'Required' }, desktop_app_link: 'https://downloads.example.com/' } }))
await invoke(DESKTOP_IPC.updatesOpen, 'app')
await harness.policyBlocked.promise
expect(settingsItem().enabled).toBe(false)
})
it.each(['http:', 'https:'] as const)('passes the %s Host cookie explicitly and attaches socket credentials only to the owned application origin and window', async (protocol) => {
await import('../src/main.ts')
await harness.preparing.promise
+2 -2
View File
@@ -40,7 +40,7 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
const runtimeId = () => [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')?.fiber?.uid
const beforeRuntime = runtimeId()
expect(beforeRuntime).toBeTypeOf('number')
expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body')
expect(scaffold.ctx.ptcRuntime.programFormat).toBe('scoped-repl')
const names = [name]
await page.locator('[data-plugin-panel]').getByRole('button', { name: '更多', exact: true }).click()
const cua = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]')
@@ -58,6 +58,6 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
}
expect(await readFile(manifest, 'utf8')).toBe(before)
expect(runtimeId()).toBe(beforeRuntime)
expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body')
expect(scaffold.ctx.ptcRuntime.programFormat).toBe('scoped-repl')
expect(scaffold.ctx.get('computerUse')).toBeUndefined()
})
+116
View File
@@ -0,0 +1,116 @@
/** Composer ArrowUp/ArrowDown recall of loaded prompts in the shipped Web composition. */
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { chromium, type Browser, type Page } from 'playwright'
import { afterAll, beforeAll, expect, it, onTestFailed } from 'vitest'
import type { StreamChunk } from '@deepseek-ai/dsh-llm'
import type { ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
import { launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
const PROMPTS = ['First history prompt', 'Second history prompt\nwith a second line'] as const
function reply(text: string): StreamChunk[] {
return [
{ type: 'block-start', index: 0, blockType: 'text' },
{ type: 'text-delta', index: 0, text },
{ type: 'block-end', index: 0, block: { type: 'text', text } },
{ type: 'usage', usage: { inputTokens: 16, outputTokens: 4 } },
{ type: 'finish', reason: { kind: 'stop' } },
]
}
let browser: Browser
let page: Page
let replayDir: string
let scaffold: WebScaffold
beforeAll(async () => {
replayDir = await mkdtemp(join(tmpdir(), 'dsh-composer-history-'))
const replayOverride = join(replayDir, 'replay.override.json')
const doc: ReplayOverrideDoc = PROMPTS.map((_, index) => ({ kind: 'chunks', chunks: reply(`Reply ${String(index + 1)}`) }))
await writeFile(replayOverride, JSON.stringify(doc))
scaffold = await launchWebScaffold({ replayFixture: join(replayDir, 'override-only.jsonl'), replayOverride })
browser = await chromium.launch()
page = await newEnglishPage(browser, 800)
watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await connectFreshWorkspace(page, scaffold.workspaceCwd, 'composer-history-e2e')
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
if (replayDir !== undefined) await rm(replayDir, { recursive: true, force: true })
})
it.skipIf(webSnapshotMode() === 'record')('recalls loaded prompts with the arrow keys from an empty draft, also after a reload', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-history'))
const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
await composer.waitFor({ timeout: 15_000 })
for (const [index, prompt] of PROMPTS.entries()) {
const settled = scaffold.whenTurnSettled(30_000)
await composer.fill(prompt)
await composer.press('Enter')
await page.getByText(`Reply ${String(index + 1)}`, { exact: true }).waitFor({ timeout: 15_000 })
await settled
await expect.poll(() => composer.textContent(), { timeout: 10_000 }).toBe('')
}
// The editor document's plain text: paragraphs and line-break nodes both end a line.
const draft = () => composer.evaluate((element) => {
interface Node { type: string; text?: string; children?: Node[] }
const editor = (element as HTMLElement & { __lexicalEditor: { getEditorState(): { toJSON(): { root: Node } } } }).__lexicalEditor
const line = (node: Node): string => node.type === 'linebreak' ? '\n' : node.text ?? (node.children ?? []).map(line).join('')
return (editor.getEditorState().toJSON().root.children ?? []).map(line).join('\n')
})
// Typed text is never displaced: ArrowUp only moves the caret.
await composer.pressSequentially('unsent')
await composer.press('ArrowUp')
expect(await draft()).toBe('unsent')
await composer.press('ControlOrMeta+a')
await composer.press('Backspace')
await expect.poll(draft).toBe('')
// From an empty draft the arrows walk the history with the caret at the draft end.
await composer.press('ArrowUp')
await expect.poll(draft).toBe(PROMPTS[1])
await composer.press('ArrowUp')
await expect.poll(draft).toBe(PROMPTS[0])
// Past the oldest entry the native arrow moves the caret to the line start,
// so the next ArrowDown returns it to the end before recalling again.
await composer.press('ArrowUp')
expect(await draft()).toBe(PROMPTS[0])
await composer.press('ArrowDown')
expect(await draft()).toBe(PROMPTS[0])
await composer.press('ArrowDown')
await expect.poll(draft).toBe(PROMPTS[1])
// Away from the draft end the arrows move the caret inside the two-line entry.
await composer.press('ArrowLeft')
await composer.press('ArrowUp')
await composer.press('ArrowDown')
expect(await draft()).toBe(PROMPTS[1])
await composer.press('End')
await composer.press('ArrowUp')
await expect.poll(draft).toBe(PROMPTS[0])
await composer.press('ArrowDown')
await expect.poll(draft).toBe(PROMPTS[1])
await composer.press('ArrowDown')
await expect.poll(draft).toBe('')
// Recall reads the loaded Session history, so it survives a page reload.
await page.reload({ waitUntil: 'load' })
const reloaded = page.locator('[data-composer-input][contenteditable="true"]').last()
await reloaded.waitFor({ timeout: 15_000 })
await page.getByText('Reply 2', { exact: true }).waitFor({ timeout: 15_000 })
await reloaded.click()
await reloaded.press('ArrowUp')
await expect.poll(() => reloaded.evaluate((element) => {
interface Node { type: string; text?: string; children?: Node[] }
const editor = (element as HTMLElement & { __lexicalEditor: { getEditorState(): { toJSON(): { root: Node } } } }).__lexicalEditor
const line = (node: Node): string => node.type === 'linebreak' ? '\n' : node.text ?? (node.children ?? []).map(line).join('')
return (editor.getEditorState().toJSON().root.children ?? []).map(line).join('\n')
})).toBe(PROMPTS[1])
})
@@ -0,0 +1,60 @@
/** Client inspection replies preserve child Session ownership through the shipped Web RPC path. */
import { chromium } from 'playwright'
import { expect, it } from 'vitest'
import { Peer } from '@deepseek-ai/dsh-client-connection'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { SessionId } from '@deepseek-ai/dsh-session'
import { launchWebScaffold } from './scaffold.ts'
import { newEnglishPage } from './support.ts'
declare module '@deepseek-ai/dsh-typert-protocol' {
interface PrincipalMap {
/** Test page permitted to use global RPCs but no Session. */
'inspect-test-page': { readonly kind: 'inspect-test-page' }
}
}
it('answers Client queries for subagents without adopting their Session as an ordinary Agent', async () => {
const scaffold = await launchWebScaffold()
try {
const browser = await chromium.launch()
try {
const page = await newEnglishPage(browser)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
await expect.poll(() => scaffold.ctx.cordisInspect.list().some(provider => provider.platform === 'client')).toBe(true)
const child = await scaffold.ctx.agents.create({
sessionId: brandString<SessionId>('inspect-child'),
meta: { origin: 'subagent', parentSession: brandString<SessionId>('inspect-parent') },
})
try {
expect(await scaffold.ctx.sessionController.resolveAgent(child.agent.id)).toMatchObject({ error: { code: 'session/agent-busy' } })
const result = await scaffold.ctx.cordisInspect.query('client', 'Service', 'listService', undefined, child.agent, new AbortController().signal)
expect(result).toHaveProperty('mode', 'catalog')
expect(result).toHaveProperty('services', expect.arrayContaining([expect.objectContaining({ key: 'layout' })]))
const peer = new Peer(scaffold.ctx, { principal: { kind: 'inspect-test-page' } })
const unregister = scaffold.ctx.remoteAccess.registerPolicy('inspect-test-page', { bindings: () => [{
role: { name: 'inspect-global', resource: 'global', actions: ['dynamicCordisRunner/resolveInspectQuery'] },
resource: { kind: 'global' },
}] })
try {
await expect(scaffold.ctx.typertGateway.invoke({
peer, namespace: 'dynamicCordisRunner', method: 'resolveInspectQuery',
args: { agentId: child.agent.id, requestId: 'inspect-0', resolution: { ok: true, data: {} } },
})).rejects.toMatchObject({ code: 'remote-access/denied' })
} finally {
unregister()
await peer.dispose()
}
expect(child.agent.session.header.origin).toBe('subagent')
expect(scaffold.ctx.agents.get(child.agent.id)).toBe(child.agent)
} finally {
await child.dispose()
}
} finally {
await browser.close()
}
} finally {
await scaffold.close()
}
})
+19 -13
View File
@@ -27,19 +27,23 @@ describe('creation recommendation after an explicit wish', () => {
})
afterAll(async () => { await browser?.close(); await scaffold?.close() })
it('shows one card below the answer, lets the user change location, and restores a dismissal', async () => {
it('keeps the creation controls after a documentation example and restores only the chosen dismissal', async () => {
const tripwire = watchConsole(page)
await page.setViewportSize({ width: 620, height: 900 })
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await connectFreshWorkspace(page, scaffold.workspaceCwd)
const input = page.locator('[data-composer-input]').first()
const settled = scaffold.whenTurnSettled()
await input.fill(fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]!)
await input.press('Enter')
await settled
const card = page.locator('[data-action-card]')
const prompts = fixtureUserPrompts(await readFile(fixture, 'utf8'))
async function sendTurn(prompt: string) {
const settled = scaffold.whenTurnSettled()
await input.fill(prompt)
await input.press('Enter')
await settled
}
await sendTurn(prompts[0]!)
const creationSelector = '[data-action="create_personalized_page"]'
const card = page.locator(creationSelector)
await card.waitFor({ state: 'visible' })
expect(await card.count()).toBe(1)
expect(await page.locator('[data-turn-tail] [data-action-card]').count()).toBe(1)
const answer = page.getByText('I can create a persistent counter with increment and reset controls. Choose its location below.', { exact: true })
const answerBox = await answer.boundingBox()
@@ -107,6 +111,11 @@ describe('creation recommendation after an explicit wish', () => {
expect(await custom.count()).toBe(0)
await compareOrRefreshGolden(join(directory, 'options.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode)
expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await sendTurn(prompts[1]!)
const dismissExample = page.locator('[data-action="my_example"]').getByRole('button', { name: 'Not now', exact: true })
await dismissExample.waitFor()
expect(await page.locator('[data-action-card]').count()).toBe(2)
expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(true)
await card.getByRole('button', { name: 'Not now', exact: true }).click()
await card.getByRole('status').getByText('Dismissed', { exact: true }).waitFor()
const warnings = tripwire.warnings.length
@@ -116,14 +125,11 @@ describe('creation recommendation after an explicit wish', () => {
expect(await card.getByRole('button', { name: 'Create', exact: true }).count()).toBe(0)
expect(await card.getByRole('button', { name: 'Show more', exact: true }).isVisible()).toBe(true)
expect((await scaffold.ctx.pluginManager.listBundles()).some(bundle => bundle.name.startsWith('@dsh-local/view-'))).toBe(false)
await compareOrRefreshGolden(join(directory, 'dismissed.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode)
const statusSettled = scaffold.whenTurnSettled()
await input.fill(fixtureUserPrompts(await readFile(fixture, 'utf8'))[1]!)
await input.press('Enter')
await statusSettled
await compareOrRefreshGolden(join(directory, 'dismissed.expected.md'), await captureStableAria(page, creationSelector, scaffold.workspaceCwd), scaffold.mode)
await sendTurn(prompts[2]!)
await page.getByText('The counter proposal was dismissed. Creation never started.', { exact: true }).waitFor()
expect(await card.count()).toBe(1)
expect(await card.getByRole('button', { name: 'Create', exact: true }).count()).toBe(0)
expect(await dismissExample.isEnabled()).toBe(true)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
if (scaffold.mode === 'replay') await assertFixtureInventory(directory, [
+8 -7
View File
@@ -28,15 +28,16 @@ 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-macos', 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')
}
// Both variants start without retained state so that the persistent-mode action has an effect.
const defaults = join(directory, 'ptc-defaults')
await mkdir(defaults)
await writeFile(join(defaults, 'package.json'), JSON.stringify({ name: 'cua-ptc-defaults', version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } }))
await writeFile(join(defaults, 'cordis.patch.yml'), script
? '- id: ptc-runtime\n config:\n executionMode: vm-script\n scriptPersistence: false\n'
: '- id: ptc-runtime\n config:\n executionMode: per-call\n')
const harnessHome = join(directory, 'home')
const scaffold = ownedScaffold = await launchWebScaffold({
profile: { packages: script ? [{ dir: defaults, enabled: true }] : [] },
profile: { packages: [{ dir: defaults, enabled: true }] },
harnessHome, extraOverlayPath: [
fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), patch,
] })
+1 -1
View File
@@ -56,7 +56,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr
// Application consent remains independent of the session's tool-approval policy.
const grant = scaffold.ctx.tools.execute({ agent, signal: new AbortController().signal,
calls: [{ type: 'tool-call', id: brandString<ToolCallId>('cua-app-approval'), name: 'run_code',
arguments: JSON.stringify({ code: 'return await tools.cua({ method: "getApp", params: { selector: "Fixture" } })',
arguments: JSON.stringify({ code: 'await tools.cua({ method: "getApp", params: { selector: "Fixture" } })',
description: 'Request application access' }) }] })
const approval = page.locator('[data-approval-key]')
await Promise.race([approval.waitFor(), grant.then((result) => {
+590
View File
@@ -0,0 +1,590 @@
/** An anonymous browser enters the shipped application only after settings approval. */
import { fileURLToPath } from 'node:url'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { chromium, type Locator, type Page } from 'playwright'
import { expect, it, onTestFinished } from 'vitest'
import {
captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode,
} from './scaffold.ts'
import { launchRemoteConnectionFixture } from './remote-connection-fixture.ts'
import { openSettings, ZH_BROWSER_LOCALE } from './support.ts'
const spoofedSourceIp = '198.51.100.42'
const spoofedSourceHeaders = {
forwarded: `for=${spoofedSourceIp}`,
'x-forwarded-for': spoofedSourceIp,
'x-real-ip': spoofedSourceIp,
}
async function expectObservedSource(requests: Locator, authority: string): Promise<void> {
const content = await requests.innerText()
expect(content).toContain('来源 IP')
expect(content).toContain('127.0.0.1')
expect(content).not.toContain(authority)
expect(content).not.toContain(spoofedSourceIp)
}
async function readPairingCodes(page: Page, baseUrl: string): Promise<{ status: number; codes: (string | undefined)[] | undefined }> {
const response = await page.request.post(new URL('api/remoteConnection/pairingRequests', baseUrl).href, {
data: { type: 'client-request', rpcId: 'pairing-list-observation', method: 'remoteConnection/pairingRequests', payload: { args: {} } },
})
try {
const list: unknown = await response.json()
const result: unknown = typeof list === 'object' && list !== null ? Reflect.get(list, 'result') : undefined
const value: unknown = typeof result === 'object' && result !== null ? Reflect.get(result, 'value') : undefined
const rows: unknown = typeof value === 'object' && value !== null ? Reflect.get(value, 'requests') : undefined
const codes = Array.isArray(rows) ? rows.map((row: unknown) => {
const code: unknown = typeof row === 'object' && row !== null ? Reflect.get(row, 'code') : undefined
return typeof code === 'string' ? code : undefined
}) : undefined
return { status: response.status(), codes }
} finally { await response.dispose() }
}
async function decideWithDelayedList(page: Page, requests: Locator, code: string, decision: 'allow' | 'deny'): Promise<string> {
const releaseStaleRead = Promise.withResolvers<undefined>()
const releaseFreshReads = Promise.withResolvers<undefined>()
let readCount = 0
let staleRead: { method: string; request: unknown; response: unknown } | undefined
let staleReadSettled = false
let freshReadStarted = false
const routeErrors: unknown[] = []
await page.route('**/api/remoteConnection/pairingRequests', async (route) => {
const stale = readCount++ === 0
let handlingStarted = false
try {
if (stale) {
const response = await route.fetch()
staleRead = {
method: route.request().method(), request: route.request().postDataJSON(), response: await response.json(),
}
await releaseStaleRead.promise
handlingStarted = true
if (route.request().failure()?.errorText === 'net::ERR_ABORTED') await route.abort('aborted')
else await route.fulfill({ response })
} else {
freshReadStarted = true
await releaseFreshReads.promise
handlingStarted = true
if (route.request().failure()?.errorText === 'net::ERR_ABORTED') await route.abort('aborted')
else await route.continue()
}
} catch (error) {
if (route.request().failure()?.errorText !== 'net::ERR_ABORTED') routeErrors.push(error)
if (!handlingStarted) {
try { await route.abort('failed') } catch (abortError) { routeErrors.push(abortError) }
}
} finally {
if (stale) staleReadSettled = true
}
})
try {
await expect.poll(() => staleRead !== undefined || routeErrors.length > 0, { timeout: 15_000 }).toBe(true)
expect(routeErrors).toEqual([])
expect(staleRead?.method).toBe('POST')
expect(staleRead?.request).toMatchObject({ payload: { args: {} } })
expect(staleRead?.response).toMatchObject({ result: {
ok: true, value: { requests: [{ code: code.replace(' ', '') }] },
} })
await requests.getByRole('button', { name: decision === 'allow' ? '批准' : '拒绝', exact: true }).click()
const notice = page.getByRole('alert').filter({ hasText: decision === 'allow' ? '已批准申请' : '已拒绝申请' })
await notice.waitFor()
expect(await requests.getByText(code, { exact: true }).count()).toBe(0)
const snapshot = (await Promise.all([requests.ariaSnapshot(), notice.ariaSnapshot()])).join('\n')
releaseStaleRead.resolve(undefined)
await expect.poll(() => staleReadSettled, { timeout: 15_000 }).toBe(true)
await expect.poll(() => freshReadStarted, { timeout: 15_000 }).toBe(true)
expect(await requests.getByText(code, { exact: true }).count()).toBe(0)
return snapshot
} finally {
releaseStaleRead.resolve(undefined)
releaseFreshReads.resolve(undefined)
await page.unrouteAll({ behavior: 'wait' })
expect(routeErrors).toEqual([])
}
}
it('lets a paired mobile browser approve another device and keeps denied or cancelled applicants signed out behind a public mount', async () => {
const scaffold = await launchWebScaffold({
publicMount: { prefix: '/tools/dsh/' },
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 1440, height: 1000 } })
await owner.goto(scaffold.authenticatedUrl)
await owner.waitForFunction(() => '__DSH_BOOT__' in window)
expect((await owner.context().cookies()).some(cookie => cookie.name.startsWith('dsh-auth-') && cookie.httpOnly)).toBe(true)
await openSettings(owner, 'zh')
const navigation = owner.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true })
await expect.poll(() => navigation.count()).toBe(1)
await navigation.click()
const approvals = owner.getByRole('region', { name: '远程连接', exact: true })
.getByRole('region', { name: '配对申请', exact: true })
await approvals.waitFor()
const applicant = await browser.newPage({
locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 },
extraHTTPHeaders: spoofedSourceHeaders,
})
const errors: string[] = []
applicant.on('pageerror', error => errors.push(error.message))
const anonymousScript = applicant.waitForResponse(response => response.url() === new URL('pairing/client.js', scaffold.baseUrl).href)
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
expect((await anonymousScript).status()).toBe(200)
expect(await applicant.evaluate(() => customElements.get('dsh-device-pairing') !== undefined)).toBe(true)
expect(await applicant.evaluate(() => '__ModuleLoader__' in window)).toBe(false)
await applicant.locator('#auth-pair-request').click()
await applicant.locator('#auth-pair-code').waitFor()
const previousCode = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(previousCode, { exact: true }).waitFor()
const countdown = applicant.locator('#auth-pair-countdown')
const initialCountdown = await countdown.innerText()
expect(initialCountdown).toMatch(/\d+:\d{2}/u)
await expect.poll(() => countdown.innerText()).not.toBe(initialCountdown)
const [replacementResponse] = await Promise.all([
applicant.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request')),
applicant.getByRole('button', { name: '重新申请', exact: true }).click(),
])
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(previousCode)
await applicant.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
const code = await applicant.locator('#auth-pair-code').innerText()
expect(code).toMatch(/^[A-Z2-9]{4} [A-Z2-9]{4}$/u)
await approvals.getByText(previousCode, { exact: true }).waitFor({ state: 'detached' })
await approvals.getByText(code, { exact: true }).waitFor()
expect(await replacementResponse.request().allHeaders()).toMatchObject(spoofedSourceHeaders)
const ticket: unknown = await replacementResponse.json()
expect(ticket).toMatchObject({ code: code.replace(' ', ''), sourceIp: '127.0.0.1', authority: new URL(scaffold.baseUrl).origin })
await expectObservedSource(approvals, new URL(scaffold.baseUrl).host)
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await applicant.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
const screenshotDirectory = process.env.DSH_PAIRING_SCREENSHOT_DIR
if (screenshotDirectory !== undefined) {
await applicant.emulateMedia({ colorScheme: 'light' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)).toBe('rgb(250, 250, 250)')
await applicant.screenshot({ path: join(screenshotDirectory, 'auth-request-light.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: 'dark' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)).toBe('rgb(23, 23, 23)')
await applicant.screenshot({ path: join(screenshotDirectory, 'auth-request-dark.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: null })
}
const mode = webSnapshotMode()
const applicationUrl = new URL(scaffold.authenticatedUrl)
const tokenPlaceholder = `${applicationUrl.origin}${applicationUrl.pathname}?token=xxx`
expect(await applicant.locator('#token').getAttribute('placeholder')).toBe(tokenPlaceholder)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/request.expected.md', import.meta.url)),
(await captureStableAria(applicant, 'main', scaffold.workspaceCwd, {
replacements: [
[tokenPlaceholder, '{{application-url}}?token=xxx'],
[code, '{{pairing-code}}'], [new URL(scaffold.baseUrl).host, '{{authority}}'],
],
})).replace(/\d+:\d{2}/gu, '{{remaining}}'), mode,
)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/approval.expected.md', import.meta.url)),
(await approvals.ariaSnapshot()).replaceAll(code, '{{pairing-code}}'), mode,
)
const approvedDecision = await decideWithDelayedList(owner, approvals, code, 'allow')
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(scaffold.baseUrl)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await applicant.reload())?.status()).toBe(200)
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
await openSettings(applicant, 'zh')
await applicant.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true }).click()
const mobileSection = applicant.getByRole('region', { name: '远程连接', exact: true })
const mobileApprovals = mobileSection.getByRole('region', { name: '配对申请', exact: true })
await mobileApprovals.waitFor()
expect(await mobileSection.getByRole('img', { name: '一次性登录二维码', exact: true }).count()).toBe(0)
const third = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
third.on('pageerror', error => errors.push(error.message))
expect((await third.goto(scaffold.baseUrl))?.status()).toBe(401)
await third.getByRole('button', { name: '申请配对', exact: true }).click()
await third.locator('#auth-pair-code').waitFor()
const thirdCode = await third.locator('#auth-pair-code').innerText()
await mobileApprovals.getByText(thirdCode, { exact: true }).waitFor()
await expectObservedSource(mobileApprovals, new URL(scaffold.baseUrl).host)
expect(await third.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await third.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
expect(await third.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
if (screenshotDirectory !== undefined) {
await applicant.emulateMedia({ colorScheme: 'light' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('light')
await applicant.screenshot({ path: join(screenshotDirectory, 'pairing-light.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: 'dark' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('dark')
await applicant.screenshot({ path: join(screenshotDirectory, 'pairing-dark.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: null })
}
await mobileApprovals.getByRole('button', { name: '批准', exact: true }).click()
await third.waitForFunction(() => '__DSH_BOOT__' in window)
expect(third.url()).toBe(scaffold.baseUrl)
expect((await third.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await third.reload())?.status()).toBe(200)
await third.waitForFunction(() => '__DSH_BOOT__' in window)
await mobileApprovals.getByText(thirdCode, { exact: true }).waitFor({ state: 'detached' })
expect(await third.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
expect(errors).toEqual([])
const denied = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
expect((await denied.goto(scaffold.baseUrl))?.status()).toBe(401)
await denied.locator('#auth-pair-request').click()
await denied.locator('#auth-pair-code').waitFor()
const deniedCode = await denied.locator('#auth-pair-code').innerText()
await approvals.getByText(deniedCode, { exact: true }).waitFor()
const deniedDecision = await decideWithDelayedList(owner, approvals, deniedCode, 'deny')
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/decision.expected.md', import.meta.url)),
[approvedDecision, deniedDecision].join('\n'), mode,
)
await denied.locator('#auth-pair-panel[data-state="denied"]').waitFor()
expect(await denied.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await denied.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
await denied.getByRole('button', { name: '重新申请', exact: true }).click()
await denied.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
const cancelledCode = await denied.locator('#auth-pair-code').innerText()
await approvals.getByText(cancelledCode, { exact: true }).waitFor()
await denied.locator('#auth-pair-cancel').click()
await denied.getByRole('button', { name: '申请配对', exact: true }).waitFor()
expect(await denied.locator('#auth-pair-panel').isHidden()).toBe(true)
await approvals.getByText(cancelledCode, { exact: true }).waitFor({ state: 'detached' })
expect((await denied.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect((await denied.reload())?.status()).toBe(401)
for (const decision of ['allow', 'deny'] as const) {
const unconfirmed = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
unconfirmed.on('pageerror', error => errors.push(error.message))
expect((await unconfirmed.goto(scaffold.baseUrl))?.status()).toBe(401)
const creation = unconfirmed.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request') && response.status() === 200)
await unconfirmed.getByRole('button', { name: '申请配对', exact: true }).click()
await unconfirmed.locator('#auth-pair-code').waitFor()
const unconfirmedCode = await unconfirmed.locator('#auth-pair-code').innerText()
const created = await creation
const ticket: unknown = await created.json()
const submitted: unknown = created.request().postDataJSON()
if (typeof ticket !== 'object' || ticket === null || typeof submitted !== 'object' || submitted === null) {
throw new Error('Pairing creation did not exchange credential records')
}
expect(Reflect.get(ticket, 'id') === Reflect.get(submitted, 'id') && Reflect.get(ticket, 'secret') === Reflect.get(submitted, 'secret')).toBe(true)
expect(Reflect.get(ticket, 'code')).toBe(unconfirmedCode.replace(' ', ''))
const observed = await readPairingCodes(owner, scaffold.baseUrl)
expect(observed.status).toBe(200)
expect(observed.codes).toContain(unconfirmedCode.replace(' ', ''))
try { await approvals.getByText(unconfirmedCode, { exact: true }).waitFor() }
catch (error) {
const current = await readPairingCodes(owner, scaffold.baseUrl)
console.info('pairing approval list before dropped decision', { decision, code: unconfirmedCode, ...current, content: await approvals.innerText(), errors })
throw error
}
expect((await unconfirmed.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
const decisionDropped = Promise.withResolvers<undefined>()
const routeErrors: unknown[] = []
let committedResponse: unknown
await owner.route('**/api/remoteConnection/decidePairing', async (route) => {
try {
const response = await route.fetch()
committedResponse = await response.json()
expect(response.status()).toBe(200)
} catch (error) {
routeErrors.push(error)
} finally {
try { await route.abort('failed') } catch (error) { routeErrors.push(error) }
decisionDropped.resolve(undefined)
}
})
try {
await approvals.getByRole('button', { name: decision === 'allow' ? '批准' : '拒绝', exact: true }).click()
await decisionDropped.promise
expect(routeErrors).toEqual([])
expect(committedResponse).toMatchObject({ result: { ok: true, value: decision === 'allow' ? 'approved' : 'denied' } })
await owner.getByRole('alert').filter({ hasText: '无法确认审批结果,请刷新列表后再试' }).waitFor()
expect(await owner.getByRole('alert').filter({ hasText: '已批准申请' }).count()).toBe(0)
expect(await owner.getByRole('alert').filter({ hasText: '已拒绝申请' }).count()).toBe(0)
if (decision === 'allow') {
await unconfirmed.waitForFunction(() => '__DSH_BOOT__' in window)
expect(unconfirmed.url()).toBe(scaffold.baseUrl)
expect((await unconfirmed.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await unconfirmed.reload())?.status()).toBe(200)
await unconfirmed.waitForFunction(() => '__DSH_BOOT__' in window)
} else {
await unconfirmed.locator('#auth-pair-panel[data-state="denied"]').waitFor()
expect(await unconfirmed.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await unconfirmed.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect((await unconfirmed.reload())?.status()).toBe(401)
}
await approvals.getByText(unconfirmedCode, { exact: true }).waitFor({ state: 'detached' })
} finally {
await owner.unrouteAll({ behavior: 'wait' })
expect(routeErrors).toEqual([])
}
}
expect(errors).toEqual([])
} finally {
await browser.close()
}
})
it('keeps one Remote connection panel, its QR invitation, and login link while another browser requests approval', async () => {
const fixture = await launchRemoteConnectionFixture(false)
onTestFinished(() => fixture.close())
const browser = await chromium.launch({
proxy: { server: 'http://127.0.0.1:9', bypass: '*' },
args: ['--host-resolver-rules=MAP qr-login.test 127.0.0.1'],
})
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 1440, height: 1000 } })
await owner.goto(fixture.authenticatedUrl)
await openSettings(owner, 'zh')
const navigation = owner.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true })
await expect.poll(() => navigation.count()).toBe(1)
await navigation.click()
const section = owner.getByRole('region', { name: '远程连接', exact: true })
const loginLink = section.getByRole('region', { name: '访问地址', exact: true }).locator('code')
await expect.poll(() => loginLink.innerText()).toBe(fixture.authenticatedUrl)
const approvals = section.getByRole('region', { name: '配对申请', exact: true })
await approvals.waitFor()
const created = owner.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
await section.getByRole('button', { name: '生成二维码', exact: true }).click()
const invitation = await (await created).json() as { result: { ok: boolean; value: { url: string } } }
expect(invitation.result.ok).toBe(true)
const qr = section.getByRole('img', { name: '一次性登录二维码', exact: true })
await qr.waitFor()
const qrMarkup = await qr.innerHTML()
const applicant = await browser.newPage({
locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 }, extraHTTPHeaders: spoofedSourceHeaders,
})
expect((await applicant.goto(fixture.url))?.status()).toBe(401)
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
const previousCode = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(previousCode, { exact: true }).waitFor()
const countdown = applicant.locator('#auth-pair-countdown')
const initialCountdown = await countdown.innerText()
await expect.poll(() => countdown.innerText()).not.toBe(initialCountdown)
const pairingListUrl = new URL('api/remoteConnection/pairingRequests', fixture.url).href
await owner.route(pairingListUrl, route => route.fulfill({ status: 503 }))
const readFailure = approvals.getByRole('alert')
await readFailure.waitFor()
expect(await approvals.getByText(previousCode, { exact: true }).count()).toBe(0)
expect(await approvals.getByRole('note').count()).toBe(0)
expect(await approvals.getByRole('status').count()).toBe(0)
const retry = approvals.getByRole('button', { name: '重试', exact: true })
expect(await retry.isEnabled()).toBe(true)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/approval-refresh-failed.expected.md', import.meta.url)),
await approvals.ariaSnapshot(), webSnapshotMode(),
)
const [replacementResponse] = await Promise.all([
applicant.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request')),
applicant.getByRole('button', { name: '重新申请', exact: true }).click(),
])
await applicant.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(previousCode)
const code = await applicant.locator('#auth-pair-code').innerText()
await owner.unroute(pairingListUrl)
await retry.click()
await approvals.getByText(code, { exact: true }).waitFor()
expect(await approvals.getByText(previousCode, { exact: true }).count()).toBe(0)
expect(await readFailure.count()).toBe(0)
await approvals.getByRole('note').waitFor()
expect(await replacementResponse.request().allHeaders()).toMatchObject(spoofedSourceHeaders)
const ticket: unknown = await replacementResponse.json()
expect(ticket).toMatchObject({ code: code.replace(' ', ''), sourceIp: '127.0.0.1', authority: new URL(fixture.url).origin })
await expectObservedSource(approvals, new URL(fixture.url).host)
expect(await qr.innerHTML()).toBe(qrMarkup)
expect(await section.getByRole('button', { name: '重新生成', exact: true }).isEnabled()).toBe(true)
expect(await section.getByRole('button', { name: '取消', exact: true }).isEnabled()).toBe(true)
expect(await navigation.count()).toBe(1)
expect(await approvals.getByRole('button').allTextContents()).toEqual(['批准', '拒绝'])
for (const width of [1440, 390]) {
await owner.setViewportSize({ width, height: 1000 })
await approvals.scrollIntoViewIfNeeded()
const codeBounds = (await approvals.locator('code').boundingBox())!
const sourceIp = (await approvals.getByText('127.0.0.1', { exact: true }).boundingBox())!
const approve = (await approvals.getByRole('button', { name: '批准', exact: true }).boundingBox())!
const deny = (await approvals.getByRole('button', { name: '拒绝', exact: true }).boundingBox())!
expect(approve.height).toBe(28)
expect(deny.height).toBe(28)
if (width === 1440) {
expect(approve.x).toBeGreaterThan(codeBounds.x + codeBounds.width)
expect(deny.x).toBeGreaterThan(approve.x + approve.width)
expect(approve.y).toBe(deny.y)
const informationCenter = (codeBounds.y + sourceIp.y + sourceIp.height) / 2
expect(Math.abs(informationCenter - approve.y - approve.height / 2)).toBeLessThanOrEqual(1)
} else {
expect(approve.y).toBeGreaterThanOrEqual(sourceIp.y + sourceIp.height)
expect(deny.y).toBeGreaterThanOrEqual(approve.y + approve.height)
expect(approve.x).toBe(deny.x)
expect(approve.width).toBe(deny.width)
}
}
await owner.setViewportSize({ width: 1440, height: 1000 })
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/coexistence.expected.md', import.meta.url)),
(await captureStableAria(owner, 'section[aria-label="远程连接"]', fixture.root, {
replacements: [[fixture.authenticatedUrl, '{{access-address}}?token={{login-token}}'], [fixture.url, '{{access-address}}'], [code, '{{pairing-code}}']],
})).replace(/\d+ 秒后过期/gu, '{{seconds}} 秒后过期'), webSnapshotMode(),
)
await approvals.getByRole('button', { name: '批准', exact: true }).click()
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(fixture.url)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect(await qr.innerHTML()).toBe(qrMarkup)
expect(await loginLink.innerText()).toBe(fixture.authenticatedUrl)
const scanning = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
const exchanged = scanning.waitForResponse(response => new URL(response.url()).pathname === '/' && new URL(response.url()).searchParams.get('login') === 'qr'
&& response.request().method() === 'POST')
await scanning.goto(invitation.result.value.url)
expect((await exchanged).status()).toBe(204)
await scanning.waitForFunction(() => '__DSH_BOOT__' in window)
expect(scanning.url()).toBe(fixture.url)
expect((await scanning.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
await section.getByText('二维码已使用,请在手机上确认是否已登录', { exact: true }).waitFor()
expect(await navigation.count()).toBe(1)
} finally { await browser.close() }
})
it('shows expiry and lets the applicant start a new request without signing in', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-pairing-expiry-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const overlay = join(root, 'pairing.yml')
await writeFile(overlay, '- id: remote-connection\n config:\n pairing:\n requestTtlMs: 3000\n pollIntervalMs: 500\n')
const scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const applicant = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
const expiredCode = await applicant.locator('#auth-pair-code').innerText()
await applicant.locator('#auth-pair-panel[data-state="expired"]').waitFor()
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await applicant.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
await applicant.getByRole('button', { name: '重新申请', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
expect(await applicant.locator('#auth-pair-code').innerText()).not.toBe(expiredCode)
await applicant.locator('#auth-pair-cancel').click()
await applicant.getByRole('button', { name: '申请配对', exact: true }).waitFor()
expect(await applicant.locator('#auth-pair-panel').isHidden()).toBe(true)
} finally { await browser.close() }
})
it('keeps Token and pairing usable on the same page after a QR exchange fails', async () => {
const fixture = await launchRemoteConnectionFixture(false)
onTestFinished(() => fixture.close())
const browser = await chromium.launch({
proxy: { server: 'http://127.0.0.1:9', bypass: '*' },
args: ['--host-resolver-rules=MAP qr-login.test 127.0.0.1'],
})
try {
const applicant = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
const errors: string[] = []
applicant.on('pageerror', error => errors.push(error.message))
const target = new URL(fixture.url)
target.searchParams.set('login', 'qr')
target.hash = 'a'.repeat(43)
const exchanged = applicant.waitForResponse(response => response.request().method() === 'POST'
&& new URL(response.url()).pathname === '/' && new URL(response.url()).searchParams.get('login') === 'qr')
expect((await applicant.goto(target.href))?.status()).toBe(200)
expect((await exchanged).status()).toBe(410)
const failure = applicant.getByRole('alert').filter({ hasText: '二维码' })
await failure.waitFor()
expect(new URL(applicant.url()).hash).toBe('')
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
const token = applicant.locator('#token')
expect(await token.isEnabled()).toBe(true)
expect(await applicant.locator('#token-submit').isEnabled()).toBe(true)
expect(await applicant.getByRole('button', { name: '申请配对', exact: true }).isEnabled()).toBe(true)
const screenshotDirectory = process.env.DSH_PAIRING_SCREENSHOT_DIR
if (screenshotDirectory !== undefined) await mkdir(screenshotDirectory, { recursive: true })
for (const scene of [
{ name: 'mobile-light', width: 390, height: 844, colorScheme: 'light' },
{ name: 'mobile-dark', width: 390, height: 844, colorScheme: 'dark' },
{ name: 'desktop-light', width: 1440, height: 1000, colorScheme: 'light' },
] as const) {
await applicant.setViewportSize({ width: scene.width, height: scene.height })
await applicant.emulateMedia({ colorScheme: scene.colorScheme })
const layout = await applicant.evaluate(() => {
const form = document.querySelector<HTMLElement>('#token-form')!
const pairing = document.querySelector<HTMLElement>('dsh-device-pairing')!
const notice = document.querySelector<HTMLElement>('#qr-notice')!
const title = document.querySelector<HTMLElement>('#title')!
const formBox = form.getBoundingClientRect()
const pairBox = pairing.getBoundingClientRect()
return {
sameContainer: form.parentElement === pairing.parentElement,
feedbackOutside: notice.parentElement === form.parentElement?.parentElement,
headingAbove: title.getBoundingClientRect().bottom <= notice.getBoundingClientRect().top,
feedbackAbove: notice.getBoundingClientRect().bottom <= formBox.top,
gap: pairBox.top - formBox.bottom,
xDifference: pairBox.x - formBox.x,
widthDifference: pairBox.width - formBox.width,
borders: [form, pairing].map(card => Number.parseFloat(getComputedStyle(card).borderTopWidth)),
parentBorder: Number.parseFloat(getComputedStyle(form.parentElement!).borderTopWidth),
overflows: document.documentElement.scrollWidth > innerWidth,
}
})
expect(layout).toMatchObject({
sameContainer: true, feedbackOutside: true, headingAbove: true, feedbackAbove: true, overflows: false,
})
expect(Math.abs(layout.gap - 24)).toBeLessThanOrEqual(1)
expect(Math.abs(layout.xDifference)).toBeLessThanOrEqual(1)
expect(Math.abs(layout.widthDifference)).toBeLessThanOrEqual(1)
expect(layout.borders.every(border => border > 0)).toBe(true)
expect(layout.parentBorder).toBe(0)
if (screenshotDirectory !== undefined) {
await applicant.screenshot({
path: join(screenshotDirectory, `qr-rejected-options-${scene.name}.png`), fullPage: true,
})
}
}
await applicant.setViewportSize({ width: 390, height: 844 })
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
if (screenshotDirectory !== undefined) {
for (const colorScheme of ['light', 'dark'] as const) {
await applicant.emulateMedia({ colorScheme })
await applicant.screenshot({
path: join(screenshotDirectory, `pairing-waiting-mobile-${colorScheme}.png`), fullPage: true,
})
}
}
expect(await token.isEnabled()).toBe(true)
const launchToken = new URL(fixture.authenticatedUrl).searchParams.get('token')
if (launchToken === null) throw new Error('Token entry did not publish a startup credential')
await token.fill(launchToken)
await applicant.locator('#token-submit').click()
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(fixture.url)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-auth-') && cookie.httpOnly)).toBe(true)
expect(errors).toEqual([])
} finally {
await browser.close()
}
})
+153
View File
@@ -0,0 +1,153 @@
// DingTalk sign-in failures, recovery, and sign-out through the real Host/Remote/browser composition.
// A stand-in dws waits for each authorization page visit and keeps its sign-in on disk.
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const DINGTALK_DIR = fileURLToPath(new URL('../../../packages/connector/dingtalk', import.meta.url))
const AUTH_PAGE = 'https://login.dingtalk.com/oauth2/auth'
const authUrl = (attempt: number) => `${AUTH_PAGE}?e2e=${String(attempt)}&state=fixture-state`
// The stand-in keeps its sign-in in state.json beside itself. auth login prints a
// new authorization link alone on an indented stderr line for each attempt and
// waits until the test marks the page visited; its second successful sign-in
// makes a second organization's account current, as the stand-in's own rule;
// auth logout accepts only the current account's profile.
const DWS = `#!/usr/bin/env node
const { existsSync, readFileSync, writeFileSync } = require('node:fs')
const { join } = require('node:path')
const dir = __dirname
const statePath = join(dir, 'state.json')
const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { signedIn: false, attempts: 0, logins: 0 }
const ACCOUNTS = [
{ corp_id: 'corp-e2e', corp_name: 'E2E 组织', user_id: 'user-e2e', user_name: 'E2E 用户' },
{ corp_id: 'corp-e2e-2', corp_name: '第二个 E2E 组织', user_id: 'user-e2e-2', user_name: '第二个 E2E 用户' },
]
const current = () => ACCOUNTS[Math.min(state.logins, ACCOUNTS.length) - 1]
const save = () => { writeFileSync(statePath, JSON.stringify(state)) }
const json = (value) => JSON.stringify(value, null, 2) + '\\n'
switch (process.argv.slice(2).join(' ')) {
case 'auth status --format json':
process.stdout.write(json(state.signedIn
? { success: true, authenticated: true, ...current() }
: { success: true, authenticated: false, message: '未登录' }))
break
case 'auth login --no-browser --format json': {
state.attempts += 1
save()
process.stderr.write('\\n🔐 登录钉钉\\n\\n请在浏览器中完成扫码授权。\\n如果浏览器未自动打开,请手动访问:\\n ${AUTH_PAGE}?e2e=' + state.attempts + '&state=fixture-state\\n\\n⏳ 等待授权中...\\n')
const poll = setInterval(() => {
if (!existsSync(join(dir, 'auth-visited'))) return
clearInterval(poll)
if (existsSync(join(dir, 'login-fails'))) {
process.stderr.write(json({ error: { category: 'auth', message: 'dingtalk login failed; state=fixture-state' } }))
process.exitCode = 2
} else {
state.signedIn = true
state.logins += 1
save()
process.stdout.write(json({ success: true, message: '登录成功' }))
}
}, 50)
break
}
case state.signedIn ? 'auth logout --profile ' + current().corp_id + ':' + current().user_id : 'auth logout':
state.signedIn = false
save()
process.stdout.write('[OK] 已清除认证信息\\n')
break
default:
process.stderr.write('unexpected dws arguments: ' + process.argv.slice(2).join(' ') + '\\n')
process.exitCode = 1
}
`
// The stand-in runs through its shebang, which Windows cannot execute.
describe.skipIf(process.platform === 'win32')('web e2e: DingTalk plugin account', () => {
let binDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
binDir = await mkdtemp(join(tmpdir(), 'dsh-dingtalk-e2e-'))
await writeFile(join(binDir, 'dws'), DWS)
await chmod(join(binDir, 'dws'), 0o755)
// Stand-in skills keep the row from downloading the release's skills archive.
const skillsDir = join(binDir, 'skills')
await mkdir(join(skillsDir, 'dingtalk-shared'), { recursive: true })
await writeFile(join(skillsDir, 'dingtalk-shared', 'SKILL.md'), '# DingTalk stand-in guide\n')
const overlay = join(binDir, 'dingtalk.overlay.yml')
await writeFile(overlay, `- id: dingtalk\n config:\n binDir: ${JSON.stringify(binDir)}\n skillsDir: ${JSON.stringify(skillsDir)}\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: DINGTALK_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
await context.route(url => url.href.startsWith(AUTH_PAGE), async (route) => {
await writeFile(join(binDir, 'auth-visited'), '')
await route.fulfill({ contentType: 'text/html; charset=utf-8', body: '<!doctype html><title>DingTalk</title><p>DingTalk stand-in page</p>' })
})
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
if (binDir !== undefined) await rm(binDir, { recursive: true, force: true })
})
it('reports a failed sign-in without its output, connects on retry, signs in to another organization, and signs out after confirmation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-dingtalk-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 钉钉插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-dingtalk"]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
const opened: Page[] = []
context.on('page', (popup) => { opened.push(popup) })
await writeFile(join(binDir, 'login-fails'), '')
await section.getByRole('button', { name: '连接钉钉', exact: true }).click()
await section.getByRole('alert').waitFor({ timeout: 20_000 })
expect(await section.getAttribute('data-connector-account')).toBe('disconnected')
expect(await section.getByRole('alert').innerText()).toContain('auth-login · exit 2')
expect(await section.innerText()).not.toContain('fixture-state')
await rm(join(binDir, 'login-fails'))
await rm(join(binDir, 'auth-visited'))
await section.getByRole('button', { name: '连接钉钉', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([authUrl(1), authUrl(2)])
await section.getByText('已登录为 E2E 组织 的 E2E 用户。可以在对话中直接请 Agent 使用钉钉。', { exact: true }).waitFor({ timeout: 10_000 })
await page.getByText('钉钉已连接', { exact: true }).waitFor({ timeout: 10_000 })
// Signing in again while connected adds another organization's account; the section shows the account dws then reports.
await rm(join(binDir, 'auth-visited'))
await section.getByRole('button', { name: '登录其他组织', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connecting')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([authUrl(1), authUrl(2), authUrl(3)])
await section.getByText('已登录为 第二个 E2E 组织 的 第二个 E2E 用户。可以在对话中直接请 Agent 使用钉钉。', { exact: true }).waitFor({ timeout: 10_000 })
await section.getByRole('button', { name: '退出登录', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '退出钉钉登录?' })
await dialog.getByRole('button', { name: '退出登录', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
await page.getByText('已退出钉钉登录', { exact: true }).waitFor({ timeout: 10_000 })
expect(tripwire.pageErrors).toEqual([])
})
})
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "Agent 预设" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- text: 权限 选择新会话的默认权限模式
@@ -5,6 +5,7 @@
- button "Models"
- button "Plugins"
- button "Agent presets"
- button "Remote connection"
- button "Open configuration file"
- button "Close"
- text: Permission Choose the default permission mode for new sessions
@@ -0,0 +1,5 @@
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 无法加载申请,请重试以刷新列表
- button "重试"
@@ -0,0 +1,10 @@
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- note:
- paragraph: 批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备
- text: 配对码
- code: {{pairing-code}}
- paragraph: 来源 IP 127.0.0.1
- button "批准"
- button "拒绝"
@@ -0,0 +1,27 @@
- region "远程连接":
- heading "远程连接" [level=2]
- paragraph: 通过以下方式,在其他设备上登录并使用 DeepSeek Harness。
- region "访问地址":
- heading "访问地址" [level=3]
- code: {{access-address}}?token={{login-token}}
- button "复制链接"
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "重新生成"
- button "取消"
- img "一次性登录二维码"
- paragraph:
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- note:
- paragraph: 批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备
- text: 配对码
- code: {{pairing-code}}
- paragraph: 来源 IP 127.0.0.1
- button "批准"
- button "拒绝"
@@ -0,0 +1,16 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请" [disabled]
- status: 正在确认登录状态…
@@ -0,0 +1,8 @@
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已批准申请
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已拒绝申请
@@ -0,0 +1,16 @@
- main:
- region "Connect to this Host":
- heading "Connect to this Host" [level=1]
- paragraph: Use one of the methods below to sign in.
- form "Enter a login token or link":
- heading "Enter a login token or link" [level=2]
- paragraph: On a signed-in device, copy the link from Settings → Remote connection and paste it here.
- textbox "Enter a login token or link":
- /placeholder: {{application-url}}?token=xxx
- button "Continue"
- region "Pair this device":
- heading "Pair this device" [level=2]
- paragraph: After requesting, open Settings → Remote connection on another signed-in device. Match the pairing code and approve to sign in here automatically.
- code: {{pairing-code}}
- button "Request again"
- alert: Could not complete pairing. Check your connection, then request again.
@@ -0,0 +1,16 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请"
- alert: 无法完成配对,请检查网络后重新申请
@@ -0,0 +1,18 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请"
- button "取消申请"
- status: 正在等待批准…
- timer: 剩余时间:{{remaining}}
@@ -1,4 +1,3 @@
- textbox "搜索分支"
- group "默认":
- menuitem "origin/main 默认"
- group "本地分支":
@@ -0,0 +1,4 @@
- textbox "/ Browse commands · @ Mention files or sessions"
- textbox "Plan outline Goal · Constraints · Success criteria"
- textbox "Review Changes Risks Tests"
- textbox "Describe what you want to build, / commands, @ files or sessions"
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -61,6 +62,10 @@
- text: 文本
- checkbox "图片" [checked]
- text: 图片
- group "推理等级 1":
- text: 推理等级
- button "推理等级说明": "?"
- switch "推理等级 1"
- button "添加模型"
- button "取消"
- button "保存"
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
@@ -5,6 +5,7 @@
- button "模型"
- button "插件管理"
- button "Agent 预设"
- button "远程连接"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
Loaded 100 of 952 files, more files were not shown because too many files have changed in this diff. Show more