diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index b7f69935ec..bdfa46c623 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index 2a8d5e5319..abefbb9ee8 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index 14ac57ae33..8d29c4008e 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -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 与凭据有效期仍由本说明定义。 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml index be10ec257c..c2187c2371 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md index 1401159b86..6110df0886 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md index e8e55290a6..5b18000121 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md @@ -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)负责策略切换和临时提权。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml index 6f1e439bdf..cf82708a64 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md index f831e40520..69e87f24c8 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md index b3b686385f..c450d35a9e 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md @@ -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)继续规定锁、包安装和部分失败行为。 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml index e1b5d0b632..cb9ba7c932 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md index 1998b28e64..790617b414 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md index c9fe0a24a5..f56c7e8d28 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md @@ -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)负责文件约束、权限切换与临时提权。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml index de7db438b5..8a6b2ca486 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md index ebb4ab4087..e862c255ee 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md index 88d8dc6893..5a7712989a 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.i18n.yaml index 9994778c04..c3c45a74b5 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md index 2e27d5c0b1..73dba27a09 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.zh.md b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.zh.md index c584bde8de..098fc1e3a4 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.zh.md @@ -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` 内绑定所有会话工具,会重复普通的直接调用及其声明。 diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml index 907c19c6e6..2b557568b7 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md index 8c03479ba2..df7ccd68e6 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md @@ -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)). diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md index e72908e3fc..d17a434556 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.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))。 diff --git a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml index 88fc7212bb..f41dbe794d 100644 --- a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml +++ b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md index 394f0d7b45..b9e9402f13 100644 --- a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md +++ b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md @@ -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. diff --git a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md index 6266619fa1..dbfcf227e6 100644 --- a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md +++ b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md @@ -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 调整。 diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml index ab4b4c81af..611f01dd80 100644 --- a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md index fcd4fed452..2a49a391dd 100644 --- a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md @@ -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 /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 | diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md index cc52a1a925..195bee3bef 100644 --- a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md @@ -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 /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 聚合根程序 | diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml new file mode 100644 index 0000000000..8dd88ae7ef --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md new file mode 100644 index 0000000000..19fd7a8705 --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md @@ -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=:`, `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. diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md new file mode 100644 index 0000000000..e0af8b6f10 --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md @@ -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=:` 发布,`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 共享这些记录,其他克隆则不共享。 diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml index 3554853dcc..d114a1219a 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md index cbbcee49c7..aee36a5101 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md @@ -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 /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. diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md index f9c522a559..e85d57e1a6 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md @@ -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 /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 门禁都不会收集性能用例。 diff --git a/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.i18n.yaml b/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.i18n.yaml index d03a5ff8c5..89ad1182b6 100644 --- a/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.md b/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.md index 926203ea5b..ee3606138c 100644 --- a/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.md +++ b/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.md @@ -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. diff --git a/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.zh.md b/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.zh.md index e8a64dca20..8bf558b3da 100644 --- a/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.zh.md +++ b/.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.zh.md @@ -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。 diff --git a/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.i18n.yaml b/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.i18n.yaml index bd483649b5..efb6e0f173 100644 --- a/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.md b/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.md index 3b800774cc..c395c1507c 100644 --- a/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.md +++ b/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.md @@ -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. diff --git a/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.zh.md b/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.zh.md index 83182c650e..31da8da383 100644 --- a/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.zh.md +++ b/.agents/notes/implemented/testing/2026-10-07-scaled-benchmark-report.zh.md @@ -40,4 +40,4 @@ Session 语料的列表、搜索和 fork 用例报告最大合成工作集的整 ## 影响 -读者可以在经审阅的机器上查看每个端点及其实测默认值,并调整存储占比,而不改变任何门禁。页面依赖经审阅的常量:跨指令集评分、共享 vCPU 和磁盘延迟等级都较粗略,因此结果是估计值而不是测量值。内存视图不测量交换和回收成本。`node 24 / benchmarks` job 将该页面作为 `benchmark-report` 产物发布。 +读者可以在经审阅的机器上查看每个端点及其实测默认值,并调整存储占比,而不改变任何门禁。页面依赖经审阅的常量:跨指令集评分、共享 vCPU 和磁盘延迟等级都较粗略,因此结果是估计值而不是测量值。内存视图不测量交换和回收成本。`node 24 / benchmark report` job 用两个基准阶段 job 的结果渲染该页面,并作为 `benchmark-report` 产物发布。 diff --git a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.i18n.yaml b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.i18n.yaml index 778be9ae01..4116756217 100644 --- a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md index 7c92d9c72e..c1bd66948e 100644 --- a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md @@ -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 | |---|---| diff --git a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md index f5b31146b8..74cab1b544 100644 --- a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md @@ -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 下分两个进程运行:计时与分配。 | 项 | 内容 | |---|---| diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml new file mode 100644 index 0000000000..104fe53627 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md new file mode 100644 index 0000000000..502a331260 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md @@ -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. diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md new file mode 100644 index 0000000000..9b6ec141d5 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md @@ -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 的元素计数方式可能随浏览器版本变化;改变计数的升级需要重新记录上面的校准值和负对照中的值。 diff --git a/.agents/skills/dsh-merging-stacked-prs/SKILL.md b/.agents/skills/dsh-merging-stacked-prs/SKILL.md index 7e6a985614..69a7869df5 100644 --- a/.agents/skills/dsh-merging-stacked-prs/SKILL.md +++ b/.agents/skills/dsh-merging-stacked-prs/SKILL.md @@ -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 ` 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. diff --git a/.agents/skills/dsh-pre-push-checks/SKILL.md b/.agents/skills/dsh-pre-push-checks/SKILL.md index e10d03cecc..5b36b1007f 100644 --- a/.agents/skills/dsh-pre-push-checks/SKILL.md +++ b/.agents/skills/dsh-pre-push-checks/SKILL.md @@ -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=:` 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=:` 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. diff --git a/.github/review-ownership/.gitignore b/.github/review-ownership/.gitignore deleted file mode 100644 index c18dd8d83c..0000000000 --- a/.github/review-ownership/.gitignore +++ /dev/null @@ -1 +0,0 @@ -__pycache__/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1d0a0b7b5..c3c7cc71e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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,18 +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' - # Browsers install beside the build; only the browser readers wait for them. - # The persistent VM image owns Playwright's Linux system packages, so the - # failover pool skips apt instead of mutating the shared host each run. - DSH_CI_PLAYWRIGHT_INSTALL: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && 'browsers' || 'with-deps' }} - # 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. @@ -444,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: @@ -497,8 +926,8 @@ jobs: key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} # Ubuntu HTTP archive mirrors can stall for tens of seconds per package - # (Blacksmith lists http://azure.archive.ubuntu.com first), so ephemeral - # runners fetch the archive over HTTPS before the Playwright gate's apt. + # (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: | @@ -517,12 +946,56 @@ jobs: r'https://\1.ubuntu.com/', source.read_text())) PY - - 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" + # 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: | + 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" - - name: Run compatibility, snapshot, and artifact gates - run: pnpm run check:ci:consumers + # 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 + + - 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 @@ -633,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. @@ -656,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 diff --git a/.gitignore b/.gitignore index e3b3ba67b0..7024b069d8 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/AGENTS.md b/AGENTS.md index 6a2ccfad64..beb634cc61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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)). diff --git a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts index 3faedc4a74..ca858d5871 100644 --- a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts +++ b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts @@ -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) => { diff --git a/apps/cli/tests/profiles/sdk/tool-parity.ts b/apps/cli/tests/profiles/sdk/tool-parity.ts index 0b6299051e..a74e51d6fb 100644 --- a/apps/cli/tests/profiles/sdk/tool-parity.ts +++ b/apps/cli/tests/profiles/sdk/tool-parity.ts @@ -18,8 +18,6 @@ export const toolParityExceptions: Record = { 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.' }, ], diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index 53228c775e..2e2d7f1092 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -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. diff --git a/apps/web/tests/bundle-platform.e2e.ts b/apps/web/tests/bundle-platform.e2e.ts index 0784bd132c..6ade4d22f3 100644 --- a/apps/web/tests/bundle-platform.e2e.ts +++ b/apps/web/tests/bundle-platform.e2e.ts @@ -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() }) diff --git a/apps/web/tests/composer-history.e2e.ts b/apps/web/tests/composer-history.e2e.ts new file mode 100644 index 0000000000..2fa8cb0194 --- /dev/null +++ b/apps/web/tests/composer-history.e2e.ts @@ -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]) +}) diff --git a/apps/web/tests/cordis-inspect-subagent.e2e.ts b/apps/web/tests/cordis-inspect-subagent.e2e.ts new file mode 100644 index 0000000000..8e6fc4358c --- /dev/null +++ b/apps/web/tests/cordis-inspect-subagent.e2e.ts @@ -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('inspect-child'), + meta: { origin: 'subagent', parentSession: brandString('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() + } +}) diff --git a/apps/web/tests/creation-recommendations.e2e.ts b/apps/web/tests/creation-recommendations.e2e.ts index eeb92882e1..006a9e49b2 100644 --- a/apps/web/tests/creation-recommendations.e2e.ts +++ b/apps/web/tests/creation-recommendations.e2e.ts @@ -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, [ diff --git a/apps/web/tests/expected/input-plugin-placeholder.expected.md b/apps/web/tests/expected/input-plugin-placeholder.expected.md new file mode 100644 index 0000000000..6149c9db2b --- /dev/null +++ b/apps/web/tests/expected/input-plugin-placeholder.expected.md @@ -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" diff --git a/apps/web/tests/expected/models-settings/catalog-inputs.expected.md b/apps/web/tests/expected/models-settings/catalog-inputs.expected.md index a675cf5794..d1fe7f9957 100644 --- a/apps/web/tests/expected/models-settings/catalog-inputs.expected.md +++ b/apps/web/tests/expected/models-settings/catalog-inputs.expected.md @@ -62,6 +62,10 @@ - text: 文本 - checkbox "图片" [checked] - text: 图片 + - group "推理等级 1": + - text: 推理等级 + - button "推理等级说明": "?" + - switch "推理等级 1" - button "添加模型" - button "取消" - button "保存" diff --git a/apps/web/tests/fixtures/plugins/demo-composer-review-session/client.js b/apps/web/tests/fixtures/plugins/demo-composer-review-session/client.js new file mode 100644 index 0000000000..b89458127c --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-review-session/client.js @@ -0,0 +1,92 @@ +/** Shows a three-step review outline in the empty composer of the configured Session. */ +window.__ModuleLoader__.load({ + id: '@fixture/composer-review-session', + factory(require) { + const { createElement } = require('react') + const slot = 'conversation.input.placeholder' + const locale = 'demoComposerReviewSession' + const steps = [ + { key: 'changes', accent: 'var(--dsw-alias-state-business-primary)' }, + { key: 'risks', accent: 'var(--dsw-alias-state-warn-primary)' }, + { key: 'tests', accent: 'var(--dsw-alias-state-done-primary)' }, + ] + const leadStyle = { + color: 'var(--dsw-alias-label-secondary)', + fontWeight: 500, + marginInlineEnd: '4px', + } + const stepStyle = { + display: 'inline-block', + paddingInline: '7px', + borderRadius: 'var(--dsw-radius-xs)', + fontSize: '0.875em', + lineHeight: '18px', + color: 'var(--dsw-alias-label-secondary)', + verticalAlign: 'baseline', + } + const connectorStyle = { + display: 'inline-block', + inlineSize: '8px', + blockSize: '1px', + marginInline: '1px 5px', + verticalAlign: 'middle', + backgroundColor: 'var(--dsw-alias-border-l4)', + } + + function ReviewStep({ id, accent, label, linked }) { + return createElement('span', { style: { whiteSpace: 'nowrap' } }, + linked && createElement('span', { 'aria-hidden': true, style: connectorStyle }), + createElement('span', { + 'data-demo-review-step': id, + style: { + ...stepStyle, + backgroundColor: `color-mix(in srgb, ${accent} 13%, transparent)`, + boxShadow: `inset 2px 0 ${accent}`, + }, + }, label), + ) + } + + function ReviewHint({ t }) { + return createElement('span', { 'data-demo-review-path': '' }, + createElement('span', { style: leadStyle }, t('review')), + ...steps.flatMap(({ key, accent }, index) => [ + ' ', + createElement(ReviewStep, { key, id: key, accent, label: t(key), linked: index > 0 }), + ]), + ) + } + + return { + inject: ['slots', 'locale'], + apply(ctx, config) { + ctx.effect(() => ctx.locale.register(locale, { + en: { review: 'Review', changes: 'Changes', risks: 'Risks', tests: 'Tests' }, + zh: { review: '审查', changes: '改动', risks: '风险', tests: '测试' }, + })) + + ctx.slots.inject(slot, () => { + function register() { + const targetSessionId = config.sessionId.get() + return ctx.slots.register({ + name: slot, + locale, + priority: -1, + select: ({ sessionId }) => sessionId === targetSessionId ? sessionId : null, + }, ReviewHint) + } + + let dispose = register() + const unsubscribe = config.sessionId.subscribe(() => { + dispose() + dispose = register() + }) + return () => { + unsubscribe() + dispose() + } + }) + }, + } + }, +}) diff --git a/apps/web/tests/fixtures/plugins/demo-composer-review-session/cordis.patch.yml b/apps/web/tests/fixtures/plugins/demo-composer-review-session/cordis.patch.yml new file mode 100644 index 0000000000..65f2772ecc --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-review-session/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: demo-composer-review-session + name: '@fixture/composer-review-session' diff --git a/apps/web/tests/fixtures/plugins/demo-composer-review-session/index.js b/apps/web/tests/fixtures/plugins/demo-composer-review-session/index.js new file mode 100644 index 0000000000..4abe6c86c7 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-review-session/index.js @@ -0,0 +1,10 @@ +/** Host configuration for the session-specific composer hint. */ +import z from '@deepseek-ai/schemastery' + +/** Copy a Session ID into `sessionId` to give its composer the review checklist. */ +export const Config = z.object({ + sessionId: z.string().default('').volatile(), +}) + +/** Publish config to the client half without mounting a Host service. */ +export function apply() {} diff --git a/apps/web/tests/fixtures/plugins/demo-composer-review-session/package.json b/apps/web/tests/fixtures/plugins/demo-composer-review-session/package.json new file mode 100644 index 0000000000..c076a69e92 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-review-session/package.json @@ -0,0 +1,13 @@ +{ + "name": "@fixture/composer-review-session", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "index.js", + "exports": { ".": "./index.js", "./client": "./client.js" }, + "dependencies": { "@deepseek-ai/schemastery": "*" }, + "dsh": { + "bundle": { "patch": "./cordis.patch.yml" }, + "client": { "platform": "web" } + } +} diff --git a/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/client.js b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/client.js new file mode 100644 index 0000000000..524ceb0179 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/client.js @@ -0,0 +1,75 @@ +/** Offers shortcuts or a planning outline according to the current Session's mode. */ +window.__ModuleLoader__.load({ + id: '@fixture/composer-shortcuts', + factory(require) { + const { createElement } = require('react') + const locale = 'demo.composerShortcuts' + const placeholder = 'conversation.input.placeholder' + const messages = { + en: { + commands: 'Browse commands', + mentions: 'Mention files or sessions', + plan: 'Plan outline', + goal: 'Goal', + constraints: 'Constraints', + criteria: 'Success criteria', + }, + zh: { + commands: '浏览命令', + mentions: '引用文件或会话', + plan: '规划提纲', + goal: '目标', + constraints: '约束', + criteria: '验收标准', + }, + } + const fieldStyle = { + borderRadius: 'var(--dsw-radius-xs)', + backgroundColor: 'var(--dsw-alias-bg-module-platform)', + color: 'var(--dsw-alias-label-secondary)', + padding: '1px 5px', + whiteSpace: 'nowrap', + } + const headingStyle = { + ...fieldStyle, + backgroundColor: 'var(--dsw-alias-state-business-tertiary)', + color: 'var(--dsw-alias-state-business-primary)', + fontWeight: 500, + } + const keyStyle = { + ...fieldStyle, + border: '1px solid var(--dsw-alias-border-l2)', + font: 'inherit', + } + + function PlanOutline({ t }) { + return createElement('span', { 'data-demo-composer-plan': '' }, + createElement('span', { style: headingStyle }, t('plan')), ' ', + createElement('span', { style: fieldStyle }, t('goal')), ' · ', + createElement('span', { style: fieldStyle }, t('constraints')), ' · ', + createElement('span', { style: fieldStyle }, t('criteria')), + ) + } + + function ShortcutHint({ t, useProjection }) { + const planning = useProjection('plan', plan => plan !== undefined && (plan.pending ? !plan.active : plan.active)) + if (planning) return createElement(PlanOutline, { t }) + return createElement('span', null, + createElement('kbd', { style: keyStyle }, '/'), ' ', t('commands'), ' · ', + createElement('kbd', { style: keyStyle }, '@'), ' ', t('mentions'), + ) + } + + return { + inject: ['slots', 'locale'], + apply(ctx) { + ctx.effect(() => ctx.locale.register(locale, messages)) + ctx.slots.inject(placeholder, () => ctx.slots.register({ + name: placeholder, + locale, + select: () => true, + }, ShortcutHint)) + }, + } + }, +}) diff --git a/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/cordis.patch.yml b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/cordis.patch.yml new file mode 100644 index 0000000000..000f772b35 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: demo-composer-shortcuts + name: '@fixture/composer-shortcuts' diff --git a/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/index.js b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/index.js new file mode 100644 index 0000000000..9ec9b09c91 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/index.js @@ -0,0 +1,2 @@ +/** Declares the browser-only shortcut demo to the Host loader. */ +export function apply() {} diff --git a/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/package.json b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/package.json new file mode 100644 index 0000000000..913a112525 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/demo-composer-shortcuts/package.json @@ -0,0 +1,12 @@ +{ + "name": "@fixture/composer-shortcuts", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "index.js", + "exports": { ".": "./index.js", "./client": "./client.js" }, + "dsh": { + "bundle": { "patch": "./cordis.patch.yml" }, + "client": { "platform": "web" } + } +} diff --git a/apps/web/tests/fold-blank-matrix.e2e.ts b/apps/web/tests/fold-blank-matrix.e2e.ts index 688205f072..3665dcf823 100644 --- a/apps/web/tests/fold-blank-matrix.e2e.ts +++ b/apps/web/tests/fold-blank-matrix.e2e.ts @@ -349,12 +349,22 @@ async function startTrace(page: Page, root: string): Promise { if (read === undefined) throw new Error('fold measurement is not installed') const samples: Geometry[] = [] let frame = 0 + let pending = false + const observer = new ResizeObserver(() => { + if (!pending) return + pending = false + // A scrollport or its composer can remount between rendering opportunities. + if (document.querySelector(selector)?.querySelector('[data-composer-seat]')) samples.push(read(selector)) + }) const tick = (): void => { - // A scrollport can remount between frames; that frame contributes no sample. - try { samples.push(read(selector)) } catch (_remounting) { /* skip this frame */ } + // A fresh observation is delivered after *all* rAF writers, before paint, even when the root box is unchanged. + // Reading here instead can count a gap that the fold's later callback closes in the very same frame. + pending = true + observer.unobserve(document.documentElement) + observer.observe(document.documentElement) frame = requestAnimationFrame(tick) } - window.foldProbe = { samples, stop: () => { cancelAnimationFrame(frame) } } + window.foldProbe = { samples, stop: () => { cancelAnimationFrame(frame); observer.disconnect() } } frame = requestAnimationFrame(tick) }, root) } @@ -848,12 +858,13 @@ describe.skipIf(MODE === 'record')('web e2e: blank area after next-message foldi try { world = await openWorld(browser, scenario, replayDir) const { afterFold, afterTurn, samples, anchors } = await run(world, scenario) - const transient = samples.filter(sample => sample.maxGap > BLANK_LIMIT) + const transient = samples.flatMap((sample, frame) => sample.maxGap > BLANK_LIMIT + ? [{ frame, gap: Math.round(sample.maxGap), at: Math.round(sample.gapAt), collapsing: sample.collapsing }] : []) const summary = { id: scenario.id, landing: scenario.landing, before: samples[0] === undefined ? null : rounded(samples[0]), afterFold: rounded(afterFold), afterTurn: rounded(afterTurn), anchors, peakGap: Math.round(Math.max(0, ...samples.map(sample => sample.maxGap))), - framesOverLimit: transient.length, frames: samples.length, + framesOverLimit: transient.length, firstOverLimit: transient.slice(0, TRANSIENT_FRAMES + 1), frames: samples.length, peakSpacer: Math.round(Math.max(0, ...samples.map(sample => sample.spacer))), } const evidence = async (): Promise => { @@ -864,7 +875,10 @@ describe.skipIf(MODE === 'record')('web e2e: blank area after next-message foldi // Per-frame evidence is written for failures, or for every case with FOLDMX_EVIDENCE=1. if (process.env.FOLDMX_EVIDENCE === '1') await evidence() else onTestFailed(evidence) - if (scenario.origin === 'parent-message' || scenario.origin === 'steer') { + expect(samples.length, 'post-layout frame samples').toBeGreaterThan(0) + if (scenario.anchorFolds) { + expect.soft(samples.some(sample => sample.collapsing), 'sampled a closing row during the reader fold').toBe(true) + } else if (scenario.origin === 'parent-message' || scenario.origin === 'steer') { expect.soft(samples.some(sample => sample.collapsing), 'a control case folds nothing').toBe(false) } if (scenario.roomUntilReply !== true) { @@ -898,6 +912,47 @@ describe.skipIf(MODE === 'record')('web e2e: blank area after next-message foldi export {} describe('web e2e: fold blank measurement', () => { + it('counts gaps left by the frame writers, including consecutive frames with the same gap', async () => { + const browser = await chromium.launch() + try { + const page = await browser.newPage() + await page.setContent(`
+
+
+
+
`) + await page.evaluate(installMeasure) + // Register an early writer before the probe and a late writer after it, all on the browser's frame clock. + const drive = await page.evaluateHandle(() => { + const row = document.querySelector('[data-chat-flow-key="b"]')! + let active = false + let earlyFrame = 0 + const early = (): void => { + if (active) row.style.marginTop = '240px' + earlyFrame = requestAnimationFrame(early) + } + earlyFrame = requestAnimationFrame(early) + return () => new Promise((done) => { + active = true + const gaps = [0, 180, 180, 0] + let index = 0 + const late = (): void => { + row.style.marginTop = `${gaps[index++]}px` + if (index < gaps.length) requestAnimationFrame(late) + else { cancelAnimationFrame(earlyFrame); requestAnimationFrame(() => { done() }) } + } + requestAnimationFrame(late) + }) + }) + await startTrace(page, '#viewport') + await drive.evaluate(start => start()) + const samples = await stopTrace(page) + expect(samples.filter(sample => sample.maxGap > BLANK_LIMIT).map(sample => sample.maxGap)).toEqual([180, 180]) + } finally { + await browser.close() + } + }) + it('skips a band between fully transparent rows and counts a band beside a visible row', async () => { const browser = await chromium.launch() try { diff --git a/apps/web/tests/input-plugin-extensions.e2e.ts b/apps/web/tests/input-plugin-extensions.e2e.ts index cd8548c6f3..e8bb03a918 100644 --- a/apps/web/tests/input-plugin-extensions.e2e.ts +++ b/apps/web/tests/input-plugin-extensions.e2e.ts @@ -1,5 +1,9 @@ /** Optional input contributions mount through the real Loader and preserve editor ownership. */ +import { cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { fileURLToPath } from 'node:url' +import { parseEntryYaml, stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { chromium, type Browser } from 'playwright' import { expect, it, onTestFinished } from 'vitest' import { @@ -8,24 +12,112 @@ import { import { connectFreshWorkspace, newEnglishPage } from './support.ts' const bundle = fileURLToPath(new URL('./fixtures/plugins/fixture-input-extension', import.meta.url)) +const shortcutsBundle = fileURLToPath(new URL('./fixtures/plugins/demo-composer-shortcuts', import.meta.url)) +const reviewBundle = fileURLToPath(new URL('./fixtures/plugins/demo-composer-review-session', import.meta.url)) +const schemastery = fileURLToPath(new URL('../../../vendor/schemastery', import.meta.url)) const expected = fileURLToPath(new URL('./expected/input-plugin-extensions.expected.md', import.meta.url)) -async function fixture(enabled: boolean) { +async function fixture(packages: { dir: string; enabled: boolean }[]) { const resources: { scaffold?: WebScaffold; browser?: Browser } = {} onTestFinished(async () => { try { await resources.browser?.close() } finally { await resources.scaffold?.close() } }) - const scaffold = await launchWebScaffold({ profile: { packages: [{ dir: bundle, enabled }] } }) + const scaffold = await launchWebScaffold({ profile: { packages } }) resources.scaffold = scaffold const browser = await chromium.launch() resources.browser = browser const page = await newEnglishPage(browser), tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl) - return { scaffold, page, tripwire } + return { scaffold, browser, page, tripwire } } +it('shows shortcuts, a Plan outline, and Session review steps before restoring the built-in placeholder', async () => { + // Install a private copy so the review bundle can resolve its Host schema dependency. + const installedReview = await mkdtemp(join(tmpdir(), 'dsh-composer-review-session-')) + onTestFinished(() => rm(installedReview, { recursive: true, force: true })) + await cp(reviewBundle, installedReview, { recursive: true }) + const scopeDir = join(installedReview, 'node_modules', '@deepseek-ai') + await mkdir(scopeDir, { recursive: true }) + await symlink(schemastery, join(scopeDir, 'schemastery'), 'junction') + const { scaffold, browser, page, tripwire } = await fixture([ + { dir: shortcutsBundle, enabled: true }, + { dir: installedReview, enabled: true }, + ]) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const input = page.getByRole('textbox', { name: '/ Browse commands · @ Mention files or sessions', exact: true }) + const placeholder = page.locator('[data-composer-placeholder]') + await input.waitFor() + expect(await placeholder.locator('kbd').allTextContents()).toEqual(['/', '@']) + expect((await input.innerText()).trim()).toBe('') + const captureInput = () => captureStableAria(page, '[data-composer-input]', scaffold.workspaceCwd) + const shortcutsAria = await captureInput() + + await input.focus() + const editor = page.locator('[data-composer-input]') + await editor.dispatchEvent('compositionstart') + await placeholder.waitFor({ state: 'hidden' }) + await editor.dispatchEvent('compositionend', { data: '' }) + await placeholder.waitFor({ state: 'visible' }) + + await editor.fill('/plan ') + await editor.press('Enter') + const planButton = page.getByRole('button', { name: 'Plan mode on, press to turn off', exact: true }) + const planInput = page.getByRole('textbox', { + name: 'Plan outline Goal · Constraints · Success criteria', exact: true, + }) + await planButton.waitFor() + await planInput.waitFor() + const outline = placeholder.locator('[data-demo-composer-plan]') + for (const step of ['Goal', 'Constraints', 'Success criteria']) { + expect(await outline.getByText(step, { exact: true }).isVisible()).toBe(true) + } + const planAria = await captureInput() + await planButton.click() + await planButton.waitFor({ state: 'hidden' }) + await input.waitFor() + expect(await placeholder.locator('kbd').allTextContents()).toEqual(['/', '@']) + + const session = await page.locator('[data-conversation-session]').getAttribute('data-conversation-session') + if (session === null || session === '') throw new Error('The composer has no Session ID') + const patchFile = join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml') + const parsed = parseEntryYaml(await readFile(patchFile, 'utf8')) + if (!Array.isArray(parsed)) throw new Error('The scaffold profile patch is not a list') + const profilePatches: readonly unknown[] = parsed + const configureReviewSession = (sessionId: string) => writeFile(patchFile, stringifyEntryYaml([ + ...profilePatches, + { id: 'demo-composer-review-session', config: { sessionId } }, + ])) + const reviewInput = page.getByRole('textbox', { + name: 'Review Changes Risks Tests', exact: true, + }) + await configureReviewSession(session) + await reviewInput.waitFor() + const reviewSteps = placeholder.locator('[data-demo-review-path] [data-demo-review-step]') + expect(await reviewSteps.allTextContents()).toEqual(['Changes', 'Risks', 'Tests']) + const reviewAria = await captureInput() + + await configureReviewSession(`${session}-other`) + await input.waitFor() + await configureReviewSession(session) + await reviewInput.waitFor() + + const plugins = await newEnglishPage(browser) + await plugins.goto(scaffold.authenticatedUrl) + await plugins.getByRole('button', { name: 'Plugins', exact: true }).click() + await plugins.getByRole('switch', { name: 'Enable @fixture/composer-review-session', exact: true, checked: true }).click() + await input.waitFor() + await plugins.getByRole('switch', { name: 'Enable @fixture/composer-shortcuts', exact: true, checked: true }).click() + const homePrompt = 'Describe what you want to build, / commands, @ files or sessions' + await page.getByRole('textbox', { name: homePrompt, exact: true }).waitFor() + expect(await placeholder.innerText()).toBe(homePrompt) + expect(await placeholder.locator('kbd').count()).toBe(0) + await compareOrRefreshGolden(fileURLToPath(new URL('./expected/input-plugin-placeholder.expected.md', import.meta.url)), + [shortcutsAria, planAria, reviewAria, await captureInput()].join('\n'), webSnapshotMode()) + expect(tripwire.pageErrors).toEqual([]) +}) + it('expands an input activity and inserts one undoable result without overwriting subsequent edits', async () => { - const { scaffold, page, tripwire } = await fixture(true) + const { scaffold, page, tripwire } = await fixture([{ dir: bundle, enabled: true }]) await connectFreshWorkspace(page, scaffold.workspaceCwd) const input = page.locator('[data-composer-input]') const start = page.getByRole('button', { name: 'Input activity', exact: true }) @@ -61,7 +153,7 @@ it('expands an input activity and inserts one undoable result without overwritin }) it('offers bundle guidance only after explicit activation and navigates to its configuration', async () => { - const { page, tripwire } = await fixture(false) + const { page, tripwire } = await fixture([{ dir: bundle, enabled: false }]) await page.getByRole('button', { name: 'Plugins', exact: true }).click() const toggle = page.getByRole('switch', { name: 'Enable @fixture/input-extension', exact: true }) await toggle.waitFor() diff --git a/apps/web/tests/markdown-wide-table.e2e.ts b/apps/web/tests/markdown-wide-table.e2e.ts index 16e45fd37a..f77ce2b3a9 100644 --- a/apps/web/tests/markdown-wide-table.e2e.ts +++ b/apps/web/tests/markdown-wide-table.e2e.ts @@ -216,13 +216,13 @@ async function awaitTableLayout(target: Page): Promise { const element = document.querySelector('[data-sidebar-collapsed][data-rightbar-collapsed]') if (element === null) return false const tracks = getComputedStyle(element).gridTemplateColumns.split(' ').map(Number.parseFloat) - const root = element.querySelector('div[data-phase]') + const body = element.querySelector('div[data-phase] [data-conversation-content]') // Desktop retains the rail; the mobile drawer leaves the whole width to the transcript. return tracks[0] === (element.hasAttribute('data-sidebar-drawer') ? 0 : 56) && tracks.at(-1) === 0 && element.getAnimations().every(animation => animation.playState === 'finished' || animation.playState === 'idle') - && root !== null - && root.style.getPropertyValue('--dsh-conversation-column-width') === `${String(root.offsetWidth)}px` + && body !== null + && body.style.getPropertyValue('--dsh-conversation-column-width') === `${String(body.offsetWidth)}px` }, undefined, { timeout: 10_000 }) } diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 3c2b3ff0fc..b6da142437 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -543,6 +543,46 @@ describe('web e2e: Models settings page configures a dormant provider', () => { expect(tripwire.pageErrors).toEqual([]) }, 60_000) + it('replaces an installed catalog model\'s reasoning levels and returns to them when switched off', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-models-catalog-reasoning')) + await scaffold.ctx.settings.mutate('llm-pi-ai', [{ + op: 'set', path: ['providers', 'openai'], value: { models: [{ id: 'gpt-6-astra', name: 'GPT-6 Astra' }] }, + }]) + const dialog = page.getByRole('dialog', { name: '设置' }) + const edit = dialog.getByRole('button', { name: '编辑 openai', exact: true }) + const toggle = dialog.getByRole('switch', { name: '推理等级 1' }) + const efforts = async (): Promise => + (await scaffold.ctx.llm.resolveModelInfo('openai', 'gpt-6-astra')).reasoning?.efforts.map(effort => String(effort.id)) ?? [] + const openModelOptions = async (): Promise => { + await edit.click() + await dialog.getByText('自定义设置').click() + await dialog.getByRole('button', { name: '模型选项 1' }).click() + } + try { + const inherited = await efforts() + expect(inherited).toContain('max') + await openModelOptions() + expect(await toggle.getAttribute('aria-checked')).toBe('false') + await toggle.click() + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await toggle.waitFor({ state: 'detached' }) + expect(await efforts()).toEqual(['off', 'low', 'medium', 'high']) + // The saved notice confirms the browser directory refresh, so the reopened draft holds the stored levels. + await dialog.getByText('已保存 openai。', { exact: true }).waitFor({ timeout: 10_000 }) + + await openModelOptions() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await toggle.click() + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await toggle.waitFor({ state: 'detached' }) + expect(await efforts()).toEqual(inherited) + } finally { + await scaffold.ctx.settings.mutate('llm-pi-ai', [{ op: 'unset', path: ['providers', 'openai'] }]) + await edit.waitFor({ state: 'detached' }) + } + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + it('saves model drag order, discards canceled moves, and preserves the other provider', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-order')) const dialog = page.getByRole('dialog', { name: '设置' }) diff --git a/apps/web/tests/reference-composer.e2e.ts b/apps/web/tests/reference-composer.e2e.ts index 0931c525f4..47cdb171ed 100644 --- a/apps/web/tests/reference-composer.e2e.ts +++ b/apps/web/tests/reference-composer.e2e.ts @@ -311,6 +311,23 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through expect(tripwire.warnings).toEqual([]) }) + it('keeps a file path typed by hand in typed order', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-typed-path')) + const input = page.locator('[data-composer-input]').first() + + // No menu pick: every character of the path arrives as its own key press. + await writeComposerDraft(page, input, '@folderx/nested/leaf.txt') + await expect.poll(() => input.textContent()).toBe('@folderx/nested/leaf.txt') + // The caret follows the last character, and the sentence's period stays outside the reference. + await page.keyboard.type('. Done') + await expect.poll(() => input.textContent()).toBe('@folderx/nested/leaf.txt. Done') + await expect.poll(() => input.locator('[data-composer-text-ref]').allTextContents()) + .toEqual(['@folderx/nested/leaf.txt']) + + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + it('settles a folder as an atomic chip; Tab and the chevron drill instead', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-folder')) const input = page.locator('[data-composer-input]').first() diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 2928f03842..6a37c2c37b 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -164,6 +164,7 @@ async function hitsItself(locator: Locator): Promise { * surface and release over the conversation. */ async function floatByDrag(page: Page, tab: Locator): Promise { + await tab.hover({ trial: true }) const surface = page.locator('[data-dockkit-surface]').first() const box = await surface.boundingBox() if (box === null) throw new Error('surface is not rendered') @@ -474,7 +475,10 @@ describe('web e2e: shipped right Sidebar', () => { } await expect.poll(async () => await tabTitles(column)).toEqual(['Start']) - await expectTitleAlignment(column.locator('[data-dockkit-tab-title]')) + const guideTitle = column.locator('[data-dockkit-tab-title]') + await expectTitleAlignment(guideTitle) + // Even this short, unclosable title has the ordinary edge mask, not the close-button mask. + expect(await guideTitle.evaluate(el => getComputedStyle(el).maskImage)).toContain('16px') await expect.poll(async () => await column.locator('[data-sidebar-right-guide-entry]').count()).toBe(2) expect(await column.locator('[data-sidebar-right-guide-entry="browser"]').count()).toBe(0) await column.locator('[data-sidebar-right-guide-entry="files"]').click() @@ -484,7 +488,9 @@ describe('web e2e: shipped right Sidebar', () => { const addTab = column.locator('[data-dockkit-add-tab]') const filesTab = column.locator('[data-dockkit-tab]').filter({ hasText: 'Files' }) await expect.poll(async () => await tabTitles(column)).toEqual(['Files']) - await expectTitleAlignment(filesTab.locator('[data-dockkit-tab-title]')) + const filesTitle = filesTab.locator('[data-dockkit-tab-title]') + await expectTitleAlignment(filesTitle) + expect(await filesTitle.evaluate(el => getComputedStyle(el).maskImage)).toContain('14px') await column.locator('[data-files-state="tree"]').waitFor({ state: 'visible' }) expect(await filesTab.locator('[data-dockkit-tab-close]').count()).toBe(1) await expect.poll(async () => await addTab.count()).toBe(1) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index cd716a0177..178a4e83c0 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -32,6 +32,7 @@ "tests/sidebar-drawer.e2e.ts", "tests/session-panel-layout.e2e.ts", "tests/creation-recommendations.e2e.ts", + "tests/cordis-inspect-subagent.e2e.ts", "tests/plugin-recommendations.e2e.ts", "tests/deepseek-chat-import.e2e.ts", "tests/japanese-plugin-metadata.e2e.ts", @@ -270,6 +271,7 @@ "tests/chat-scroll-contract.e2e.ts", "tests/chat-long-interactions.e2e.ts", "tests/chat-continuous-conversation.e2e.ts", + "tests/composer-history.e2e.ts", "tests/composer-tab-geometry.e2e.ts", "tests/conversation-view-tabs.e2e.ts", "tests/window-drag-coverage.e2e.ts", diff --git a/benchmarks/AGENTS.md b/benchmarks/AGENTS.md index eda9f8cad3..8e8cd5fbbe 100644 --- a/benchmarks/AGENTS.md +++ b/benchmarks/AGENTS.md @@ -8,7 +8,7 @@ This tree owns required, repository-level performance gates whose measured user - Browser workflow cases drive built Client bundles through the shared shipped-composition Web scaffold. Report its source-resolved test Host separately from published-Host evidence; two animation frames prove a rendering opportunity, not hardware presentation. Use fresh browsers and private scaffold worlds per sample. - Synthesize fixed inputs from reviewed constants. Never use recorded Sessions, user material, ambient repositories, or network services. - Run process-level wall-clock and retained-memory samples in fresh children with private `mkdtemp` roots. Pure synchronous folds create a fresh object graph per sample and must not mutate process-global state. Bound every child, await exit, and remove owned roots after failure as well as success. -- Pass every budgeted wall-clock endpoint to `recordTimings` from `support/scaling-report.ts` before asserting it, with a `BenchmarkCase` stating what it measures and which user scenario it affects. Give each endpoint its process CPU time over the same interval when the worker can measure it, otherwise a commented storage-wait share; omit endpoints that include paced or fixed waits. Pass whole-process peak RSS to `recordPeakMemory`. Profiles live in `support/machine-profiles.ts`; each run writes `.dsh-report/report.html`, which the `node 24 / benchmarks` job publishes as the `benchmark-report` artifact. +- Pass every budgeted wall-clock endpoint to `recordTimings` from `support/scaling-report.ts` before asserting it, with a `BenchmarkCase` stating what it measures and which user scenario it affects. Give each endpoint its process CPU time over the same interval when the worker can measure it, otherwise a commented storage-wait share; omit endpoints that include paced or fixed waits. Pass whole-process peak RSS to `recordPeakMemory`. Profiles live in `support/machine-profiles.ts`; each run writes `.dsh-report/report.html`, and CI renders one page from both benchmark phase jobs in `node 24 / benchmark report`, published as the `benchmark-report` artifact. - Record reference-machine expectations separately from the shared CI time scale and variance headroom. Do not apply the time scale to memory or dimensionless ratios. - Report enough raw and aggregate measurements to explain each verdict, including whether a budget uses a median, minimum, absolute value, or ratio. Enforce reviewed source constants; environment variables must not override performance budgets. - Keep scenario-specific support beside its benchmark. Move a helper into `benchmarks/support/` only after at least two benchmark directories require the same behavior. diff --git a/benchmarks/rightbar-drag-browser/README.i18n.yaml b/benchmarks/rightbar-drag-browser/README.i18n.yaml new file mode 100644 index 0000000000..d7a6028a8d --- /dev/null +++ b/benchmarks/rightbar-drag-browser/README.i18n.yaml @@ -0,0 +1,13 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write benchmarks/rightbar-drag-browser/README.md +/right-sidebar-drag-browser-benchmark: + en: 0ec06c11a4e9680c + zh: 2aa104d63575bfcf +/right-sidebar-drag-browser-benchmark/run: + en: 0dce8b92617ea78b + zh: 22ce9ccc29acda36 +/right-sidebar-drag-browser-benchmark/measurements: + en: a46b806f1f9ae765 + zh: f4a81542a960a55c diff --git a/benchmarks/rightbar-drag-browser/README.md b/benchmarks/rightbar-drag-browser/README.md new file mode 100644 index 0000000000..678d9fbea0 --- /dev/null +++ b/benchmarks/rightbar-drag-browser/README.md @@ -0,0 +1,24 @@ +# Right Sidebar drag browser benchmark + +English | [中文](README.zh.md) + +The required Chromium case in [rightbar-drag.bench.ts](rightbar-drag.bench.ts) drags the right Sidebar's resize handle beside a synthetic 120-turn Session whose older pages are all loaded, and counts restyled elements and layouts during the drag. The shipped Web scaffold owns the isolated home, persistence, and loopback listener; Chromium loads the built Web artifacts. + +## Run + +`pnpm run test:bench` builds libraries, workers, and Web artifacts before running the serial benchmark inventory. With artifacts already built, select this directory through `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/rightbar-drag-browser`. A shell that exports `NODE_USE_ENV_PROXY` unsets it first, as the [test proxy setup](../../scripts/test-proxy-environment.ts) requires. + +## Measurements + +Each Chromium trace spans one trusted drag through two animation frames after release. The benchmark uses two fresh browser processes and scaffold worlds, with the Session panel hidden. + +- **Changing column:** Each sample widens the right Sidebar by 40 steps of 8px and drags it back in a 1680×1000 viewport. The rendered transcript column must narrow as the Sidebar widens and widen on return; both endpoints must be below the 680px content-width floor. +- **Fixed column:** The first sample also opens the same 120 turns in a separate page with fresh storage, a 2560×1000 viewport and a saved 720px content width. After the opening slide settles, the visible Sidebar must reach each of 40 steps of 2px, from 1152px to 1232px and back. Every delivered transcript column width must be 720px. The Session panel's reserve-room value at its dock probe must switch from 1px to 0px and back. + +- **Restyles:** Sum the elements reported by each style recalculation and divide by the page's element count. For the changing column, the upper median per direction must not exceed 1 (one page's worth). For the fixed column, each direction must not exceed 0.10. +- **Individual style passes:** Every sample prints `restylePassesByElementCount`: a bucket such as `"3": 40` means 40 complete Chromium `UpdateLayoutTree` events each reported three restyled elements. These are element visits, not distinct DOM nodes across a drag or invalidation reasons. `peakStyledElements` is the largest count in one event; `peakCountPassMs` is the duration of that event (the longer duration wins a tie). Each fixed-column direction must keep every pass at or below 512 elements, even if the cumulative ratio passes. +- **Layouts:** Each changing-column drag must produce at least one `Layout` event. `layoutCount` includes them all; `scriptNestedLayoutCount` counts each layout fully enclosed by a script event on the same process and thread, including animation frame callbacks. This subset must not exceed 20 per drag (half the mouse steps). Nesting is a proxy for synchronous layout, not evidence that every nested layout is unnecessary; browser reflow outside script does not consume the budget. + +The p95 and longest animation-frame gaps (`frameP95Ms`, `maxFrameGapMs`) span the gesture through the two frames after release, excluding trace startup and decoding. Frame gaps and style and layout durations are diagnostics only; the work-count budgets do not scale with CPU speed. + +The fixture contains mixed-language prose, lists, 12 code fences, 8 tables, reasoning, and 24 tool results. No model, tool, external network, recorded Session, or private Harness home supplies its content. The [decision record](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md) owns the workload choice, calibration, alternatives, and exclusions. diff --git a/benchmarks/rightbar-drag-browser/README.zh.md b/benchmarks/rightbar-drag-browser/README.zh.md new file mode 100644 index 0000000000..22763db2df --- /dev/null +++ b/benchmarks/rightbar-drag-browser/README.zh.md @@ -0,0 +1,24 @@ +# 右侧栏拖动浏览器基准 + +[English](README.md) | 中文 + +[rightbar-drag.bench.ts](rightbar-drag.bench.ts) 中的必需 Chromium 用例在一个已加载全部更早分页的 120 轮合成会话旁拖动右侧栏的宽度拖拽条,并统计拖动期间重算样式的元素数和布局次数。随产品发布的 Web 测试脚手架提供隔离的 home、持久化和回环监听;Chromium 加载已构建的 Web 产物。 + +## 运行 + +`pnpm run test:bench` 先构建库、worker 和 Web 产物,再运行串行基准清单。产物已构建时,可通过 `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/rightbar-drag-browser` 只运行本目录。导出了 `NODE_USE_ENV_PROXY` 的 shell 需要先取消它,这是[测试代理设置](../../scripts/test-proxy-environment.ts)的要求。 + +## 测量 + +每次 Chromium 追踪覆盖一次真实鼠标拖动,直到松开后的两个动画帧。基准使用两个全新的浏览器进程和脚手架环境,均隐藏会话面板。 + +- **列宽变化:** 每个样本都在 1680×1000 视口中把右侧栏加宽 40 步(每步 8px),再拖回。实际渲染的正文列必须随侧栏加宽而变窄、随侧栏缩窄而变宽;起止列宽都必须低于 680px 的正文宽度下限。 +- **列宽固定:** 第一个样本还在单独页面中打开相同的 120 轮记录;该页面使用独立存储,视口为 2560×1000,预存的正文宽度为 720px。侧栏展开动画结束后,从 1152px 到 1232px 再拖回,每个方向 40 步,每步 2px,可见侧栏必须逐步到达目标宽度。每次观察到的正文列宽都必须是 720px。会话面板的停靠探针上,标记预留空间是否足够的值必须从 1px 变为 0px,再变回 1px。 + +- **样式重算:** 各次样式重算报告的元素数之和除以页面元素数。列宽变化时,每个方向的上中位数不得超过 1(即一整个页面的元素数)。列宽固定时,每个方向的比值不得超过 0.10。 +- **单次样式重算:** 每个样本都输出 `restylePassesByElementCount`。例如 `"3": 40` 表示 Chromium 有 40 个完整的 `UpdateLayoutTree` 事件各自重算了 3 个元素。这不是整段拖动去重后的 DOM 节点数,也不是失效原因条数。`peakStyledElements` 是单个事件的最大元素数;`peakCountPassMs` 是该事件的耗时(元素数并列时取较长者)。正文固定时,加宽和缩窄的每次重算都不得超过 512 个元素,即使累计比值合格也一样。 +- **布局:** 列宽变化时,每次拖动必须产生至少一个 `Layout` 事件。`layoutCount` 统计所有布局;`scriptNestedLayoutCount` 只统计起止时间均落在同一进程、同一线程的脚本事件内的布局,每次布局只计一次,动画帧回调也算脚本事件。每次拖动此项不得超过 20(鼠标步数的一半)。嵌套关系是判断同步布局的间接指标,并不说明每次嵌套布局都多余;脚本以外的浏览器重排不占用该预算。 + +帧间隔的 p95 和最大值(`frameP95Ms`、`maxFrameGapMs`)覆盖手势至松开后两个动画帧,不包含追踪启动和解析。帧间隔、样式重算耗时和布局耗时仅作诊断;工作量预算不随 CPU 速度缩放。 + +夹具包含中英混排的正文、列表、12 个代码块、8 个表格、推理内容和 24 个工具结果。内容不来自任何模型、工具、外部网络、录制会话或私有 Harness home。[决策记录](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md)负责说明负载选择、校准、备选方案和排除项。 diff --git a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts new file mode 100644 index 0000000000..51257d0c99 --- /dev/null +++ b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts @@ -0,0 +1,362 @@ +/** Required browser budgets for restyles and script-nested layout while dragging the right Sidebar beside a long history. */ +import { chromium, type Browser, type Page } from 'playwright' +import { expect, it } from 'vitest' +import { launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from '../../apps/web/tests/scaffold.ts' +import { newEnglishPage } from '../../apps/web/tests/support.ts' +import { HISTORY_TURNS, SESSION_ID, syntheticHistory } from './synthetic-history.ts' + +const SAMPLES = 2 +/** Below the content width's 680px floor at this width, so the drag changes the column but not the resolved content width. */ +const VIEWPORT = { width: 1680, height: 1000 } +const CONTENT_WIDTH_FLOOR_PX = 680 +const FIXED_VIEWPORT = { width: 2560, height: 1000 } +const FIXED_COLUMN_PX = 720 +const FIXED_PANEL_START_PX = 1152 +const FIXED_STEP_PX = 2 +const FIXED_RESTYLE_BUDGET = 0.1 +/** One fixed-column style pass, independent of the cumulative page-ratio budget. */ +const FIXED_PEAK_ELEMENT_BUDGET = 512 +const STEPS = 40 +const STEP_PX = 8 +const STEP_GAP_MS = 8 +const TAIL = '[data-chat-flow-key*="turn-tail"]' +/** + * Elements restyled over one whole drag, as a multiple of the page's elements. A drag that restyles the + * transcript on every frame reaches about one multiple per frame; one that restyles only what the resize + * changes stays far below a single multiple. + */ +const RESTYLE_BUDGET = 1 +/** The regression put one layout inside script per step; occasional script-nested layouts need not be waste. */ +const SCRIPT_NESTED_LAYOUT_BUDGET = STEPS / 2 +const SCRIPT_EVENTS = new Set(['FunctionCall', 'EventDispatch', 'FireAnimationFrame', 'TimerFire', 'RunMicrotasks', 'v8.callFunction']) + +interface TraceEvent { + name: string + ph: string + pid: number + tid: number + ts: number + dur?: number + args?: { elementCount?: number } +} + +interface TraceSummary { + styledElements: number + /** Element count → number of completed UpdateLayoutTree events reporting that count. */ + restylePassesByElementCount: Record + peakStyledElements: number + /** Duration of the pass with the highest element count; the longer pass wins ties. */ + peakCountPassMs: number + styleMs: number + layoutMs: number + layoutCount: number + scriptNestedLayoutCount: number +} + +interface DragSample extends TraceSummary { + restyleRatio: number + frameP95Ms: number + maxFrameGapMs: number + columnWidthBefore: number + columnWidth: number +} + +function expectRestylesWithinBudget(ratio: number, budget = RESTYLE_BUDGET): void { + expect(ratio).toBeLessThanOrEqual(budget) +} + +function expectFixedPeakWithinBudget(count: number): void { + expect(count, 'most elements restyled in one fixed-column UpdateLayoutTree event').toBeLessThanOrEqual(FIXED_PEAK_ELEMENT_BUDGET) +} + +function median(values: number[]): number { + return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]! +} + +/** Style recalculation and layout totals from a Chromium timeline trace. */ +function summarizeTrace(buffer: Buffer): TraceSummary { + const parsed = JSON.parse(buffer.toString('utf8')) as { traceEvents: TraceEvent[] } | TraceEvent[] + const events = (Array.isArray(parsed) ? parsed : parsed.traceEvents).filter(event => event.ph === 'X') + const styles = events.filter(event => event.name === 'UpdateLayoutTree') + const layouts = events.filter(event => event.name === 'Layout') + const scripts = events.filter(event => SCRIPT_EVENTS.has(event.name)) + expect(scripts.length, 'drag trace must contain script events').toBeGreaterThan(0) + const end = (event: TraceEvent): number => event.ts + (event.dur ?? 0) + const ms = (list: TraceEvent[]): number => list.reduce((total, event) => total + (event.dur ?? 0), 0) / 1000 + const restylePassesByElementCount: Record = {} + let styledElements = 0 + let peakStyledElements = 0 + let peakCountPassMs = 0 + for (const event of styles) { + const count = event.args?.elementCount + if (count === undefined || !Number.isSafeInteger(count) || count < 0) { + throw new Error('Chromium UpdateLayoutTree is missing a valid elementCount') + } + const passMs = (event.dur ?? 0) / 1000 + restylePassesByElementCount[count] = (restylePassesByElementCount[count] ?? 0) + 1 + styledElements += count + if (count > peakStyledElements || (count === peakStyledElements && passMs > peakCountPassMs)) { + peakStyledElements = count + peakCountPassMs = passMs + } + } + return { + styledElements, restylePassesByElementCount, peakStyledElements, peakCountPassMs, + styleMs: ms(styles), + layoutMs: ms(layouts), + layoutCount: layouts.length, + scriptNestedLayoutCount: layouts.filter(layout => scripts.some(script => + script.pid === layout.pid && script.tid === layout.tid && script.ts <= layout.ts && end(layout) <= end(script), + )).length, + } +} + +async function loadAll(page: Page): Promise { + let count = await page.locator(TAIL).count() + while (count < HISTORY_TURNS) { + await page.getByRole('button', { name: 'Load earlier', exact: true }).click() + await page.waitForFunction( + ({ selector, previous }) => document.querySelectorAll(selector).length > previous, + { selector: TAIL, previous: count }, + ) + count = await page.locator(TAIL).count() + } + return count +} + +async function openLoadedSidebar(page: Page, url: string): Promise { + page.setDefaultTimeout(60_000) + await page.goto(url, { waitUntil: 'load' }) + await page.getByRole('treeitem').first().click() + await page.getByRole('treeitem').nth(1).click() + await page.locator(TAIL).last().waitFor() + expect(await loadAll(page)).toBe(HISTORY_TURNS) + await page.getByRole('button', { name: 'Open right sidebar' }).first().click() + await page.locator('[data-side="rightbar"]').waitFor() + // The Sidebar opens with a track transition; the drag starts from its settled width. + await page.waitForFunction(() => document.querySelector('[data-rightbar-collapsed], [data-animating]') === null) + return page.evaluate(() => document.querySelectorAll('*').length) +} + +/** Frame timestamps the page collects during one drag. */ +type FrameProbe = Window & { benchmarkFrames?: { frames: number[]; running: boolean } } +type FixedWidthProbe = typeof window & { benchmarkWidths: { column: Set; panel: number } } + +async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: number, fixedPanelStart?: number): Promise { + const box = await page.locator('[data-side="rightbar"]').boundingBox() + if (box === null) throw new Error('right Sidebar resize handle missing') + const x = box.x + box.width / 2 + const y = box.y + box.height / 2 + const readColumnWidth = (): Promise => page.locator('[data-chat-flow]').first().evaluate(element => element.getBoundingClientRect().width) + const columnWidthBefore = await readColumnWidth() + await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] }) + await page.evaluate(() => new Promise((resolve) => { + const probe = { frames: [] as number[], running: true } + ;(window as FrameProbe).benchmarkFrames = probe + const tick = (time: number): void => { + if (!probe.running) return + probe.frames.push(time) + requestAnimationFrame(tick) + } + requestAnimationFrame((time) => { tick(time); resolve() }) + })) + await page.mouse.move(x, y) + await page.mouse.down() + for (let step = 1; step <= STEPS; step++) { + const delta = direction * step * (fixedPanelStart === undefined ? STEP_PX : FIXED_STEP_PX) + await page.mouse.move(x - delta, y) + if (fixedPanelStart === undefined) await page.waitForTimeout(STEP_GAP_MS) + else { + // Observe the actual panel before sending the next move; a freeze or coalesced drag must not reduce the work count. + await page.waitForFunction(width => (window as FixedWidthProbe).benchmarkWidths.panel === width, fixedPanelStart + delta) + } + } + await page.mouse.up() + // Two animation frames let the release reach style and layout before the trace closes. + const frames = await page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => { + const probe = (window as FrameProbe).benchmarkFrames! + probe.running = false + resolve(probe.frames) + })) + })) + const trace = summarizeTrace(await browser.stopTracing()) + const gaps = frames.slice(1).map((time, index) => time - frames[index]!).sort((a, b) => a - b) + return { + ...trace, + restyleRatio: trace.styledElements / elements, + frameP95Ms: gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * 0.95))] ?? 0, + maxFrameGapMs: gaps.at(-1) ?? 0, + columnWidthBefore, + columnWidth: await readColumnWidth(), + } +} + +async function measureFixedColumn(browser: Browser, url: string): Promise { + const page = await newEnglishPage(browser, FIXED_VIEWPORT.height) + try { + const consoleWatch = watchConsole(page) + await page.setViewportSize(FIXED_VIEWPORT) + await page.addInitScript(width => { localStorage.setItem('dsh.conversation.contentWidth', String(width)) }, FIXED_COLUMN_PX) + const elements = await openLoadedSidebar(page, url) + const panelSelector = '[data-sidebar-right-panel="push"][data-sidebar-right-open]' + const panel = page.locator(panelSelector) + // The sliding dock items animate inside the panel, independently of its grid track. + await panel.evaluate(async node => { + await Promise.all(node.getAnimations({ subtree: true }).filter(animation => animation instanceof CSSTransition && animation.transitionProperty === 'transform').map(animation => animation.finished)) + }) + await page.evaluate(selector => { + const panel = document.querySelector(selector)! + const column = document.querySelector('[data-chat-flow]')! + const widths = { column: new Set(), panel: 0 } + ;(window as FixedWidthProbe).benchmarkWidths = widths + // Use delivered border boxes rather than forcing layout from a per-frame geometry read. + const observer = new ResizeObserver(entries => { + for (const entry of entries) { + const width = entry.borderBoxSize[0]!.inlineSize + if (entry.target === panel) widths.panel = width + else widths.column.add(width) + } + }) + observer.observe(panel, { box: 'border-box' }) + observer.observe(column, { box: 'border-box' }) + }, panelSelector) + await page.waitForFunction(() => (window as FixedWidthProbe).benchmarkWidths.column.size > 0) + const reserveRoom = (): Promise => page.locator('[data-session-panel-probe]').first().evaluate(node => + getComputedStyle(node).getPropertyValue('--dsh-session-panel-reserve-room').trim()) + let panelStart = FIXED_PANEL_START_PX + for (const direction of [1, -1] as const) { + expect(await page.evaluate(() => (window as FixedWidthProbe).benchmarkWidths.panel)).toBe(panelStart) + const reserveBefore = await reserveRoom() + const result = await drag(browser, page, direction, elements, panelStart) + const reserveAfter = await reserveRoom() + const geometry = await page.evaluate(() => { + const { panel, column } = (window as FixedWidthProbe).benchmarkWidths + return { panelWidth: panel, columnWidths: [...column] } + }) + console.log(JSON.stringify({ + benchmark: 'rightbar-drag-browser/fixed-column', direction, elements, + budget: FIXED_RESTYLE_BUDGET, peakElementBudget: FIXED_PEAK_ELEMENT_BUDGET, + panelStart, ...geometry, reserveBefore, reserveAfter, ...result, + })) + panelStart += direction * STEPS * FIXED_STEP_PX + expect(geometry.panelWidth).toBe(panelStart) + expect(geometry.columnWidths).toEqual([FIXED_COLUMN_PX]) + expect([result.columnWidthBefore, result.columnWidth]).toEqual([FIXED_COLUMN_PX, FIXED_COLUMN_PX]) + expect([reserveBefore, reserveAfter]).toEqual(direction === 1 ? ['1px', '0px'] : ['0px', '1px']) + expect(result.styledElements).toBeGreaterThan(0) + expectFixedPeakWithinBudget(result.peakStyledElements) + expectRestylesWithinBudget(result.restyleRatio, FIXED_RESTYLE_BUDGET) + } + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await page.close() + } +} + +it('accepts recorded restyle ratios and rejects a drag that restyles the transcript every frame', () => { + // 200-turn local samples: 1,479,947 and 1,909,568 elements restyled beside 28,895 before the width axis + // kept resize inputs on the Conversation body; 2,622 and 3,368 after. + for (const restyled of [1_479_947, 1_909_568]) expect(() => expectRestylesWithinBudget(restyled / 28_895)).toThrow() + for (const restyled of [2_622, 3_368]) expectRestylesWithinBudget(restyled / 28_895) + expectRestylesWithinBudget(RESTYLE_BUDGET) + expect(() => expectRestylesWithinBudget(RESTYLE_BUDGET + 0.01)).toThrow() +}) + +it('rejects the fixed-column drag that restyled the transcript when reserve room flipped', () => { + const elements = 18_428 + expect(() => expectRestylesWithinBudget(18_239 / elements, FIXED_RESTYLE_BUDGET)).toThrow() + for (const restyled of [380, 379]) expectRestylesWithinBudget(restyled / elements, FIXED_RESTYLE_BUDGET) +}) + +/** A Chromium trace fragment with completed style passes and a separate invalidation notification. */ +function restyleTrace(passes: readonly (readonly [number | undefined, number])[]): TraceSummary { + const span = { pid: 1, tid: 1, ph: 'X' } + const events = [ + { ...span, ts: 0, name: 'FunctionCall', dur: 1 }, + { ...span, ts: 0, ph: 'I', name: 'ScheduleStyleInvalidationTracking', args: { elementCount: 99_999 } }, + ...passes.map(([elementCount, dur], index) => ({ + ...span, ts: (index + 1) * 10_000, name: 'UpdateLayoutTree', dur, args: { elementCount }, + })), + ] + return summarizeTrace(Buffer.from(JSON.stringify({ traceEvents: events }))) +} + +it('reports the breadth of each style pass and the duration of the broadest pass, not the slowest pass', () => { + expect(restyleTrace([[3, 9_000], [14_911, 1_200], [3, 500], [14_911, 2_300], [0, 100]])).toMatchObject({ + styledElements: 29_828, + restylePassesByElementCount: { 0: 1, 3: 2, 14911: 2 }, + peakStyledElements: 14_911, + peakCountPassMs: 2.3, + }) + expect(() => restyleTrace([[undefined, 100]])).toThrow('elementCount') +}) + +it('distinguishes one oversized style pass from the same total work spread over small passes', () => { + const elements = 18_428 + const distributed = restyleTrace(Array.from({ length: 200 }, () => [3, 100] as const)) + const spike = restyleTrace([[600, 100]]) + for (const result of [distributed, spike]) { + expect(result.styledElements).toBe(600) + expectRestylesWithinBudget(result.styledElements / elements, FIXED_RESTYLE_BUDGET) + } + expectFixedPeakWithinBudget(distributed.peakStyledElements) + expect(() => expectFixedPeakWithinBudget(spike.peakStyledElements)).toThrow() +}) + +it('counts each layout enclosed by script on the same thread once, including frame callbacks', () => { + const event = (name: string, ts: number, dur: number, pid = 1, tid = 1): TraceEvent => ({ name, ph: 'X', ts, dur, pid, tid }) + const events = [ + event('FireAnimationFrame', 10, 10), event('FunctionCall', 11, 5), + event('Layout', 10, 10), event('Layout', 12, 1), + event('Layout', 19, 2), event('Layout', 12, 1, 2, 1), event('Layout', 12, 1, 1, 2), + event('PrePaint', 30, 5), event('Layout', 31, 1), + ] + expect(summarizeTrace(Buffer.from(JSON.stringify(events)))).toMatchObject({ layoutCount: 6, scriptNestedLayoutCount: 2 }) +}) + +it(`bounds restyles and script-nested layouts while the right Sidebar is dragged beside ${String(HISTORY_TURNS)} turns`, async () => { + if (webSnapshotMode() !== 'replay') throw new Error('browser benchmarks require keyless replay mode') + const samples: Record<'widen' | 'narrow', DragSample[]> = { widen: [], narrow: [] } + for (let sample = 0; sample < SAMPLES; sample++) { + const failures: unknown[] = [] + // The scaffold owns a private home, persistence root, and loopback listener for this sample. + const scaffold = await launchWebScaffold() + try { + await seedSession(scaffold, syntheticHistory(), SESSION_ID) + const browser = await chromium.launch({ headless: true }) + try { + if (sample === 0) await measureFixedColumn(browser, scaffold.authenticatedUrl) + const page = await newEnglishPage(browser, VIEWPORT.height) + await page.setViewportSize(VIEWPORT) + const consoleWatch = watchConsole(page) + const elements = await openLoadedSidebar(page, scaffold.authenticatedUrl) + for (const [direction, key] of [[1, 'widen'], [-1, 'narrow']] as const) { + const result = await drag(browser, page, direction, elements) + console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/sample', sample, direction: key, elements, ...result })) + // The transcript column moves opposite the Sidebar width while the resolved content width stays at its floor. + expect(Math.max(result.columnWidthBefore, result.columnWidth)).toBeLessThan(CONTENT_WIDTH_FLOOR_PX) + if (key === 'widen') expect(result.columnWidth).toBeLessThan(result.columnWidthBefore) + else expect(result.columnWidth).toBeGreaterThan(result.columnWidthBefore) + expect(result.styledElements).toBeGreaterThan(0) + expect(result.layoutCount).toBeGreaterThan(0) + expect(result.scriptNestedLayoutCount).toBeLessThanOrEqual(SCRIPT_NESTED_LAYOUT_BUDGET) + samples[key].push(result) + } + expect(consoleWatch.pageErrors).toEqual([]) + } catch (error) { failures.push(error) } finally { + await browser.close().catch((error: unknown) => failures.push(error)) + } + } catch (error) { failures.push(error) } finally { + await scaffold.close().catch((error: unknown) => failures.push(error)) + } + if (failures.length > 0) throw new AggregateError(failures, 'browser benchmark failed') + } + const aggregate = { + widen: median(samples.widen.map(sample => sample.restyleRatio)), + narrow: median(samples.narrow.map(sample => sample.restyleRatio)), + } + console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/median', turns: HISTORY_TURNS, steps: STEPS, budget: RESTYLE_BUDGET, aggregate, samples })) + expectRestylesWithinBudget(aggregate.widen) + expectRestylesWithinBudget(aggregate.narrow) +}) diff --git a/benchmarks/rightbar-drag-browser/synthetic-history.ts b/benchmarks/rightbar-drag-browser/synthetic-history.ts new file mode 100644 index 0000000000..46295614c4 --- /dev/null +++ b/benchmarks/rightbar-drag-browser/synthetic-history.ts @@ -0,0 +1,67 @@ +/** Synthetic current-generation history whose rows wrap, for measuring transcript restyles during a resize. */ +import { brandString } from '@deepseek-ai/dsh-brand' +import { createAssistantMessage, createSystemMessage, createToolResultMessage, createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { Session, type SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' + +/** Closed turns in the workload; every one is loaded before the drag. */ +export const HISTORY_TURNS = 120 +/** Identity private to each isolated scaffold. */ +export const SESSION_ID = 'benchmark-rightbar-drag' +const TITLE = 'SYNTHETIC_RIGHTBAR_DRAG' + +function prose(turn: number): string { + const paragraph = `Turn ${String(turn)} synthetic analysis: the renderer measures every row, wraps mixed text 混合中文段落用于换行测量, and keeps \`inline code\` beside **bold** words. ` + const parts = [paragraph.repeat(6), paragraph.repeat(4)] + parts.push(Array.from({ length: 6 }, (_, i) => `- item ${String(i)}: ${paragraph.slice(0, 120)}`).join('\n')) + if (turn % 10 === 0) { + parts.push('```ts\n' + Array.from({ length: 40 }, (_, i) => `const value${String(i)} = compute(${String(i)}, "${'x'.repeat(30)}")`).join('\n') + '\n```') + } + if (turn % 15 === 0) { + parts.push('| a | b | c |\n|---|---|---|\n' + Array.from({ length: 8 }, (_, i) => `| ${String(i)} | ${paragraph.slice(0, 60)} | ${String(i * 3)} |`).join('\n')) + } + return parts.join('\n\n') +} + +/** + * Create prose, lists, code, tables, reasoning, and tool output without reading user data. + * @returns Current Session JSONL accepted by the shared Web seeder. + */ +export function syntheticHistory(): string { + const session = Session.create(brandString(SESSION_ID)) + for (let turn = 1; turn <= HISTORY_TURNS; turn++) { + session.append('turn/start', { turn }) + session.append('step/start', { turn, step: 1 }) + if (turn === 1) session.append('system/message', { turn, step: 1, message: createSystemMessage('') }, { surfaceOp: 'append' }) + const user = session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: `Question ${String(turn)}: ` + '请检查宽度变化时的排版。 '.repeat(12) }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + if (turn === 1) session.append('session/title', { title: TITLE, messageSeqs: [user.seq], source: { kind: 'fallback' } }) + const tool = turn % 5 === 0 + const callId = brandString(`synthetic-call-${String(turn)}`) + const args = '{"path":"src/a.ts"}' + session.append('assistant/message', { + turn, step: 1, stream: [], + message: createAssistantMessage({ + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + content: [ + { type: 'reasoning', text: 'Compare the synthetic module and test. '.repeat(20) }, + { type: 'text', text: prose(turn) }, + ...tool ? [{ type: 'tool-call' as const, id: callId, name: 'synthetic_tool', arguments: args }] : [], + ], + }), + usage: { inputTokens: 4000, outputTokens: 800 }, + }, { surfaceOp: 'append' }) + if (tool) { + const call = session.append('tool/call', { turn, step: 1, callId, name: 'synthetic_tool', arguments: args }) + session.append('tool/result', { turn, step: 1, message: createToolResultMessage({ + callId, isError: false, content: [{ type: 'text', text: 'Synthetic tool output line.\n'.repeat(40) }], + }) }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + } + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + } + const header = { type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 1700000000000, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 } + return [JSON.stringify(header), ...session.snapshotEvents().map(event => JSON.stringify(event)), ''].join('\n') +} diff --git a/benchmarks/support/scaling-report.ts b/benchmarks/support/scaling-report.ts index 6345dde870..2a20ead10b 100644 --- a/benchmarks/support/scaling-report.ts +++ b/benchmarks/support/scaling-report.ts @@ -24,8 +24,11 @@ import { MACHINE_PROFILES, matchMachineProfile } from './machine-profiles.ts' /** Directory owning `results.jsonl` and `report.html`; ignored by Git. */ export const REPORT_DIRECTORY = join(import.meta.dirname, '..', '.dsh-report') -const RESULTS_PATH = join(REPORT_DIRECTORY, 'results.jsonl') -const REPORT_PATH = join(REPORT_DIRECTORY, 'report.html') +const RESULTS_FILE = 'results.jsonl' +const ENVIRONMENT_FILE = 'environment.json' +const REPORT_FILE = 'report.html' +const RESULTS_PATH = join(REPORT_DIRECTORY, RESULTS_FILE) +const REPORT_PATH = join(REPORT_DIRECTORY, REPORT_FILE) /** Identity and reader-facing description of one benchmark case, shown when hovering its rows in the report. */ export interface BenchmarkCase { @@ -120,23 +123,112 @@ export function setup(): void { rmSync(REPORT_DIRECTORY, { recursive: true, force: true }) } -/** Vitest global teardown: render the report when a case recorded a timing and this phase owns the report. */ +/** + * Vitest global teardown: when a case recorded a timing and this phase owns the report, render it and + * record the measuring machine beside the results, so {@link mergeReportDirectories} can render one + * report from phases measured on separate machines. + */ export function teardown(): void { if (reportPhase() === 'first') return if (!existsSync(RESULTS_PATH)) return - const records = readFileSync(RESULTS_PATH, 'utf8').split('\n').filter(line => line !== '').map(line => JSON.parse(line) as TimingRecord | MemoryRecord) - const cpuModel = cpus()[0]?.model.trim() ?? 'unknown CPU' + const environment = measuringEnvironment() + writeFileSync(join(REPORT_DIRECTORY, ENVIRONMENT_FILE), `${JSON.stringify(environment)}\n`) writeFileSync(REPORT_PATH, renderReport({ - records, + records: readRecords(RESULTS_PATH), + ...environment, + revision: process.env['GITHUB_SHA'], + generatedAt: new Date().toISOString(), + })) + console.log(`benchmark report: ${REPORT_PATH}`) +} + +/** The machine fields of {@link ReportData}, measured by the process that ran the cases. */ +export type MeasuringEnvironment = Pick + +function measuringEnvironment(): MeasuringEnvironment { + const cpuModel = cpus()[0]?.model.trim() ?? 'unknown CPU' + return { cpuModel, platform: `${process.platform}-${process.arch}`, node: process.version, - revision: process.env['GITHUB_SHA'], - generatedAt: new Date().toISOString(), cores: availableParallelism(), measuredProfile: matchMachineProfile(cpuModel), - })) - console.log(`benchmark report: ${REPORT_PATH}`) + } +} + +function readRecords(path: string): (TimingRecord | MemoryRecord)[] { + return readFileSync(path, 'utf8').split('\n').filter(line => line !== '').map(line => JSON.parse(line) as TimingRecord | MemoryRecord) +} + +function readEnvironment(path: string): MeasuringEnvironment { + const value: unknown = JSON.parse(readFileSync(path, 'utf8')) + if (typeof value !== 'object' || value === null) throw new Error(`${path} must hold a JSON object.`) + const field = (name: string): unknown => Reflect.get(value, name) + const cpuModel = field('cpuModel') + const platform = field('platform') + const node = field('node') + const cores = field('cores') + const measuredProfile = field('measuredProfile') + if (typeof cpuModel !== 'string' || typeof platform !== 'string' || typeof node !== 'string' + || typeof cores !== 'number' || !Number.isInteger(cores) || cores < 1 + || (measuredProfile !== undefined && typeof measuredProfile !== 'string')) { + throw new Error(`${path} must record cpuModel, platform, node, a positive integer cores, and an optional measuredProfile.`) + } + return { cpuModel, platform, node, cores, measuredProfile } +} + +/** + * Combine the results of phases that each ran alone on its own machine into the inputs of one report. + * Records are concatenated in directory order. When every phase reports the same machine, the report + * uses it; otherwise the CPU models are listed together and the measured profile is left for the reader + * to choose, because one profile cannot describe both machines. + * @param directories - report directories, each holding `results.jsonl` and `environment.json`. + * @param revision - commit the phases measured. + * @param generatedAt - render time. + * @returns the report inputs and any machine mismatch to surface. + * @throws If no directory holds results, or a directory holds results without a valid environment. + */ +export function mergeReportDirectories( + directories: readonly string[], + revision: string | undefined, + generatedAt: string, +): { readonly data: ReportData; readonly warnings: readonly string[] } { + const phases = directories + .filter(directory => existsSync(join(directory, RESULTS_FILE))) + .map(directory => ({ + records: readRecords(join(directory, RESULTS_FILE)), + environment: readEnvironment(join(directory, ENVIRONMENT_FILE)), + })) + const [first] = phases + if (first === undefined) throw new Error(`no benchmark results under ${JSON.stringify(directories)}.`) + const models = [...new Set(phases.map(phase => phase.environment.cpuModel))] + const warnings = models.length > 1 + ? [`benchmark phases ran on different CPUs (${models.join(' | ')}); choose the measured profile in the report.`] + : [] + return { + data: { + records: phases.flatMap(phase => phase.records), + ...first.environment, + ...models.length > 1 ? { cpuModel: models.join(' | '), measuredProfile: undefined } : {}, + revision, + generatedAt, + }, + warnings, + } +} + +/** + * Render one report from several phase report directories into `outputDirectory/report.html`. + * @param outputDirectory - directory to write the report into. + * @param directories - phase report directories; ones without results are skipped. + * @returns the warnings from {@link mergeReportDirectories}. + * @throws If no directory holds results. + */ +export function renderMergedReport(outputDirectory: string, directories: readonly string[]): readonly string[] { + const { data, warnings } = mergeReportDirectories(directories, process.env['GITHUB_SHA'], new Date().toISOString()) + mkdirSync(outputDirectory, { recursive: true }) + writeFileSync(join(outputDirectory, REPORT_FILE), renderReport(data)) + return warnings } /** Inputs embedded in one rendered report. */ diff --git a/docs/config-catalog.md b/docs/config-catalog.md index fa5c3b4a9d..635dbc7d32 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -401,7 +401,7 @@ export interface SearchLimits { ## `@deepseek-ai/dsh-attachment-local` -- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts) +- `source`: [`packages/attachment/attachment-local/src/index.ts:70`](../packages/attachment/attachment-local/src/index.ts) ```ts config-catalog /** Local attachment backend configuration. */ @@ -429,6 +429,10 @@ export interface Config { normalizedImageMaxBytes?: number /** Maximum simultaneous normalization or request-image transformations in this service instance. */ imageCompressionConcurrency?: number + /** Minimum long-edge shrink divisor after a request image exceeds its hard byte limit; must be greater than one. Default: 1.1. */ + requestImageMinShrinkFactor?: number + /** Fraction of the hard byte limit used to estimate the next request-image size; in (0, 1]. Default: 0.95. */ + requestImageByteHeadroom?: number } ``` @@ -936,7 +940,7 @@ export interface ToolResultPruneConfig { ## `@deepseek-ai/dsh-cordis-host-runner` - `inject`: `tools` -- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts) +- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:107`](../packages/extensions/cordis-host-runner/src/index.ts) ```ts config-catalog /** Runner configuration. */ @@ -2272,7 +2276,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:251`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:257`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2380,11 +2384,16 @@ export interface PiAiProviderProfile { * steps rewrite the request prefix less often. */ imageOffloadCountQuantum?: number + /** Fixed divisor of maxRequestImageBytes when allocating hard per-image budgets; independent of current image count. Default: 20. */ + requestImageBudgetCount?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number + /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ + requestImageMaxDimension?: number /** - * Raw encoded-byte target for each deterministic inline request version; - * the smallest quality-ladder output is used when no quality fits. + * Hard per-image encoded-byte cap overriding the selected model's base64 budget. + * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. + * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ @@ -3162,7 +3171,7 @@ export interface Config { export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig - /** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */ + /** persistent-in-memory, the default, retains a REPL per owner; per-call uses fresh async function bodies; vm-script uses VM contexts. */ executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ scriptPersistence?: boolean diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f1b2837cd3..547f7953e2 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -403,7 +403,7 @@ export interface SearchLimits { ## `@deepseek-ai/dsh-attachment-local` -- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts) +- `source`: [`packages/attachment/attachment-local/src/index.ts:70`](../packages/attachment/attachment-local/src/index.ts) ```ts config-catalog /** Local attachment backend configuration. */ @@ -431,6 +431,10 @@ export interface Config { normalizedImageMaxBytes?: number /** Maximum simultaneous normalization or request-image transformations in this service instance. */ imageCompressionConcurrency?: number + /** Minimum long-edge shrink divisor after a request image exceeds its hard byte limit; must be greater than one. Default: 1.1. */ + requestImageMinShrinkFactor?: number + /** Fraction of the hard byte limit used to estimate the next request-image size; in (0, 1]. Default: 0.95. */ + requestImageByteHeadroom?: number } ``` @@ -938,7 +942,7 @@ export interface ToolResultPruneConfig { ## `@deepseek-ai/dsh-cordis-host-runner` - `inject`: `tools` -- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts) +- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:107`](../packages/extensions/cordis-host-runner/src/index.ts) ```ts config-catalog /** Runner configuration. */ @@ -2274,7 +2278,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:251`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:257`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2382,11 +2386,16 @@ export interface PiAiProviderProfile { * steps rewrite the request prefix less often. */ imageOffloadCountQuantum?: number + /** Fixed divisor of maxRequestImageBytes when allocating hard per-image budgets; independent of current image count. Default: 20. */ + requestImageBudgetCount?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number + /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ + requestImageMaxDimension?: number /** - * Raw encoded-byte target for each deterministic inline request version; - * the smallest quality-ladder output is used when no quality fits. + * Hard per-image encoded-byte cap overriding the selected model's base64 budget. + * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. + * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ @@ -3164,7 +3173,7 @@ export interface Config { export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig - /** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */ + /** persistent-in-memory, the default, retains a REPL per owner; per-call uses fresh async function bodies; vm-script uses VM contexts. */ executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ scriptPersistence?: boolean diff --git a/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml b/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml index a974d598d1..732ee119e7 100644 --- a/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml +++ b/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml @@ -6,11 +6,11 @@ en: f41561de1c6dbfef zh: 83b863e1ac91d913 /responding-to-review-across-a-stacked-pr-chain/ground-rules: - en: 5545e41aea74b5d6 - zh: 7105f51939753a1a + en: e5b1b3c2b7db3d92 + zh: 2fb7defc040f453d /responding-to-review-across-a-stacked-pr-chain/resolve-comments-through-the-stack: - en: 4d58b207c8ecbcaa - zh: 38673a460674b8d6 + en: 0699f3b7a2791606 + zh: 6ca53b1dc25bd38d /responding-to-review-across-a-stacked-pr-chain/verify: en: 07cfbae7602fc30e zh: 19782f06ee3c4a74 diff --git a/docs/cookbook/responding-to-pr-review-on-a-stack.md b/docs/cookbook/responding-to-pr-review-on-a-stack.md index 61b15fd5e7..79d783cc37 100644 --- a/docs/cookbook/responding-to-pr-review-on-a-stack.md +++ b/docs/cookbook/responding-to-pr-review-on-a-stack.md @@ -10,15 +10,15 @@ Review comments may target several PRs in a dependent stack (`A ← B ← C …` 2. **GitHub's stack object is authoritative.** Base branches establish the expected dependency order, while `PullRequest.stack` and `stackEntry.position` prove that GitHub recognizes it. Do not treat a matching branch chain as an official stack without checking those fields. 3. **A fix lands on the PR that INTRODUCED the issue, then flows up-stack.** When a comment on PR `B` points at code `B` introduced, fix it on `B` and propagate `B` into `C` — even if `C` also carries the file. Originating the fix downstream leaves `B` shipping the unfixed code and hides the fix from `B`'s reviewer. 4. **Each review fix remains a distinct commit.** A later rebase may change its OID, but do not amend a reviewed fix out of the branch history. Amend only your own not-yet-pushed, not-yet-reviewed work. -5. **Choose merge-forward or rebase deliberately.** Both histories are allowed after review. A rewritten push must be lease-protected and must abort rather than overwrite a concurrently advanced remote head; raw `--force` is forbidden. +5. **Propagate by rebase with rerere.** Run `git config rerere.enabled true` before rebasing so Git replays recorded conflict resolutions; inspect each replayed resolution before staging it. Use merge-forward only when the PR author explicitly asks for it. A rewritten push must be lease-protected and must abort rather than overwrite a concurrently advanced remote head; raw `--force` is forbidden ([rationale](../../.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md)). ## Resolve comments through the stack 1. Triage every comment on the merits before acting: verify the claim against the code — a reviewer flagging the right symptom can still misdiagnose the cause. 2. Map each accepted finding to its originating PR and fix it there. 3. Propagate the fixed layer through every affected child in order: - - **Merge-forward:** merge the fixed parent branch into its child, validate the child, and continue upward. Preserve each in-progress checkpoint. - **Native cascading rebase:** use `gh stack rebase`, validate the rewritten layers, then publish with `gh stack push`; or use `gh stack sync`, which may publish first and therefore requires immediate post-sync validation under [dsh-pre-push-checks](../../.agents/skills/dsh-pre-push-checks/SKILL.md). + - **Merge-forward, only on the PR author's explicit request:** merge the fixed parent branch into its child, validate the child, and continue upward. Preserve each in-progress checkpoint. 4. Treat delegated fixes as trust-but-verify: a sub-agent's report describes intent, not necessarily what landed. Re-run the gates yourself on the actual tree, and for a regression guard, prove it FAILS on the unfixed code (introduce the regression, watch red, revert) — a guard that passes both ways guards nothing. A sub-agent that reframes a problem as already handled is a signal to dig in personally. 5. Reply in the review thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level comment, stating the fix and the current commit or head that carries it. 6. After any rewritten push, re-read unresolved threads, approvals, mergeability, and checks. A force-pushed commit OID or outdated inline anchor is not current evidence that the finding remains resolved. diff --git a/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md b/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md index a33418d342..4b35491c23 100644 --- a/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md +++ b/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md @@ -10,15 +10,15 @@ 2. **GitHub 的 stack 对象是权威依据。** base 分支确定预期的依赖顺序,`PullRequest.stack` 和 `stackEntry.position` 则证明 GitHub 已识别该堆叠。未经检查这些字段,不得仅凭分支链吻合就将其视为官方堆叠。 3. **修复落在引入问题的那个 PR 上,然后沿堆叠向上流动。** 当 PR `B` 上的评论指向 `B` 引入的代码时,在 `B` 上修复,再将 `B` 的变更传播到 `C`,即使 `C` 也包含该文件。把修复发起在下游会导致 `B` 带着未修复的代码交付,并对 `B` 的评审者隐藏修复。 4. **每项评审修复都保留为独立 commit。** 后续 rebase 可能改变其 OID,但不得通过 amend 把已经评审的修复从分支历史中抹去。只有你自己尚未推送且尚未评审的工作才可以 amend。 -5. **明确选择 merge-forward 或 rebase。** 评审后允许采用这两种历史更新方式。改写历史的推送必须受 lease 保护;如果远端 head 在此期间前移,操作必须中止,不得将其覆盖。禁止直接使用 `--force`。 +5. **以启用 rerere 的 rebase 传播修复。** rebase 前运行 `git config rerere.enabled true`,让 Git 复用已记录的冲突解决结果;暂存前检查每个复用的解决结果。只有 PR 作者明确要求时才使用 merge-forward。改写历史的推送必须受 lease 保护;如果远端 head 在此期间前移,操作必须中止,不得将其覆盖。禁止直接使用 `--force`([理由](../../.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md))。 ## 沿堆叠解决评审意见 1. 在行动之前先就事论事地审视每条评论:对照代码验证其论断——评审者指出了正确的症状,但仍可能误诊原因。 2. 将每个被接受的发现映射到引入该问题的 PR,并在那里修复。 3. 将修复后的层按顺序传播到每个受影响的子 PR: - - **Merge-forward:** 将修复后的父分支合并到其子分支,验证子分支,然后继续沿堆叠向上传播。保留每个正在处理的检查点。 - **原生级联 rebase:** 使用 `gh stack rebase`,验证所有已改写的层,然后通过 `gh stack push` 发布;也可以使用 `gh stack sync`,该命令可能先发布,因此必须按照 [dsh-pre-push-checks](../../.agents/skills/dsh-pre-push-checks/SKILL.md) 在同步后立即验证。 + - **Merge-forward(仅在 PR 作者明确要求时):** 将修复后的父分支合并到其子分支,验证子分支,然后继续沿堆叠向上传播。保留每个正在处理的检查点。 4. 委派的修复需要信任但验证:subagent 的报告描述的是意图,不一定是实际落地的内容。请亲自在实际代码树上重新运行门禁;对于回归守卫,要证明它在未修复的代码上**失败**(引入回归、观察变红、再还原)——两种情况都通过的守卫什么也守不住。subagent 将问题重新定性为「已处理」时,这是一个需要亲自深入的信号。 5. 在评审线程中回复(`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`),而非发顶层评论;说明修复内容及当前承载修复的 commit 或 head。 6. 每次改写推送后,都要重新读取未解决线程、批准状态、可合并性和检查结果。经 force-push 改写的 commit OID 或已过时的内联锚点,都不足以证明该发现当前仍处于已解决状态。 diff --git a/docs/defensive-patterns/general.i18n.yaml b/docs/defensive-patterns/general.i18n.yaml index fecd9d26cd..1878a2daeb 100644 --- a/docs/defensive-patterns/general.i18n.yaml +++ b/docs/defensive-patterns/general.i18n.yaml @@ -36,8 +36,8 @@ en: f74f2467e507455f zh: fe1bae04be5ad63a /defensive-patterns/changes-carry-performance-evidence: - en: 0d6855d1ae0ef4ae - zh: 0f771999398ce052 + en: ed9da54674e60a52 + zh: e7d155cd17651ff9 /defensive-patterns/migrations-preserve-behavior: en: 6213e051f51437b8 zh: 853580b3a4fec100 diff --git a/docs/defensive-patterns/general.md b/docs/defensive-patterns/general.md index 165d416d21..a310a76ce2 100644 --- a/docs/defensive-patterns/general.md +++ b/docs/defensive-patterns/general.md @@ -192,7 +192,7 @@ Measurement is owned by [benchmarks/](../../benchmarks/AGENTS.md), one directory pnpm run test:bench ``` -Package-local diagnostics stay beside their owner with the `.perf.ts` suffix and do not join `test:bench`. The CI gate is `pnpm run check:ci:bench` (job `node 24 / benchmarks`), which publishes a scaled report — that gate is an alert, not a pass: a regression there is located by re-running the owning scenario and profiling segments locally to find which part slowed and which change introduced it. Retained-memory claims use `pnpm run test:bench:memory 4g|8g`, which reruns its listed files under an unchanged budget in a swapless cgroup. +Package-local diagnostics stay beside their owner with the `.perf.ts` suffix and do not join `test:bench`. The CI gates are the two phase jobs `node 24 / benchmarks 1/2` and `2/2` (`pnpm run check:ci:bench-prebuilt`), and `node 24 / benchmark report` publishes a scaled report from both — that gate is an alert, not a pass: a regression there is located by re-running the owning scenario and profiling segments locally to find which part slowed and which change introduced it. Retained-memory claims use `pnpm run test:bench:memory 4g|8g`, which reruns its listed files under an unchanged budget in a swapless cgroup. Boundaries: edits that touch no runtime path — comments, documentation, test-only code — need no measurement, and production performance code is not benchmark instrumentation to be deleted opportunistically (`performance.now()` and `scheduler.yield()` are part of production decode and encode chunk scheduling). An architectural change that genuinely costs performance states the measured cost and the reason, and the domain owner approves it; "the layering needed it" is not a self-service reason. Record the command, the numbers, the environment, and the input size so the baseline can be rebuilt. diff --git a/docs/defensive-patterns/general.zh.md b/docs/defensive-patterns/general.zh.md index 8013ec28fd..fa8794815d 100644 --- a/docs/defensive-patterns/general.zh.md +++ b/docs/defensive-patterns/general.zh.md @@ -214,7 +214,7 @@ if (pluginName === 'ui-attachment') { /* business branch inside the manager */ } pnpm run test:bench ``` -包内诊断留在包旁边、用 `.perf.ts` 后缀,不进 `test:bench`。CI 门禁是 `pnpm run check:ci:bench`(作业 `node 24 / benchmarks`),产出 scaled report——该门禁只是**报警**,不是通过依据:出现退化时重跑对应场景并本地分段 profile,定位是哪一段变慢、哪次变更引入。内存留存类结论用 `pnpm run test:bench:memory 4g|8g`,它会在无 swap 的 cgroup 里以不变预算重跑其列出的文件。 +包内诊断留在包旁边、用 `.perf.ts` 后缀,不进 `test:bench`。CI 门禁是两个阶段作业 `node 24 / benchmarks 1/2` 与 `2/2`(`pnpm run check:ci:bench-prebuilt`),由 `node 24 / benchmark report` 汇总两者产出 scaled report——该门禁只是**报警**,不是通过依据:出现退化时重跑对应场景并本地分段 profile,定位是哪一段变慢、哪次变更引入。内存留存类结论用 `pnpm run test:bench:memory 4g|8g`,它会在无 swap 的 cgroup 里以不变预算重跑其列出的文件。 边界:不触碰运行路径的改动——注释、文档、仅测试代码——不需要测量;生产性能代码不是可以顺手删掉的 benchmark instrumentation(`performance.now()`、`scheduler.yield()` 属于生产 decode/encode 分片调度的一部分)。架构调整确实要付出性能代价时,写明实测代价与理由,并由对应领域专家确认;「分层需要」不是自助理由。命令、数字、环境与输入规模都要落账,以便返工时重建同一基线。 diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 07c82f4ecf..6e8a366336 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1632,8 +1632,8 @@ en: e4a4fc20bc145671 zh: 48bb675a3807ae42 /session-persistence-event-catalog/resolved-persistence-types/kind-cordis-host-runner: - en: 578c453192e3daa6 - zh: f28b2d995442f5b2 + en: ec733000e7c8bc23 + zh: 091389d028d9c789 /session-persistence-event-catalog/resolved-persistence-types/kind-cua-activity-form-notice: en: b2d834240d76ef1a zh: 5cd10724fc6deccf diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 62a2c67e42..8f8a7dcd3b 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -6812,7 +6812,7 @@ Sources: [`packages/core/session/src/types.ts:217`](../packages/core/session/src SHA-256: `02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79` -Sources: [`packages/extensions/cordis-host-runner/src/index.ts:15`](../packages/extensions/cordis-host-runner/src/index.ts) +Sources: [`packages/extensions/cordis-host-runner/src/index.ts:16`](../packages/extensions/cordis-host-runner/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 146e42491b..010d589730 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -6814,7 +6814,7 @@ SHA-256: `b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0` SHA-256: `02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79` -来源:[`packages/extensions/cordis-host-runner/src/index.ts:15`](../packages/extensions/cordis-host-runner/src/index.ts) +来源:[`packages/extensions/cordis-host-runner/src/index.ts:16`](../packages/extensions/cordis-host-runner/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index e13e2588b0..7e229b7fe1 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -75,7 +75,7 @@ {"digest":"022623b9ef98ec47ec3c3bae0c51027c70d2601141c5e92e26a0d83d1b4cef06","names":[],"sources":[]}, {"digest":"023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4","names":[],"sources":["packages/core/session/src/types.ts:221"]}, {"digest":"025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc","names":[],"sources":[]}, - {"digest":"02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79","names":[],"sources":["packages/extensions/cordis-host-runner/src/index.ts:15"]}, + {"digest":"02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79","names":[],"sources":["packages/extensions/cordis-host-runner/src/index.ts:16"]}, {"digest":"0341d4c3dfcd53253cdc1e789d9130d3cd848b6f8b0706bf92f313a68b39ff23","names":[],"sources":[]}, {"digest":"041960dcab4a409b4d50f524abbec606e518dc198f84d6a84922155096326592","names":[],"sources":["packages/core/session/src/types.ts:327"]}, {"digest":"04c12e59a9ed4d7a59b642223a9bdd3b4303c1d27873c72c5e487760892bbb08","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:176"]}, diff --git a/docs/subsystems/attachment.md b/docs/subsystems/attachment.md index bccf3c33a3..75d8bbf887 100644 --- a/docs/subsystems/attachment.md +++ b/docs/subsystems/attachment.md @@ -134,12 +134,14 @@ interface StoredImageAttachment { ```ts type-equiv /** Deterministic request-image target selected by one exact model route for one attachment. */ interface ImageRequestTarget { - /** Target width in pixels; a target above the source keeps the source width. */ + /** Maximum request width in pixels; byte-limit enforcement can produce a smaller image. */ width: number - /** Target height in pixels; a target above the source keeps the source height. */ + /** Maximum request height in pixels; byte-limit enforcement can produce a smaller image. */ height: number - /** Encoded-byte target before base64 expansion or Files API upload; the smallest quality-ladder output is kept when no quality fits. */ - maxBytes: number + /** Hard encoded-byte limit before base64 expansion or Files API upload; successful results never exceed it. */ + maxImageBytes: number + /** Preferred encoded-byte target, no greater than maxImageBytes; exceeding only this target does not reduce resolution. */ + imageTargetBytes: number } ``` @@ -299,9 +301,9 @@ fileHostPath(ref: FileAttachmentRef): string | undefined /** * Generate or read one deterministic model-request version from the stored normalized image. * @param ref - durable provider-independent normalized attachment reference. - * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output. + * @param target - route-chosen maximum dimensions, hard byte limit, and preferred byte target. * @param signal - optional cancellation. - * @returns request bytes and the cache/upload identity covering every transform input. + * @returns request bytes within the hard limit, actual encoded dimensions, and a cache/upload identity covering every transform input. */ readImageRequest( ref: ImageAttachmentRef, target: ImageRequestTarget, signal?: AbortSignal, ): Promise ``` diff --git a/docs/subsystems/attachment.zh.md b/docs/subsystems/attachment.zh.md index c917947b73..ef6c0192cb 100644 --- a/docs/subsystems/attachment.zh.md +++ b/docs/subsystems/attachment.zh.md @@ -134,12 +134,14 @@ interface StoredImageAttachment { ```ts type-equiv /** Deterministic request-image target selected by one exact model route for one attachment. */ interface ImageRequestTarget { - /** Target width in pixels; a target above the source keeps the source width. */ + /** Maximum request width in pixels; byte-limit enforcement can produce a smaller image. */ width: number - /** Target height in pixels; a target above the source keeps the source height. */ + /** Maximum request height in pixels; byte-limit enforcement can produce a smaller image. */ height: number - /** Encoded-byte target before base64 expansion or Files API upload; the smallest quality-ladder output is kept when no quality fits. */ - maxBytes: number + /** Hard encoded-byte limit before base64 expansion or Files API upload; successful results never exceed it. */ + maxImageBytes: number + /** Preferred encoded-byte target, no greater than maxImageBytes; exceeding only this target does not reduce resolution. */ + imageTargetBytes: number } ``` @@ -299,9 +301,9 @@ fileHostPath(ref: FileAttachmentRef): string | undefined /** * Generate or read one deterministic model-request version from the stored normalized image. * @param ref - durable provider-independent normalized attachment reference. - * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output. + * @param target - route-chosen maximum dimensions, hard byte limit, and preferred byte target. * @param signal - optional cancellation. - * @returns request bytes and the cache/upload identity covering every transform input. + * @returns request bytes within the hard limit, actual encoded dimensions, and a cache/upload identity covering every transform input. */ readImageRequest( ref: ImageAttachmentRef, target: ImageRequestTarget, signal?: AbortSignal, ): Promise ``` diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 704ce4467b..e5feb9ed76 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -88,7 +88,7 @@ register
(kind: ActionCardKind
): () => void * Record a card decision in the Session log; the next model request reports it. * @param agent - agent whose Session owns the card. * @param decision - the card's new state. - * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + * @throws when no kind ever registered the decision's action with this service. */ record(agent: Agent, decision: ActionCardDecision): void diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index e441de34b8..cd0f3fee21 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -88,7 +88,7 @@ register
(kind: ActionCardKind
): () => void * Record a card decision in the Session log; the next model request reports it. * @param agent - agent whose Session owns the card. * @param decision - the card's new state. - * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + * @throws when no kind ever registered the decision's action with this service. */ record(agent: Agent, decision: ActionCardDecision): void diff --git a/docs/subsystems/extensions.md b/docs/subsystems/extensions.md index 4d8e592487..5d5c4ccca1 100644 --- a/docs/subsystems/extensions.md +++ b/docs/subsystems/extensions.md @@ -56,15 +56,15 @@ async query( platform: CordisInspectPlatform, providerId: string, methodName: st /** * Accept the first valid Client response for a pending query. - * @param agent - Agent whose Session owns the query. + * @param sessionId - Session identity recorded by the pending query, including subagent Sessions. * @param requestId - Pending Client query identity. * @param resolution - Client provider result or failure. * @returns acknowledgement with accepted true only for a success that settles the query; only the first failure diagnostic is retained. */ -resolveClientQuery( agent: Agent, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck +resolveClientQuery( sessionId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck ``` -Types: [Agent](core.md) +Types: [Agent](core.md) · [SessionId](core.md) Source: [`packages/extensions/cordis-host-runner/src/inspect-registry.ts`](../../packages/extensions/cordis-host-runner/src/inspect-registry.ts) @@ -173,13 +173,13 @@ async stop(agent: Agent, pluginId: CordisDynamicPluginId): Promise agentId } }) resolveInspectQuery( agentId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck /** * Frame-wide inventory, grouped as one row per stable Plugin. @@ -257,7 +257,7 @@ inspectPackage( agent: Agent, pluginId: CordisDynamicPluginId, packageId: Cordis @Remote('invoke') async invoke( pluginId: CordisDynamicPluginId, pluginRunId: CordisDynamicPluginRunId, method: string, args: JsonValue, ): Promise ``` -Types: [Agent](core.md) +Types: [Agent](core.md) · [SessionId](core.md) Source: [`packages/extensions/cordis-host-runner/src/index.ts`](../../packages/extensions/cordis-host-runner/src/index.ts) diff --git a/docs/subsystems/extensions.zh.md b/docs/subsystems/extensions.zh.md index 715653f19a..611ec66ae2 100644 --- a/docs/subsystems/extensions.zh.md +++ b/docs/subsystems/extensions.zh.md @@ -56,15 +56,15 @@ async query( platform: CordisInspectPlatform, providerId: string, methodName: st /** * Accept the first valid Client response for a pending query. - * @param agent - Agent whose Session owns the query. + * @param sessionId - Session identity recorded by the pending query, including subagent Sessions. * @param requestId - Pending Client query identity. * @param resolution - Client provider result or failure. * @returns acknowledgement with accepted true only for a success that settles the query; only the first failure diagnostic is retained. */ -resolveClientQuery( agent: Agent, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck +resolveClientQuery( sessionId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck ``` -Types: [Agent](core.zh.md) +Types: [Agent](core.zh.md) · [SessionId](core.zh.md) Source: [`packages/extensions/cordis-host-runner/src/inspect-registry.ts`](../../packages/extensions/cordis-host-runner/src/inspect-registry.ts) @@ -173,13 +173,13 @@ async stop(agent: Agent, pluginId: CordisDynamicPluginId): Promise agentId } }) resolveInspectQuery( agentId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck /** * Frame-wide inventory, grouped as one row per stable Plugin. @@ -257,7 +257,7 @@ inspectPackage( agent: Agent, pluginId: CordisDynamicPluginId, packageId: Cordis @Remote('invoke') async invoke( pluginId: CordisDynamicPluginId, pluginRunId: CordisDynamicPluginRunId, method: string, args: JsonValue, ): Promise ``` -Types: [Agent](core.zh.md) +Types: [Agent](core.zh.md) · [SessionId](core.zh.md) Source: [`packages/extensions/cordis-host-runner/src/index.ts`](../../packages/extensions/cordis-host-runner/src/index.ts) diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 4b6ab19ee0..e68f25f5e5 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -939,12 +939,12 @@ declare abstract class LlmAdapter { */ imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined; /** - * Resolve the image dimensions and byte target this adapter sends to the model. + * Resolve the maximum image dimensions and byte budgets this adapter uses for the model. * The default preserves normalized images; adapters that resize must override it. * @param _provider - registered provider route. * @param _model - exact model id. * @param image - normalized image whose request projection is being resolved. - * @returns the same target used by request serialization, before provider-internal processing. + * @returns the target used by request serialization; encoded images can be smaller to satisfy the hard byte limit. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; /** @@ -1123,7 +1123,7 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u * @param provider - registered provider route. * @param model - exact model id. * @param image - normalized image reference. - * @returns dimensions and byte target used by the adapter's request serializer. + * @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions. */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 5f5c23cebe..983ee785d3 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -939,12 +939,12 @@ declare abstract class LlmAdapter { */ imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined; /** - * Resolve the image dimensions and byte target this adapter sends to the model. + * Resolve the maximum image dimensions and byte budgets this adapter uses for the model. * The default preserves normalized images; adapters that resize must override it. * @param _provider - registered provider route. * @param _model - exact model id. * @param image - normalized image whose request projection is being resolved. - * @returns the same target used by request serialization, before provider-internal processing. + * @returns the target used by request serialization; encoded images can be smaller to satisfy the hard byte limit. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; /** @@ -1123,7 +1123,7 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u * @param provider - registered provider route. * @param model - exact model id. * @param image - normalized image reference. - * @returns dimensions and byte target used by the adapter's request serializer. + * @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions. */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index e24cd26f22..05710ee316 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -196,6 +196,7 @@ Factory: conversation.content [ConversationContent] │ └─ conversation.plan-review.actions ├─ conversation.composer.bar [InputBar] │ ├─ conversation.input.attachments +│ ├─ conversation.input.placeholder │ ├─ conversation.input.permission │ ├─ conversation.input.plan │ ├─ conversation.input.model diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 2cb79e4060..8e1bf17ad5 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -198,6 +198,7 @@ Factory: conversation.content [ConversationContent] │ └─ conversation.plan-review.actions ├─ conversation.composer.bar [InputBar] │ ├─ conversation.input.attachments +│ ├─ conversation.input.placeholder │ ├─ conversation.input.permission │ ├─ conversation.input.plan │ ├─ conversation.input.model diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml index 879a5e290a..bf70bb4b3c 100644 --- a/docs/testing.i18n.yaml +++ b/docs/testing.i18n.yaml @@ -6,8 +6,8 @@ en: 0d7399a58529b9eb zh: 7f445b06430f21a4 /testing-policy/tiers: - en: ae5eb9cc384542cb - zh: 3473df2dc1e36bd0 + en: 29e64525fdf54929 + zh: bbddb2a55022e525 /testing-policy/how-specs-execute: en: 022c534e72e23142 zh: c07a20994224f37c diff --git a/docs/testing.md b/docs/testing.md index 9064aef93d..3c6051ba6b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -10,7 +10,7 @@ How this repo tests, tier by tier, and the rules that keep a green suite meaning - **Coverage gate** (`pnpm run test:coverage`): the gating run, per-file 100% on `packages/*/*/src`. An uncovered line is often dead code the gate flags for deletion, not a missing test to bolt on. Line coverage is necessary, never sufficient — it proves lines ran, not that the feature works as shipped. Per-file 100% on `packages/shell/pwsh-local/src` needs a real `pwsh`: without one its executor suites self-skip and `vitest.config.ts` exempts the file so pwsh-less hosts stay green, while CI runners ship pwsh and enforce the full bar. - **Real-API e2e** (`pnpm run test:e2e`): with-key tests against live provider APIs — the DeepSeek model plus provider-specific smokes that gate on their own keys; each suite self-skips without its key so keyless CI stays green ([real-API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md)). - **Owner-local expected output** (`pnpm run test:expected`): keyless assembled CLI/process expectations without a recorded-session round trip. Drivers use `*.expected.e2e.ts` beside `tests/expected/`; CI runs built exports. Package/script expectations use `test`, while browser expectations use `test:web`. -- **Performance benchmarks** (`pnpm run test:bench`; required Linux PR gate `node 24 / benchmarks`): `benchmarks/` groups user-path gates. It builds libraries and workers; timed code runs under plain Node, never TSX. Synthetic inputs enforce time, heap, and scaling budgets; package-local `.perf.ts` stays diagnostic ([rules](../.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.md)). +- **Performance benchmarks** (`pnpm run test:bench`; required Linux PR gates `node 24 / benchmarks 1/2` and `2/2`): `benchmarks/` groups user-path gates. It builds libraries and workers; timed code runs under plain Node, never TSX. Synthetic inputs enforce time, heap, and scaling budgets; package-local `.perf.ts` stays diagnostic ([rules](../.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.md)). - **Snapshot** (`pnpm run test:snapshot`): a top-level scenario's highest recorded parent generation supplies user input and model replay, then serves as the expected persisted result. Parent filenames are `session[.vN].jsonl`; child roles are `session.[.vN].jsonl`; v0 omits `.v0`, positive versions require lowercase `.vN`, and each filename must agree with its header. Process scenarios start through `dsh`: headless owns one-shot behavior, the SDK owns persistent control, ACP owns automation-protocol behavior, and Web retains browser/ARIA evidence beside the same Session. `snapshot.yml` declares the profile, composition/header class, recording policy, exceptional replay or input metadata, and workspace facts. Typed tokens preserve parent/child identity relationships; only header pins own prompt/schema sidecars. A mutating scenario independently compares the complete `workspace.expected/` tree, which record and refresh never rewrite. Use `test:snapshot:record` when a model transcript changes and `test:snapshot:refresh` when replay input remains valid; review every resulting diff. - **Web browser snapshot** (`pnpm run test:web`; required Linux PR gate): The command builds plugin CSS, then compares all session-driven `snapshots/web/` and UI-only `apps/web/tests/expected/` output in Chromium; the model/reasoning picker also runs in WebKit. CI enforces read-only `DSH_SNAPSHOT=replay`; record/refresh stay local, with every diff reviewed ([web lane](../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md), [CI reference](../scripts/run-web-snapshots.ts)). diff --git a/docs/testing.zh.md b/docs/testing.zh.md index f756cc9306..ae644fbe97 100644 --- a/docs/testing.zh.md +++ b/docs/testing.zh.md @@ -10,7 +10,7 @@ - **覆盖率门禁**(`pnpm run test:coverage`):门禁级运行,对 `packages/*/*/src` 按文件 100% 覆盖。未覆盖的行往往是门禁正确标记出的死代码(应删除),而非需要补写的测试。行覆盖率是必要条件,但永远不是充分条件:它证明行被执行过,不证明功能按交付预期工作。`packages/shell/pwsh-local/src` 的按文件 100% 覆盖需要真实的 `pwsh`:缺少它时其执行器套件会自动跳过,`vitest.config.ts` 会豁免该文件以使无 pwsh 的主机保持绿色,而 CI runner 自带 pwsh,仍按完整标准执行门禁。 - **真实 API e2e**(`pnpm run test:e2e`):带密钥测试调用真实提供方 API,包括 DeepSeek 模型以及各提供方特有的冒烟测试;这些测试各自由自己的密钥控制,缺少密钥时套件会自动跳过,使 keyless CI 保持绿色([真实 API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.zh.md))。 - **所属位置的预期输出**(`pnpm run test:expected`):无录制会话往返的无密钥组装 CLI/进程预期。驱动使用 `*.expected.e2e.ts`,并与 `tests/expected/` 同属一处;CI 针对构建产物运行。包/脚本预期使用 `test`,浏览器预期使用 `test:web`。 -- **性能基准**(`pnpm run test:bench`;必需的 Linux PR gate `node 24 / benchmarks`):`benchmarks/` 按用户路径组织门禁。它先构建 library 和 worker;被计时代码在纯 Node 下运行,不使用 TSX。合成输入执行耗时、堆和缩放预算;包内 `.perf.ts` 保留为诊断([规则](../.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.zh.md))。 +- **性能基准**(`pnpm run test:bench`;必需的 Linux PR gate `node 24 / benchmarks 1/2` 与 `2/2`):`benchmarks/` 按用户路径组织门禁。它先构建 library 和 worker;被计时代码在纯 Node 下运行,不使用 TSX。合成输入执行耗时、堆和缩放预算;包内 `.perf.ts` 保留为诊断([规则](../.agents/notes/implemented/testing/2026-09-04-session-open-performance-gate.zh.md))。 - **快照**(`pnpm run test:snapshot`):顶层场景数值最高的已录制 parent generation 同时提供用户输入和模型回放,并作为持久化结果的预期值。parent 文件名是 `session[.vN].jsonl`;child 角色使用 `session.[.vN].jsonl`;v0 省略 `.v0`,正版本必须使用小写 `.vN`,且每个文件名必须与其 header 一致。进程级场景都通过 `dsh` 启动:headless 负责一次性行为,SDK 负责持久控制,ACP 负责自动化协议行为,Web 在同一 Session 旁保留浏览器与 ARIA 证据。`snapshot.yml` 声明 profile、组合与请求头类别、录制策略、例外回放或输入元数据以及 workspace 事实。带类型的 token 保留父子身份关系;只有请求头 pin 拥有 prompt/schema sidecar。变更 workspace 的场景会独立比较完整的 `workspace.expected/` 目录,record 与 refresh 绝不改写该目录。当模型 transcript(文本记录)变化时使用 `test:snapshot:record`,回放输入仍有效时使用 `test:snapshot:refresh`;请审查所有结果差异。 - **Web 浏览器快照**(`pnpm run test:web`;必需的 Linux PR(Pull Request)门禁):命令先构建插件 CSS,再用 Chromium 比较 `snapshots/web/` 下全部会话驱动输出和 `apps/web/tests/expected/` 下全部纯 UI 输出;模型与推理强度选择场景还在 WebKit 中运行。CI 强制只读的 `DSH_SNAPSHOT=replay`;record/refresh 留在本地,每处 diff 都须评审([web 车道](../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md)、[CI 说明](../scripts/run-web-snapshots.ts))。 diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index b65cf0a716..679756eb45 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -72,8 +72,8 @@ en: 8c8643ef46fd075f zh: 8c8643ef46fd075f /tool-schema-catalog/deepseek-ai-dsh-tool-executor-ptc/run-code: - en: 93d8526bbc4936d2 - zh: 963af83582d289c5 + en: 839345c3b7a0414d + zh: 906c029c30394562 /tool-schema-catalog/deepseek-ai-dsh-plan-mode: en: b500b530845e26a9 zh: b500b530845e26a9 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 6362317eaf..7538893da3 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -612,7 +612,7 @@ ask_user_question keeps the original blocking behavior by default; set `mode: ti ### `run_code` -Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program is the body of an async TypeScript function; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level await and return are supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. Each call runs in a fresh Node process. Node APIs are available through await import(...). Relative paths use the supplied working directory; process.env starts empty. Direct filesystem access follows this execution's sandbox policy. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically. +Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically. ```json { @@ -620,7 +620,7 @@ Execute a TypeScript program against the available tools. Takes two required arg "properties": { "code": { "type": "string", - "description": "The program: the body of an async TypeScript function." + "description": "The TypeScript program to execute, following this tool's execution instructions." }, "description": { "type": "string", diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index f7bebf58de..8753f7952d 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -616,7 +616,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 ### `run_code` -针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,异步函数的函数体(仅限可擦除语法,支持顶层 `await` 和 `return`);以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。使用 inspect(...values) 展示选定的文本和图片。程序是异步 TypeScript 函数的函数体,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层 await 和 return。使用 inspect(...values) 展示输出。不要使用 console。模板字面量的 raw 形式只用于反斜杠必须原样保留的短文本,例如正则表达式;其他文本,尤其是文件内容和命令,用普通字符串书写。文件内容写成引号字符串数组,每行一个元素,用换行符拼接;不要写成一个模板字面量。每次调用在新的 Node 进程中运行,可通过 await import(...) 使用 Node API。相对路径以传入的工作目录为准;process.env 初始为空。直接文件系统访问遵循本次执行的沙箱策略。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 +针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,要执行的程序;以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。使用 inspect(...values) 展示选定的文本和图片。程序由 TypeScript REPL 语句组成,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层声明和 await;不支持顶层 return。使用 inspect(...values) 展示输出。不要使用 console。模板字面量的 raw 形式只用于反斜杠必须原样保留的短文本,例如正则表达式;其他文本,尤其是文件内容和命令,用普通字符串书写。文件内容写成引号字符串数组,每行一个元素,用换行符拼接;不要写成一个模板字面量。程序在严格模式下运行:给未声明的名字赋值会抛错,有意设置全局变量请使用 globalThis;eval 和 new Function 不可用。变量、函数和导入的模块在本 Agent 的多次调用之间保留在内存中。每次调用在自己的顶层作用域中运行一个程序。它的顶层 let、const、var、class 和 function 声明,以及它从之前程序收到的名字,会拷贝到之后程序的顶层作用域:之后的程序收到的是这些变量的拷贝而不是引用,因此它们持有的对象仍然共享。同一个程序里,要么使用拷贝来的名字,要么重新声明它;不要既声明一个名字又使用它拷贝来的值。给拷贝来的名字赋值,即使它是用 const 声明的,也只改变本程序的拷贝,之后的程序会收到这个拷贝。不要在块内声明 var;块级 var 会改变之后程序拷贝到的值。之前程序中的函数和仍在运行的代码保留它们捕获的值,它们之后的赋值不会被拷贝;共享的可变状态请放在对象中。如果程序在重新声明已有名字的声明完成前失败,之后的程序保留该名字原先的值。使用 await import(...) 加载模块;require 和 module 不可用。相对导入说明符按本环境第一个程序的工作目录解析,而 process.cwd() 和相对文件路径跟随每个程序的工作目录。直接文件系统访问遵循环境启动时的沙箱策略;process.env 初始为空。超时和取消结果会说明保留的变量是被保留还是被清除。重启、沙箱变更或进程失败会清除它们。请重新创建缺失的变量和资源;对话历史不会恢复状态。之前的修改和工具效果不会回滚。获批的沙箱提权使用全新环境,之后丢弃其中的变量。请在程序结束前等待工具调用和清理完成;未完成的工具调用会被拒绝。完成、超时或取消后,新的工具调用会被拒绝,捕获的输出会被丢弃;后台工作仍可能改变状态。请在程序结束前等待子进程完成;原始输出归属于当前执行。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 ```json { @@ -624,7 +624,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 "properties": { "code": { "type": "string", - "description": "The program: the body of an async TypeScript function." + "description": "The TypeScript program to execute, following this tool's execution instructions." }, "description": { "type": "string", diff --git a/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.i18n.yaml new file mode 100644 index 0000000000..36676d0a23 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md +/: + en: c226e668bcaa1303 + zh: b24fa291f2ac9165 +/action-cards-stay-available-across-turns: + en: 1cea03e62b94a3e2 + zh: 6137ad5e581e0283 +/action-cards-stay-available-across-turns/change: + en: 7c55dcb05dc0749a + zh: fa96d17567d8cffb +/action-cards-stay-available-across-turns/migration: + en: e261b9075be87be0 + zh: f2b147aa33c16a97 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md new file mode 100644 index 0000000000..3e74952d8c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Earlier action cards stay available when a later turn offers another card." +--- + +# Action cards stay available across turns + +English | [中文](guide.zh.md) + +## Change + +A later proposal used to mark earlier unstarted cards as `replaced`. When you reopen a Session, those cards offer their actions again. Each card keeps its own recorded decisions, including dismissals and work already started. Each turn still admits only its first valid `action-card` block. + +## Migration + +1. Reopen a conversation containing two proposals from different turns. The Host rebuilds the `actionCards` projection from the Session log when it encounters a version 3 checkpoint. Session files need no edits. +2. Check that each untouched proposal offers its controls. Choose **Not now** on any proposal you no longer want. +3. If your plugin reads `ActionCardView.decisions`, use the decision for the proposal’s `cardId`. An absent decision means the card is unstarted. Remove handling for the former shared `replaced` phase. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.zh.md new file mode 100644 index 0000000000..acdef53adc --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "后续轮次出现新的 Action 卡片时,早先的卡片仍可操作。" +--- + +# Action 卡片在后续轮次仍可操作 + +[English](guide.md) | 中文 + +## 变更 + +过去,新提案会把早先尚未开始的卡片标记为 `replaced`。重新打开会话后,这些卡片会再次提供操作。每张卡片都保留自己的决定记录,包括已忽略的提案和已开始的任务。每轮仍只接纳第一个合法的 `action-card` 代码块。 + +## 迁移 + +1. 打开一个在不同轮次收到过两张提案卡片的会话。Host 遇到版本 3 的检查点时会从会话日志重建 `actionCards` 投影,无需编辑会话文件。 +2. 确认每张尚未操作的卡片都有相应的控件。对不再需要的提案选择**暂不需要**。 +3. 如果插件读取 `ActionCardView.decisions`,请按提案的 `cardId` 读取决定。没有决定记录表示卡片尚未开始,可以删除对原有共享阶段 `replaced` 的处理。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml new file mode 100644 index 0000000000..b08bfbe1b7 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md +/: + en: 8eab7a795974913a + zh: 54b06c3fea95487a +/request-image-byte-limits: + en: 6bee071887ac3982 + zh: ec0176e47b3e64a1 +/request-image-byte-limits/change: + en: 17fdb9e78254c0f4 + zh: 9f31b97bede355ae +/request-image-byte-limits/migration: + en: f42239aa9df6c95c + zh: ef4972f9e4f74ee8 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md new file mode 100644 index 0000000000..e61d9be38f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Request-image byte limits are enforced after encoding, and DeepSeek's soft target uses imageTargetBytes." +--- +# Request-image byte limits + +English | [中文](guide.zh.md) + +## Change + +Model-request images distinguish `maxImageBytes`, a hard encoded-byte limit, from `imageTargetBytes`, a preferred target. The encoder keeps the 85/75/60 quality ladder and reduces dimensions further only when its smallest output exceeds the hard limit. Each reduction starts from the saved source. A limit that cannot fit even a 1×1 image fails with `IMAGE_REQUEST_TOO_LARGE`; oversized bytes are never returned. Stored attachments are unchanged, and request caches regenerate under a new transform version. + +pi exposes only hard limits. `requestImageMaxBytes` keeps its name and now sets a hard cap on the encoded image. `requestImageBudgetCount` defaults to 20. The effective hard limit is the smaller of that cap and `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))`; the internal soft target equals it. Default allocation is 0.75 MiB per image. Width and height follow catalog limits unless `requestImageMaxDimension` overrides both with the same value; unequal local width/height overrides are not supported. + +DeepSeek renames the configurable `imageMaxBytes` soft target to `imageTargetBytes`, retaining its 2 MiB default. Its hard cap is fixed at 32 MiB. CUA's fixed `screenshotTarget.maxBytes` also becomes a hard cap. Request-image targets describe maximum dimensions; actual output can be smaller. Aggregate request limits still apply to actual encoded payloads. + +## Migration + +1. In pi provider profiles, review any explicit `requestImageMaxBytes` value. Images that exceed this value after quality adjustment now shrink further. Set `requestImageBudgetCount` to the desired allocation divisor, independently of the retained-count cap. The aggregate base64 budget must allow at least four bytes per share. For 1 MiB allocations, use a sufficient aggregate budget and divisor, such as 32 MiB and 20 shares, plus `requestImageMaxBytes: 1048576`. +2. In DeepSeek `models` and `modelOverrides`, rename `imageMaxBytes` to `imageTargetBytes`. Keep the value at or below 32 MiB. The retired field is rejected with migration guidance. +3. Consumers of `ImageRequestTarget` replace `maxBytes` with `maxImageBytes` and supply `imageTargetBytes` no greater than it. Read the final width and height from `readImageRequest`, including for coordinate mapping. Direct `readRequestImageFile` and `requestImageVariantId` callers must pass resolved resize controls; DeepSeek helper consumers use `resolveRequestImageTargetBytes` and `DEFAULT_REQUEST_IMAGE_TARGET_BYTES`. +4. Attachment-local deployments may tune `requestImageMinShrinkFactor` (default 1.1, greater than one) and `requestImageByteHeadroom` (default 0.95, in `(0, 1]`). Verify actual encoded bytes stay within the hard limit and coordinate mappings match the returned dimensions. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md new file mode 100644 index 0000000000..a9bd1f53e6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "请求图片在编码后执行字节硬上限,DeepSeek 的软目标改用 imageTargetBytes。" +--- +# 请求图片的字节限制 + +[English](guide.md) | 中文 + +## 变更 + +模型请求图片区分编码字节硬上限 `maxImageBytes` 和软目标 `imageTargetBytes`。编码器保留 85/75/60 质量阶梯,只有最小结果仍超过硬上限时才继续缩小尺寸。每次缩放都从已保存的源图开始。连 1×1 图片也无法满足上限时,以 `IMAGE_REQUEST_TOO_LARGE` 失败,不返回超限字节。存储附件保持不变,请求缓存使用新的变换版本重新生成。 + +pi 只暴露硬上限。继续使用 `requestImageMaxBytes`,它现在限制编码后每张图的字节数。`requestImageBudgetCount` 默认为 20。最终硬上限取该单图上限与 `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))` 的较小值,内部软目标等于硬上限。默认每张图分得 0.75 MiB。宽高跟随目录限制,或由 `requestImageMaxDimension` 用同一个值覆盖;不支持分别配置不同的本地宽高上限。 + +DeepSeek 将可配置软目标 `imageMaxBytes` 重命名为 `imageTargetBytes`,默认仍为 2 MiB,硬上限固定为 32 MiB。CUA 的固定截图配置 `screenshotTarget.maxBytes` 也改为硬上限。请求图片目标描述最大尺寸,实际输出可能更小。请求总量限制仍按实际编码载荷执行。 + +## 迁移 + +1. 如果 pi 提供方配置已设置 `requestImageMaxBytes`,请检查现有取值。调低编码质量后仍超过该值的图片会继续缩小尺寸。通过 `requestImageBudgetCount` 配置预算分摊张数,它独立于保留图片数量上限。base64 总预算须为每份预算至少提供 4 个字节。若希望每张分配 1 MiB,应使用足够的总预算及分摊张数,例如 32 MiB、20 份,再设置 `requestImageMaxBytes: 1048576`。 +2. 在 DeepSeek 的 `models` 和 `modelOverrides` 中,将 `imageMaxBytes` 改为 `imageTargetBytes`,值不得超过 32 MiB。旧字段会被拒绝,并提示迁移方式。 +3. `ImageRequestTarget` 调用方将 `maxBytes` 改为 `maxImageBytes`,并提供不大于硬上限的 `imageTargetBytes`。包括坐标换算在内的调用方,都从 `readImageRequest` 获取最终宽高。直接调用 `readRequestImageFile` 和 `requestImageVariantId` 时须传入已解析的缩放参数;DeepSeek 辅助函数调用方改用 `resolveRequestImageTargetBytes` 和 `DEFAULT_REQUEST_IMAGE_TARGET_BYTES`。 +4. 附件本地存储可配置 `requestImageMinShrinkFactor`,默认 1.1,必须大于 1;以及 `requestImageByteHeadroom`,默认 0.95,范围为 `(0, 1]`。检查实际编码字节满足硬上限,坐标映射与返回尺寸一致。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.i18n.yaml new file mode 100644 index 0000000000..70c2ee3f4a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md +/: + en: 3af3cc4793ec67d9 + zh: a9d8ce0a8546631c +/node-ptc-runs-the-scoped-repl-by-default: + en: 5a90a2b4a5bab5c8 + zh: f838c916dd69ede4 +/node-ptc-runs-the-scoped-repl-by-default/change: + en: be41401640bcd00e + zh: 97637a3404b2fb60 +/node-ptc-runs-the-scoped-repl-by-default/migration: + en: febb7a0bdf248d61 + zh: 6a971b47c9c07a7c diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md new file mode 100644 index 0000000000..0658cbdfdb --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Node PTC defaults to persistent-in-memory execution with the scoped REPL instead of per-call function bodies." +--- + +# Node PTC runs the scoped REPL by default + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-ptc-runtime-node` previously defaulted `executionMode` to `per-call`: each `run_code` program was an async function body in a fresh Node process, with top-level `return` and no state between calls. The default is now `persistent-in-memory`, which with the default `replScoped` runs the scoped REPL and reports program format `scoped-repl`. Each live Agent keeps one Node process whose top-level bindings carry into later calls; top-level `return` is rejected, and the last top-level expression statement is the completion value. The model guidance describes the new syntax. + +This affects every `ptc-runtime` entry that omits `executionMode`, including the default profile's PTC mode, workflow-ptc scripts that run on that runtime, and direct runtime consumers that mount the provider without configuration. Entries that set `executionMode` explicitly are unchanged. For profiles that omit it, the Computer Use detail page reports the shared PTC runtime as already persistent and its **Use persistent mode** action is disabled. + +## Migration + +1. To keep function bodies in fresh processes, set the mode in `$DSH_HOME/profiles//cordis.patch.yml`. The patch replaces the entry's whole `config`, so copy its existing fields into it: + + ```yaml + - id: ptc-runtime + config: + executionMode: per-call + ``` + +2. Programs written for the scoped REPL replace a final `return value` with a final `value` expression statement and use `await import(...)` instead of `require`. +3. Restart the profile, run `var probe = 1` in one call and `inspect(typeof probe)` in the next call of the same Session. The scoped REPL prints `number`; `per-call` prints `undefined`. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.zh.md new file mode 100644 index 0000000000..e8597c422b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.zh.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Node PTC 默认使用 persistent-in-memory 执行和 scoped REPL,不再默认使用 per-call 函数体。" +--- + +# Node PTC 默认运行 scoped REPL + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-ptc-runtime-node` 原先的 `executionMode` 默认值是 `per-call`:每个 `run_code` 程序是在新 Node 进程中运行的 async 函数体,可以使用顶层 `return`,调用之间不保留状态。现在默认值是 `persistent-in-memory`,在默认 `replScoped` 下运行 scoped REPL,并报告程序格式 `scoped-repl`。每个存活的 Agent 保留一个 Node 进程,顶层绑定带到之后的调用;顶层 `return` 会被拒绝,最后一条顶层表达式语句是完成值。模型说明描述了新语法。 + +受影响的是所有省略 `executionMode` 的 `ptc-runtime` 条目,包括默认 profile 的 PTC 模式、在该运行时上运行的 workflow-ptc 脚本,以及不带配置挂载该提供方的直接运行时使用方。显式设置了 `executionMode` 的条目不变。对于省略该项的 profile,Computer Use 详情页显示共享 PTC 运行时已是持久模式,「设为持久化」按钮不可用。 + +## 迁移 + +1. 如果要继续在新进程中运行函数体,在 `$DSH_HOME/profiles//cordis.patch.yml` 中设置执行方式。patch 会替换该条目的整个 `config`,所以要把条目已有的字段一并写进去: + + ```yaml + - id: ptc-runtime + config: + executionMode: per-call + ``` + +2. 为 scoped REPL 编写的程序,把末尾的 `return value` 改为末尾的 `value` 表达式语句,并用 `await import(...)` 代替 `require`。 +3. 重启 profile,在同一会话中先运行 `var probe = 1`,再在下一次调用中运行 `inspect(typeof probe)`。scoped REPL 输出 `number`;`per-call` 输出 `undefined`。 diff --git a/docs/user/develop/practice/dynamic-cordis.i18n.yaml b/docs/user/develop/practice/dynamic-cordis.i18n.yaml index 9e99bfb6fd..629f387443 100644 --- a/docs/user/develop/practice/dynamic-cordis.i18n.yaml +++ b/docs/user/develop/practice/dynamic-cordis.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/user/develop/practice/dynamic-cordis.md /configure-persistent-plugins-from-a-prompt: - en: e61e42a805142826 - zh: da51aa93305f2a3c + en: a1d683397b43c3f8 + zh: 77faaf707f8be306 /configure-persistent-plugins-from-a-prompt/connect-an-mcp-server: en: f9fefda94ba8a005 zh: f1a9a977a0732fc0 diff --git a/docs/user/develop/practice/dynamic-cordis.md b/docs/user/develop/practice/dynamic-cordis.md index ea805bc92f..b8219c917b 100644 --- a/docs/user/develop/practice/dynamic-cordis.md +++ b/docs/user/develop/practice/dynamic-cordis.md @@ -2,7 +2,7 @@ English | [中文](dynamic-cordis.zh.md) -Standard and Creator modes provide [Plugin Manager](../../../../packages/boot/plugin-manager/README.md) and read-only [runtime inspection](../../../../packages/extensions/tool-cordis/README.md). Plugin configuration belongs to the current profile, affects its sessions, and survives process restarts. +Standard, PTC, and Creator modes provide [Plugin Manager](../../../../packages/boot/plugin-manager/README.md); Standard and Creator also provide read-only [runtime inspection](../../../../packages/extensions/tool-cordis/README.md). Plugin configuration belongs to the current profile, affects its sessions, and survives process restarts. ## Connect an MCP server diff --git a/docs/user/develop/practice/dynamic-cordis.zh.md b/docs/user/develop/practice/dynamic-cordis.zh.md index 5c1d10bd56..060282bd77 100644 --- a/docs/user/develop/practice/dynamic-cordis.zh.md +++ b/docs/user/develop/practice/dynamic-cordis.zh.md @@ -2,7 +2,7 @@ [English](dynamic-cordis.md) | 中文 -标准模式和创造模式提供 [Plugin Manager](../../../../packages/boot/plugin-manager/README.zh.md) 和只读[运行时检查](../../../../packages/extensions/tool-cordis/README.zh.md)。插件配置属于当前 profile,影响其会话,并在进程重启后保留。 +标准模式、PTC 模式和创造模式提供 [Plugin Manager](../../../../packages/boot/plugin-manager/README.zh.md);标准模式和创造模式还提供只读[运行时检查](../../../../packages/extensions/tool-cordis/README.zh.md)。插件配置属于当前 profile,影响其会话,并在进程重启后保留。 ## 连接 MCP 服务器 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index 75f0a00884..aa3595f603 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -21,20 +21,20 @@ en: 281b2f40645aa5eb zh: 861bfe9584d9d30f /configure-models/advanced-configuration: - en: b882ec69a6899d8a - zh: 66a1713aca0e6f1c + en: 217be2655684ec9f + zh: 50bb9ce264c545f3 /configure-models/advanced-configuration/image-input: - en: 75350cb615da03a4 - zh: 6f8b3510085e4ac4 + en: f8451240e6a09b95 + zh: 5980a42a1bb4a4dc /configure-models/advanced-configuration/deepseek-account-models: en: fc09d02a89b211a7 zh: e0f23a8912a24178 /configure-models/advanced-configuration/reasoning-effort: - en: f2ffb493997dcc72 - zh: dee9238f072e53ad + en: f6a2efb22fb32f7a + zh: ff8075497aca7d2a /configure-models/advanced-configuration/request-compatibility: en: 6f52195d1502783e zh: 34dbbeacb541afd4 /configure-models/troubleshooting: - en: af9f866bec7701f0 - zh: 0e4f5e1da975be41 + en: 941e0027d0decaad + zh: 4233dbb97c08d348 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 01c18e4b86..501c1bf666 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -51,7 +51,7 @@ If a saved default names a provider that was deleted, the composer displays **Se The generated [plugin configuration catalog](../../config-catalog.md) lists every supported field and default for every plugin; [`dsh-llm-pi-ai`](../../config-catalog.md#deepseek-aidsh-llm-pi-ai) is the provider section this page configures. The [`dsh-llm-pi-ai`](../../../packages/llm/llm-pi-ai/README.md) and [`dsh-llm-deepseek`](../../../packages/llm/llm-deepseek/README.md) references own direct `cordis.patch.yml` configuration, catalog resolution, reasoning controls, credentials, and adapter errors. ::: tip Additional settings -The Models page exposes the API key, display name, base URL, API protocol, and each model's id, display name, context window, max output tokens, and input types, plus the reasoning levels of a model on a custom model API provider. Configure the reasoning levels of a built-in provider's models, request-compatibility switches, headers, timeouts, and retry policy in `$DSH_HOME/profiles//cordis.patch.yml`, the same document the page writes. Edit it directly, or, when the browser runs on the same machine as the server, open it with **Open configuration file** in the Settings header; the adapters re-read it on the next request, so nothing needs a restart. The subsections below cover the fields most gateways need. +The Models page exposes the API key, display name, base URL, API protocol, and each model's id, display name, context window, max output tokens, and input types, plus the reasoning levels of a model on a built-in or custom model API provider. Configure request-compatibility switches, headers, timeouts, and retry policy in `$DSH_HOME/profiles//cordis.patch.yml`, the same document the page writes. Edit it directly, or, when the browser runs on the same machine as the server, open it with **Open configuration file** in the Settings header; the adapters re-read it on the next request, so nothing needs a restart. The subsections below cover the fields most gateways need. For the standard Web UI launch with `dsh web`, `` is `web`, so the path is `$DSH_HOME/profiles/web/cordis.patch.yml`. If you launch a custom profile, use the name selected at startup instead. ::: @@ -80,7 +80,7 @@ These examples show config fields inside a profile patch. A Cordis config overri Pi-ai's `input` accepts `text` and `image` and applies to that model alone. An explicit nonempty selection takes priority. An omitted or empty `input` inherits the installed catalog's input types, then the route's `defaultInput`, which defaults to `[text]`. The checkboxes display these inherited values without saving an override when you merely open the row. -DeepSeek treats an omitted `inputModalities` as text-only and rejects an empty list. Clearing Image also removes that model's `imagePixelBudget` and `imageMaxBytes`, because DeepSeek rejects image limits on a text-only model. Set those limits again if you later enable images and need custom limits. +DeepSeek treats an omitted `inputModalities` as text-only and rejects an empty list. Clearing Image also removes that model's `imagePixelBudget` and `imageTargetBytes`, because DeepSeek rejects image limits on a text-only model. Set those limits again if you later enable images and need custom limits. To restore inheritance after editing the checkboxes, remove the model's `input` or `inputModalities` field from `cordis.patch.yml`. **Restore defaults** removes the entire model-catalog override, including other model edits, so use it only when you want to restore the whole catalog. @@ -135,7 +135,7 @@ A model that needs a newer DeepSeek Harness fails with `CLIENT_UPGRADE_REQUIRED` The model picker offers an **Effort** menu for a model that declares reasoning levels. A built-in provider's models inherit their levels from the installed catalog, and DeepSeek's models keep the adapter's levels. A model you enter by hand declares none until you add them, so until then the Effort entry does not appear in the menu and the endpoint's own default decides whether the model thinks. -On a custom model API provider, declare the levels in **Settings → Models**: edit the provider, open **Customized settings**, expand the model's **Model options**, and turn on **Reasoning levels**. The rows start with off, low, medium, and high. Each row pairs a level with the **API value** sent for it, which defaults to the level name; change it only where the model provider's API documentation spells the level differently. Add or delete rows to match what the endpoint supports, keep at least one level besides off, and save. Turning the switch off removes the declaration. +On a built-in or custom model API provider, declare the levels in **Settings → Models**: edit the provider, open **Customized settings**, expand the model's **Model options**, and turn on **Reasoning levels**. The rows start with off, low, medium, and high. Each row pairs a level with the **API value** sent for it, which defaults to the level name; change it only where the model provider's API documentation spells the level differently. Add or delete rows to match what the endpoint supports, keep at least one level besides off, and save. Levels declared for a built-in provider's model replace the ones it inherits. Turning the switch off removes the declaration, and a built-in provider's model then inherits its levels again. The page writes `reasoningEfforts` in `$DSH_HOME/profiles//cordis.patch.yml`, where you can also declare the levels directly: @@ -224,7 +224,7 @@ Every switch, its accepted values, and the protocols that take it are listed und - **Fetching available models reports neither a `data` array nor a `models` object** — The endpoint's listing is in a format discovery does not read. Enter the models by hand. - **The gateway refuses every request although the key and URL are right** — Its request shape differs from OpenAI's. Start with `compat.supportsDeveloperRole: false` and `compat.maxTokensField: max_tokens` on the route. - **Only reasoning models fail** — pi-ai sends their system prompt as the `developer` role, which the gateway rejects. Set `compat.supportsDeveloperRole: false`. -- **The Effort menu does not appear for a model you entered by hand** — It declares no levels. On a custom model API provider, turn on **Reasoning levels** in the model's **Model options**; elsewhere, add `reasoningEfforts` to the model in `cordis.patch.yml`. +- **The Effort menu does not appear for a model you entered by hand** — It declares no levels. Turn on **Reasoning levels** in the model's **Model options**, or add `reasoningEfforts` to the model in `cordis.patch.yml`. - **`off` does not stop a DeepSeek model from thinking** — An empty `off` sends no reasoning field at all, and an endpoint that thinks by default keeps thinking. Set `compat.thinkingFormat: deepseek` on the model or the route. - **A compat switch is refused as having no value** — A key written with nothing after the colon. Give it a value, or remove the key to keep the installed catalog's. - **An image is refused before sending** — The model declares no image modality. Give a custom provider's model `input: [text, image]`; on DeepSeek's own route, select an image-capable entry from the configured catalog (`deepseek-flash` by default) and confirm that your gateway serves that model with image input. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index b3793525f6..310017ca99 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -51,7 +51,7 @@ Provider ID 是永久的,因为请求、已保存会话、模型默认值和 自动生成的[插件配置目录](../../config-catalog.zh.md)列出每个插件的所有受支持字段与默认值;[`dsh-llm-pi-ai`](../../config-catalog.zh.md#deepseek-aidsh-llm-pi-ai) 就是本页所配置的那个提供商段落。[`dsh-llm-pi-ai`](../../../packages/llm/llm-pi-ai/README.zh.md) 和 [`dsh-llm-deepseek`](../../../packages/llm/llm-deepseek/README.zh.md) 参考文档负责直接 `cordis.patch.yml` 配置、目录解析、推理控制、凭据与适配器错误。 ::: tip 其他设置 -模型页提供 API 密钥、显示名称、API 地址、API 协议,以及每个模型的 ID、显示名称、上下文窗口、最大输出 token 数和输入类型;自定义模型 API 提供商的模型还可以在这里设置推理等级。内置提供商模型的推理等级、请求兼容性开关、请求头、超时和重试策略在 `$DSH_HOME/profiles//cordis.patch.yml` 中设置,也就是模型页写入的同一份文档。可以直接编辑它;浏览器与服务器在同一台机器时,也可以点击设置页顶部的**打开配置文件**打开它。适配器会在下一次请求时重新读取,无需重启任何东西。下面各小节介绍多数网关会用到的字段。 +模型页提供 API 密钥、显示名称、API 地址、API 协议,以及每个模型的 ID、显示名称、上下文窗口、最大输出 token 数和输入类型;内置提供商和自定义模型 API 提供商的模型还可以在这里设置推理等级。请求兼容性开关、请求头、超时和重试策略在 `$DSH_HOME/profiles//cordis.patch.yml` 中设置,也就是模型页写入的同一份文档。可以直接编辑它;浏览器与服务器在同一台机器时,也可以点击设置页顶部的**打开配置文件**打开它。适配器会在下一次请求时重新读取,无需重启任何东西。下面各小节介绍多数网关会用到的字段。 按常规方式通过 `dsh web` 启动 Web UI 时,`` 就是 `web`,完整路径为 `$DSH_HOME/profiles/web/cordis.patch.yml`。如果使用自定义 profile,请替换为启动时指定的名称。 ::: @@ -80,7 +80,7 @@ Provider ID 是永久的,因为请求、已保存会话、模型默认值和 Pi-ai 的 `input` 接受 `text` 和 `image`,且只作用于该模型。显式的非空选择优先。省略或为空的 `input` 先继承已安装目录的输入类型,再回退到路由的 `defaultInput`,后者默认为 `[text]`。复选框会显示这些继承值,仅打开模型行不会保存覆盖值。 -DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。取消图片还会移除该模型的 `imagePixelBudget` 和 `imageMaxBytes`,因为 DeepSeek 拒绝纯文本模型上的图片限制。以后重新启用图片且需要自定义限制时,需再次设置这些限制。 +DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。取消图片还会移除该模型的 `imagePixelBudget` 和 `imageTargetBytes`,因为 DeepSeek 拒绝纯文本模型上的图片限制。以后重新启用图片且需要自定义限制时,需再次设置这些限制。 修改复选框后如需恢复继承,可在 `cordis.patch.yml` 中移除模型的 `input` 或 `inputModalities` 字段。**恢复默认模型**会移除整个模型目录覆盖,包括其他模型编辑,因此仅在需要恢复整个目录时使用。 @@ -135,7 +135,7 @@ DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。 对于声明了推理等级的模型,模型选择器会提供**推理等级**菜单。内置提供商的模型从已安装目录继承其等级,DeepSeek 的模型沿用适配器提供的等级。手动录入的模型在添加等级之前不声明任何等级,因此模型菜单里不会出现推理等级项,由端点自身的默认值决定模型是否思考。 -自定义模型 API 提供商可以在**设置 → 模型**中声明等级:编辑该提供商,打开**自定义设置**,展开该模型的**模型选项**,然后打开**推理等级**。默认带有 off、low、medium、high 四行。每行把一个档位与发送给它的 **API 参数值**配成一对,参数值默认与档位名相同;只有模型提供商的 API 文档写法不同时才需要修改。按端点支持的档位增删行,至少保留一个 off 以外的档位,然后保存。关闭开关会删除该声明。 +内置提供商和自定义模型 API 提供商都可以在**设置 → 模型**中声明等级:编辑该提供商,打开**自定义设置**,展开该模型的**模型选项**,然后打开**推理等级**。默认带有 off、low、medium、high 四行。每行把一个档位与发送给它的 **API 参数值**配成一对,参数值默认与档位名相同;只有模型提供商的 API 文档写法不同时才需要修改。按端点支持的档位增删行,至少保留一个 off 以外的档位,然后保存。为内置提供商的模型声明的等级会取代它继承的等级。关闭开关会删除该声明,内置提供商的模型随即重新继承其等级。 模型页会把 `reasoningEfforts` 写入 `$DSH_HOME/profiles//cordis.patch.yml`,也可以直接在其中声明等级: @@ -224,7 +224,7 @@ DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。 - **获取可用模型提示既没有 `data` 数组也没有 `models` 对象**:端点返回的列表格式不在探测的读取范围内。请手动输入模型。 - **密钥与地址都正确,网关却拒绝每一个请求**:它的请求形状与 OpenAI 不同。先在路由上设 `compat.supportsDeveloperRole: false` 与 `compat.maxTokensField: max_tokens`。 - **只有推理模型失败**:pi-ai 把它们的系统提示词以 `developer` 角色发出,而网关拒绝该角色。设 `compat.supportsDeveloperRole: false`。 -- **手动录入的模型没有推理等级菜单**:该模型没有声明任何等级。如果是自定义模型 API 提供商,在该模型的**模型选项**中打开**推理等级**;其他提供商在 `cordis.patch.yml` 中给该模型加上 `reasoningEfforts`。 +- **手动录入的模型没有推理等级菜单**:该模型没有声明任何等级。在该模型的**模型选项**中打开**推理等级**,或在 `cordis.patch.yml` 中给该模型加上 `reasoningEfforts`。 - **`off` 无法让 DeepSeek 模型停止思考**:留空的 `off` 不发送任何推理字段,默认思考的端点就继续思考。请在模型或路由上设置 `compat.thinkingFormat: deepseek`。 - **某个 compat 开关因没有值而被拒绝**:冒号后什么都没写。给它一个值,或删掉该键以沿用已安装 catalog 的值。 - **图片在发送前被拒绝**:该模型未声明图片模态。请给自定义提供商的模型加上 `input: [text, image]`;在 DeepSeek 自身的路由上,请从配置的目录中选择支持图片的条目(默认为 `deepseek-flash`),并确认网关提供该模型且支持图片输入。 diff --git a/package.json b/package.json index b92f86fc6c..4fa191933d 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "test:coverage": "pnpm run build:native-system && vitest run --coverage", "build:native-system": "tsx native/system/scripts/build.ts --host-addon-only", "test:coverage:partitioned": "tsx scripts/run-coverage-partitions.ts", + "test:coverage:merge-shards": "tsx scripts/merge-coverage-shards.ts", "test:e2e": "vitest run --config vitest.e2e.config.ts", "test:bench": "npm run build:bench && npm run build:web && npm run test:bench:built", "test:bench:built": "tsx scripts/run-bench-suite.ts", @@ -92,11 +93,16 @@ "check:ci:static": "tsx scripts/run-gates.ts ci-static", "check:ci:lint:contracts-ready": "tsx scripts/run-gates.ts ci-lint-contracts-ready", "check:ci:coverage": "tsx scripts/run-gates.ts ci-coverage", + "check:ci:coverage-shard": "tsx scripts/run-gates.ts ci-coverage-shard", "check:ci:unit": "tsx scripts/run-gates.ts ci-unit", "check:ci:bench": "tsx scripts/run-gates.ts ci-bench", + "check:ci:bench-prebuilt": "tsx scripts/run-gates.ts ci-bench-prebuilt", "check:ci:snapshot": "tsx scripts/run-gates.ts ci-snapshot", "check:ci:artifacts": "tsx scripts/run-gates.ts ci-artifacts", "check:ci:consumers": "tsx scripts/run-gates.ts ci-consumers", + "check:ci:build": "tsx scripts/run-gates.ts ci-build", + "check:ci:consumers-prebuilt": "tsx scripts/run-gates.ts ci-consumers-prebuilt", + "check:ci:web-snapshot-prebuilt": "tsx scripts/run-gates.ts ci-web-snapshot-prebuilt", "check:windows-wine": "bash scripts/wine-windows-gates.sh", "check:ci:windows-blocking": "tsx scripts/run-gates.ts ci-windows-blocking", "check:ci:windows-complete": "tsx scripts/run-gates.ts ci-windows-complete", diff --git a/packages/attachment/attachment-local/README.i18n.yaml b/packages/attachment/attachment-local/README.i18n.yaml index 2caf5e3785..241408d0ef 100644 --- a/packages/attachment/attachment-local/README.i18n.yaml +++ b/packages/attachment/attachment-local/README.i18n.yaml @@ -18,14 +18,17 @@ en: 912a19be4b59ff8a zh: 9c14694cf2ebbaf2 /deepseek-ai-dsh-attachment-local/use-this-package/minimal-configuration: - en: 9597c3d9779cb93d - zh: 900baa94138cc7de + en: 407c75c6f2e8834b + zh: 35dbcf0974fa78bb /deepseek-ai-dsh-attachment-local/use-this-package/where-your-images-are-stored-and-how-long-they-last: en: 4ee90b8f74baa38c zh: 9c577709ec55eb82 /deepseek-ai-dsh-attachment-local/use-this-package/what-happens-when-you-attach-an-image: en: 75ba799b1e4edba4 zh: 06c5f76200e8da8a +/deepseek-ai-dsh-attachment-local/use-this-package/request-image-byte-limits: + en: d2ad0b047828baf8 + zh: 9c22a4b87fafdbec /deepseek-ai-dsh-attachment-local/use-this-package/what-can-go-wrong: en: 377696b2dc08b170 zh: 6b831ef31c93f712 @@ -36,8 +39,8 @@ en: dcd9857653645420 zh: a27259a09f17465d /deepseek-ai-dsh-attachment-local/understand-the-implementation/write-and-read-paths: - en: 4cbbe8a1466ed46f - zh: 49d2d118501867d3 + en: 93c691ba1845b5bf + zh: c9902789a6611746 /deepseek-ai-dsh-attachment-local/understand-the-implementation/source-map: en: 05af85aa85934d01 zh: 1c89e80d496dc0a3 diff --git a/packages/attachment/attachment-local/README.md b/packages/attachment/attachment-local/README.md index b27ac0c75a..572e7b3b59 100644 --- a/packages/attachment/attachment-local/README.md +++ b/packages/attachment/attachment-local/README.md @@ -47,6 +47,8 @@ Mount the plugin with no required configuration. The defaults below define what | `normalizedImageMaxDimension` | `8192` | Maximum long edge after applying the total-pixel budget | | `normalizedImageMaxBytes` | `4 MiB` | Encoded-byte target; the smallest quality-ladder output is kept when none fits | | `imageCompressionConcurrency` | `2` | FIFO limit for concurrent normalization and request transforms | +| `requestImageMinShrinkFactor` | `1.1` | Minimum divisor of the request image long edge after a hard-byte overflow; greater than one | +| `requestImageByteHeadroom` | `0.95` | Fraction of the hard byte limit used to estimate the next size; in `(0, 1]` | The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-attachment-local) is the exhaustive source for every accepted field and its JSDoc. @@ -58,6 +60,10 @@ Attached images are kept below `/attachments/v1` on this machine. Stor Attach an image and its source limits, media, dimensions, and pixels are checked before it is normalized and saved. EXIF orientation is applied, metadata and color profiles are removed, transparency is preserved, and the raster is reduced under a total-pixel budget plus a long-edge cap. Alpha images use WebP and opaque images use JPEG on the shared 85/75/60 quality ladder; the smallest output is retained when every candidate exceeds the byte target. An accepted image reappears in history and later turns, including after restart; the selected model route receives a cached request version and, when its filesystem maps the host object, a read-only execution-world path. +### Request-image byte limits + +Model routes supply `maxImageBytes` as a hard encoded-byte limit and `imageTargetBytes` as a preferred target no greater than that limit. The encoder tries qualities 85, 75, and 60 at the requested dimensions. An output above only the preferred target keeps its resolution. If the smallest output still exceeds the hard limit, the long edge is divided by `max(requestImageMinShrinkFactor, sqrt(actualBytes / (requestImageByteHeadroom × maxImageBytes)))`, rounded down, and strictly reduced. Each attempt encodes the saved source at the new dimensions; it does not recompress the previous lossy result. The loop checks cancellation between encodings and fails with `IMAGE_REQUEST_TOO_LARGE` if even a 1×1 image cannot fit. Successful results and cache hits always satisfy the hard limit. Consumers use the returned width and height for coordinates. + ### What can go wrong An image can be refused when you attach it: unsupported format, over the byte, pixel, or per-side dimension limits, or bytes that do not match their declared type. On a later read, an image that was deleted or corrupted on disk fails with a clear error. Each failure carries a stable code so the client and protocol adapters can explain it in their own words. @@ -87,7 +93,7 @@ Image reads receive a complete reference with a canonical `sha256:` ID, derive t Admission accepts up to 20 images and 200 MiB of source bytes per message; one source may use up to 50 MiB, 64 million pixels, and 65,535 pixels per side. It applies orientation, removes metadata and color profiles, and normalizes under a 2048×2048 total-pixel budget, an 8192-pixel long edge, and a 4 MiB encoded-byte target. Extreme aspect ratios therefore retain their short-edge resolution. Clean single-frame 8-bit sRGB/sRGBA PNG, JPEG, or WebP input already within those limits passes through byte-identically; GIF, animation, metadata, orientation, 16-bit PNG, and incompatible color spaces force conversion. -Request versions live below `/cache/attachments/request-images/`, resolved by `dshCachePath`; an explicit `dshHome` setting applies to both cache and durable storage. Clearing this cache between requests preserves durable attachments, and later reads regenerate the variants. `readImageRequest` scales without enlargement to the route-chosen target, resizing by the long edge only so the encoder derives the short edge as the route predicts, then applies a separate encoded-byte target through the same alpha routing and quality ladder. Its cache identity includes the attachment id, transform version, target dimensions, byte target, and fixed encoder settings; cached bytes are header-probed for format, 8-bit sRGB/sRGBA, dimensions, and alpha facts, and a mismatch regenerates the entry. Concurrent callers share one transform and cache write, while cancellation stops shared work only when no waiter remains. `imageHostPath` derives the normalized object's host path, and the mounted filesystem may map that path into its execution world without writing it to durable history. +Request versions live below `/cache/attachments/request-images/`, resolved by `dshCachePath`; an explicit `dshHome` setting applies to both cache and durable storage. Clearing this cache between requests preserves durable attachments, and later reads regenerate the variants. `readImageRequest` scales without enlargement to the route-chosen target, resizing by the long edge only so the encoder derives the short edge as the route predicts, then enforces the route's preferred byte target and hard byte limit through the same alpha routing and quality ladder, reducing resolution further only for a hard-limit overflow. Its cache identity includes the attachment id, transform version, target dimensions, both byte limits, resize controls, and fixed encoder settings; cached bytes are header-probed for format, 8-bit sRGB/sRGBA, dimensions, alpha facts, and the hard byte limit, and a mismatch regenerates the entry. Concurrent callers share one transform and cache write, while cancellation stops shared work only when no waiter remains. `imageHostPath` derives the normalized object's host path, and the mounted filesystem may map that path into its execution world without writing it to durable history. Generic-file bytes have one canonical object at `/attachments/v1/file-objects//`. Each reference path at `/attachments/v1/files///` is a read-only hard link, so different names for equal bytes do not duplicate disk content. `readFileStream` reads the reference path in bounded chunks and verifies the complete digest and recorded byte count before a consumer can finish successfully. A missing, changed, or truncated object fails its consumer instead of producing a complete export with different bytes. diff --git a/packages/attachment/attachment-local/README.zh.md b/packages/attachment/attachment-local/README.zh.md index a0663aaebe..dff6007494 100644 --- a/packages/attachment/attachment-local/README.zh.md +++ b/packages/attachment/attachment-local/README.zh.md @@ -47,6 +47,8 @@ kind: "package-reference" | `normalizedImageMaxDimension` | `8192` | 应用总像素预算后的最大长边 | | `normalizedImageMaxBytes` | `4 MiB` | 编码字节目标;没有候选满足时保留质量阶梯中的最小输出 | | `imageCompressionConcurrency` | `2` | 并发规范化与请求变换的 FIFO 上限 | +| `requestImageMinShrinkFactor` | `1.1` | 请求图片超过硬字节上限后,长边缩小倍数的最小值;必须大于 1 | +| `requestImageByteHeadroom` | `0.95` | 估算下一次尺寸时使用的硬字节上限比例;范围为 `(0, 1]` | 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-attachment-local)完整列出了所有受支持的字段及其 JSDoc。 @@ -58,6 +60,10 @@ kind: "package-reference" 附加图片后,会先检查源图限制、媒体类型、尺寸与像素,再完成规范化并保存。系统应用 EXIF 方向、移除元数据与色彩配置、保留透明度,并按总像素预算与长边上限缩小光栅。带 alpha 的图片使用 WebP,不透明图片使用 JPEG,共享 85/75/60 质量阶梯;全部候选都超过字节目标时保留最小输出。被接受的图片会重新出现在历史和后续轮次中,重启后也不例外;所选模型路由会收到缓存的请求版本,并在其文件系统可映射宿主对象时收到只读执行世界路径。 +### 请求图片的字节限制 + +模型路由提供硬编码字节上限 `maxImageBytes`,以及不大于硬上限的目标 `imageTargetBytes`。编码器先在请求尺寸下尝试 85、75、60 三档质量。仅超过目标值的输出保持分辨率。最小结果仍超过硬上限时,长边除以 `max(requestImageMinShrinkFactor, sqrt(actualBytes / (requestImageByteHeadroom × maxImageBytes)))`,向下取整并确保严格减小。每次都从已保存的源图按新尺寸编码,不重复压缩上一轮有损结果。每轮编码之间检查取消状态;即使 1×1 图片仍无法满足上限时,以 `IMAGE_REQUEST_TOO_LARGE` 失败。成功结果和缓存命中均满足硬上限。调用方使用返回的实际宽高计算坐标。 + ### 可能出什么问题 附加图片时可能被拒绝:格式不受支持、超出字节、像素或单边尺寸限制,或者字节与声明类型不符。之后读取时,磁盘上被删除或损坏的图片会以明确错误失败。每个失败都带有稳定错误码,客户端与协议适配器可以用自己的措辞解释。 @@ -87,7 +93,7 @@ kind: "package-reference" 准入允许每条消息最多 20 张图片与 200 MiB 源字节;单个源图最多 50 MiB、6400 万像素与单边 65,535 像素。系统应用方向、移除元数据与色彩配置,并把规范化结果限制在 2048×2048 总像素预算、8192 像素长边和 4 MiB 编码字节目标内,因此,即使宽高比极端,图片也会保留短边分辨率。已经满足限制的干净、单帧、8-bit sRGB/sRGBA PNG、JPEG 或 WebP 会逐字节直通;GIF、动画、元数据、方向、16-bit PNG 与不兼容色彩空间会触发转换。 -请求版本位于由 `dshCachePath` 解析的 `/cache/attachments/request-images/`;显式 `dshHome` 设置同时适用于缓存与持久存储。在两次请求之间清空此缓存会保留持久附件,后续读取会重新生成请求版本。`readImageRequest` 在不放大的前提下缩放到路由选定的目标尺寸,缩放只按长边给定,短边由编码器按路由预测的方式推出,随后通过相同的 alpha 路由与质量阶梯应用独立编码字节目标。缓存身份包含附件 id、变换版本、目标尺寸、字节目标与固定编码参数;缓存字节会先通过文件头探测格式、8-bit sRGB/sRGBA、尺寸与 alpha 信息,不匹配时重新生成。并发调用方共享一次变换与缓存写入,且只在没有等待方时由取消停止共享工作。`imageHostPath` 派生规范化对象的宿主路径,挂载的文件系统可以把该路径映射进执行世界,而不会写入持久历史。 +请求版本位于 `/cache/attachments/request-images/`,由 `dshCachePath` 解析;显式 `dshHome` 同时用于缓存和持久存储。请求之间清空此缓存不会影响持久附件,后续读取会重新生成变体。`readImageRequest` 按路由目标缩放且不放大,沿长边调整以保持比例,再按相同的透明度分流和质量阶梯处理软目标及硬字节上限,仅在硬上限仍不满足时继续降低分辨率。缓存身份包含附件 id、变换版本、目标尺寸、两项字节限制、缩放参数和固定编码设置。缓存读取检查格式、8 位 sRGB/sRGBA、尺寸、透明度和硬字节上限,不匹配时重新生成。并发调用共享一次变换和缓存写入,仅在所有等待方均离开后取消共享工作。`imageHostPath` 派生规范化对象的宿主路径,文件系统可以将其映射到执行环境,不写入持久历史。 通用文件字节的唯一规范对象位于 `/attachments/v1/file-objects//`。每条引用路径 `/attachments/v1/files///` 都是只读硬链接,所以名称不同但字节相同的文件不会重复占用磁盘。`readFileStream` 以有界分块读取引用路径,并在消费方成功结束前校验完整摘要与记录的字节数。对象缺失、被改写或截断时,消费方会失败,不会得到字节已经变化的完整导出。 diff --git a/packages/attachment/attachment-local/src/encoding.ts b/packages/attachment/attachment-local/src/encoding.ts index 1b16aafb30..2ebbd49659 100644 --- a/packages/attachment/attachment-local/src/encoding.ts +++ b/packages/attachment/attachment-local/src/encoding.ts @@ -50,20 +50,20 @@ export interface ExhaustedEncoding { /** * Execute encoding candidates in preference order and stop after the first fitting output. * @param attempts - lazy encoders ordered from preferred to fallback representation. - * @param maxBytes - positive encoded-byte target. + * @param imageTargetBytes - positive encoded-byte target. * @returns the first fitting candidate, otherwise the smallest completed fallback. */ export async function encodeFirstWithinLimit( attempts: readonly (() => Promise)[], - maxBytes: number, + imageTargetBytes: number, ): Promise> { const [first, ...remaining] = attempts if (first === undefined) throw new Error('image encoding requires at least one candidate') let smallest = await first() - if (smallest.data.byteLength <= maxBytes) return smallest + if (smallest.data.byteLength <= imageTargetBytes) return smallest for (const attempt of remaining) { const candidate = await attempt() - if (candidate.data.byteLength <= maxBytes) return candidate + if (candidate.data.byteLength <= imageTargetBytes) return candidate if (candidate.data.byteLength < smallest.data.byteLength) { smallest = candidate } diff --git a/packages/attachment/attachment-local/src/index.ts b/packages/attachment/attachment-local/src/index.ts index 2965fef0cc..f836ab5297 100644 --- a/packages/attachment/attachment-local/src/index.ts +++ b/packages/attachment/attachment-local/src/index.ts @@ -23,12 +23,14 @@ import { readFileStreamVerbatim, saveFileStreamVerbatim, saveFileVerbatim, storedFilePath, } from './file-store.ts' import { readRequestImageFile, requestImageVariantId } from './request-image.ts' +import type { RequestImageResizePolicy } from './request-image.ts' export { canPassThroughNormalization, normalizeImage } from './normalization.ts' export type { NormalizedImage, NormalizationPolicy } from './normalization.ts' export { commitPreparedImageFile, prepareImageFile, readImageFile, saveImageFile, validateImageFile } from './store.ts' export type { PreparedImageFile } from './store.ts' export { readRequestImageFile, requestImageVariantId } from './request-image.ts' +export type { RequestImageResizePolicy } from './request-image.ts' /** Default maximum encoded bytes for one submitted image; oversized sources are refused, not shrunk. */ export const DEFAULT_MAX_IMAGE_BYTES = 50 * 1024 * 1024 @@ -61,6 +63,9 @@ export const DEFAULT_IMAGE_COMPRESSION_CONCURRENCY = 2 /** Maximum configurable native image transformations per store. */ export const MAX_IMAGE_COMPRESSION_CONCURRENCY = 8 +const DEFAULT_REQUEST_IMAGE_MIN_SHRINK_FACTOR = 1.1 +const DEFAULT_REQUEST_IMAGE_BYTE_HEADROOM = 0.95 + /** Local attachment backend configuration. */ export interface Config { /** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */ @@ -86,6 +91,10 @@ export interface Config { normalizedImageMaxBytes?: number /** Maximum simultaneous normalization or request-image transformations in this service instance. */ imageCompressionConcurrency?: number + /** Minimum long-edge shrink divisor after a request image exceeds its hard byte limit; must be greater than one. Default: 1.1. */ + requestImageMinShrinkFactor?: number + /** Fraction of the hard byte limit used to estimate the next request-image size; in (0, 1]. Default: 0.95. */ + requestImageByteHeadroom?: number } function abortReason(signal: AbortSignal): Error { @@ -159,6 +168,8 @@ export class LocalAttachmentStore extends AttachmentStore { normalizedImageMaxPixels: z.number().step(1).min(1).default(DEFAULT_NORMALIZED_IMAGE_MAX_PIXELS), normalizedImageMaxDimension: z.number().step(1).min(1).default(DEFAULT_NORMALIZED_IMAGE_MAX_DIMENSION), normalizedImageMaxBytes: z.number().step(1).min(1).default(DEFAULT_NORMALIZED_IMAGE_MAX_BYTES), + requestImageMinShrinkFactor: z.number().min(1 + Number.EPSILON).max(Number.MAX_VALUE).default(DEFAULT_REQUEST_IMAGE_MIN_SHRINK_FACTOR), + requestImageByteHeadroom: z.number().min(Number.MIN_VALUE).max(1).default(DEFAULT_REQUEST_IMAGE_BYTE_HEADROOM), imageCompressionConcurrency: z.number().step(1).min(1).max(MAX_IMAGE_COMPRESSION_CONCURRENCY) .default(DEFAULT_IMAGE_COMPRESSION_CONCURRENCY), }) @@ -170,6 +181,7 @@ export class LocalAttachmentStore extends AttachmentStore { readonly normalizationPolicy: Readonly /** Resolved instance-level compression limit. */ readonly imageCompressionConcurrency: number + private readonly requestImageResizePolicy: Readonly private readonly cacheRoot: string private readonly compression: CompressionLimiter private readonly requestInflight = new Map>() @@ -192,6 +204,15 @@ export class LocalAttachmentStore extends AttachmentStore { maxDimension: config.normalizedImageMaxDimension ?? DEFAULT_NORMALIZED_IMAGE_MAX_DIMENSION, maxBytes: config.normalizedImageMaxBytes ?? DEFAULT_NORMALIZED_IMAGE_MAX_BYTES, }) + const minShrinkFactor = config.requestImageMinShrinkFactor ?? DEFAULT_REQUEST_IMAGE_MIN_SHRINK_FACTOR + const byteHeadroom = config.requestImageByteHeadroom ?? DEFAULT_REQUEST_IMAGE_BYTE_HEADROOM + if (!Number.isFinite(minShrinkFactor) || minShrinkFactor <= 1) { + throw new Error('attachment-local: requestImageMinShrinkFactor must be a finite number greater than one') + } + if (!Number.isFinite(byteHeadroom) || byteHeadroom <= 0 || byteHeadroom > 1) { + throw new Error('attachment-local: requestImageByteHeadroom must be a finite number in (0, 1]') + } + this.requestImageResizePolicy = Object.freeze({ minShrinkFactor, byteHeadroom }) const compressionConcurrency = config.imageCompressionConcurrency ?? DEFAULT_IMAGE_COMPRESSION_CONCURRENCY if (!Number.isSafeInteger(compressionConcurrency) || compressionConcurrency < 1 @@ -264,7 +285,7 @@ export class LocalAttachmentStore extends AttachmentStore { signal: AbortSignal | undefined, ): Promise { signal?.throwIfAborted() - const variantId = requestImageVariantId(ref, target) + const variantId = requestImageVariantId(ref, target, this.requestImageResizePolicy) const key = String(variantId) let operation = this.requestInflight.get(key) if (operation?.controller.signal.aborted) { @@ -277,6 +298,7 @@ export class LocalAttachmentStore extends AttachmentStore { this.cacheRoot, stored ?? await this.readImage(ref, sharedSignal), target, + this.requestImageResizePolicy, sharedSignal, ) return request diff --git a/packages/attachment/attachment-local/src/request-image.ts b/packages/attachment/attachment-local/src/request-image.ts index a6140963d6..c0b0c1110b 100644 --- a/packages/attachment/attachment-local/src/request-image.ts +++ b/packages/attachment/attachment-local/src/request-image.ts @@ -4,7 +4,7 @@ import { createHash, randomUUID } from 'node:crypto' import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import type { Sharp } from 'sharp' -import { AttachmentError } from '@deepseek-ai/dsh-attachment' +import { AttachmentError, longEdgeDimensions, requestImageDimensions } from '@deepseek-ai/dsh-attachment' import type { ImageVariantId } from '@deepseek-ai/dsh-attachment/types' import { brandString } from '@deepseek-ai/dsh-brand' import type { @@ -25,7 +25,15 @@ import { detectImage, encodedAlphaIsCompatible, probeImage } from './image.ts' import { requireSharp } from './sharp.ts' /** Transform version included in every cache and upload-index identity. */ -export const REQUEST_IMAGE_TRANSFORM_VERSION = 'request-image-v6' +export const REQUEST_IMAGE_TRANSFORM_VERSION = 'request-image-v7' + +/** Resolved encoder controls for deterministic byte-limit enforcement. */ +export interface RequestImageResizePolicy { + /** Minimum divisor of the long edge after an oversized encoding; greater than one. */ + minShrinkFactor: number + /** Fraction of the hard byte limit used to estimate the next size; greater than zero and at most one. */ + byteHeadroom: number +} interface EncodedRequestImage { data: Uint8Array @@ -52,16 +60,22 @@ function checkedInteger(value: number, name: string): number { function validateTarget(target: ImageRequestTarget): void { checkedInteger(target.width, 'Image request width') checkedInteger(target.height, 'Image request height') - checkedInteger(target.maxBytes, 'Image request maxBytes') + checkedInteger(target.maxImageBytes, 'Image request maxImageBytes') + checkedInteger(target.imageTargetBytes, 'Image request imageTargetBytes') + if (target.imageTargetBytes > target.maxImageBytes) { + throw new AttachmentError('Image request imageTargetBytes must not exceed maxImageBytes.', 'INVALID_ATTACHMENT_REF') + } } -function descriptor(attachment: ImageAttachmentRef, target: ImageRequestTarget): string { +function descriptor(attachment: ImageAttachmentRef, target: ImageRequestTarget, policy: RequestImageResizePolicy): string { return JSON.stringify({ transformVersion: REQUEST_IMAGE_TRANSFORM_VERSION, attachmentId: attachment.attachmentId, targetWidth: target.width, targetHeight: target.height, - encodedByteBudget: target.maxBytes, + maxImageBytes: target.maxImageBytes, + imageTargetBytes: target.imageTargetBytes, + resize: { minShrinkFactor: policy.minShrinkFactor, byteHeadroom: policy.byteHeadroom }, encoding: { webpQualities: IMAGE_ENCODING_QUALITIES, webpEffort: WEBP_ENCODING_EFFORT, @@ -75,18 +89,20 @@ function descriptor(attachment: ImageAttachmentRef, target: ImageRequestTarget): /** * Complete deterministic identity for one attachment and route-chosen request target. * @param attachment - provider-independent durable normalized attachment reference. - * @param target - route-chosen dimensions and byte target. + * @param target - route-chosen dimensions, hard byte limit, and preferred byte target. + * @param policy - resolved size-reduction controls. * @returns branded digest over every request transform input. */ export function requestImageVariantId( attachment: ImageAttachmentRef, target: ImageRequestTarget, + policy: RequestImageResizePolicy, ): ImageVariantId { - return brandString(`sha256:${digest(descriptor(attachment, target))}`) + return brandString(`sha256:${digest(descriptor(attachment, target, policy))}`) } /** Resize by the source long edge only, so the encoder derives the short edge as the route predicts. */ -function pipeline(attachment: StoredImageAttachment, target: ImageRequestTarget): Sharp { +function pipeline(attachment: StoredImageAttachment, target: Pick): Sharp { const byWidth = attachment.ref.width >= attachment.ref.height return sourcePipeline(attachment) .resize({ ...byWidth ? { width: target.width } : { height: target.height }, withoutEnlargement: true }) @@ -101,10 +117,12 @@ async function createRequestImage( attachment: StoredImageAttachment, target: ImageRequestTarget, hasAlpha: boolean, + policy: RequestImageResizePolicy, + signal: AbortSignal | undefined, ): Promise { if (target.width >= attachment.ref.width && target.height >= attachment.ref.height - && attachment.data.byteLength <= target.maxBytes) { + && attachment.data.byteLength <= target.imageTargetBytes) { return { data: attachment.data, mediaType: attachment.ref.mediaType, @@ -112,11 +130,31 @@ async function createRequestImage( height: attachment.ref.height, } } - const encodedVersion = await encodeFirstWithinLimit( - encodingLadder(pipeline(attachment, target), hasAlpha), - target.maxBytes, - ) - return isExhaustedEncoding(encodedVersion) ? encodedVersion.smallest : encodedVersion + const source = attachment.ref + let dimensions = longEdgeDimensions(source.width, source.height, source.width >= source.height ? target.width : target.height) + if (dimensions.width > target.width || dimensions.height > target.height) { + dimensions = requestImageDimensions(source.width, source.height, Infinity, target.width, target.height) + } + for (;;) { + signal?.throwIfAborted() + const encoded = await encodeFirstWithinLimit( + encodingLadder(pipeline(attachment, dimensions), hasAlpha), + target.imageTargetBytes, + ) + signal?.throwIfAborted() + const candidate = isExhaustedEncoding(encoded) ? encoded.smallest : encoded + if (candidate.data.byteLength <= target.maxImageBytes) return candidate + const longEdge = Math.max(candidate.width, candidate.height) + if (longEdge === 1) { + throw new AttachmentError( + `Image still exceeds the ${target.maxImageBytes}-byte request limit at 1x1 pixels. Increase the image byte limit.`, + 'IMAGE_REQUEST_TOO_LARGE', + ) + } + const divisor = Math.max(policy.minShrinkFactor, Math.sqrt(candidate.data.byteLength / (policy.byteHeadroom * target.maxImageBytes))) + const nextEdge = Math.max(1, Math.min(longEdge - 1, Math.floor(longEdge / divisor))) + dimensions = longEdgeDimensions(attachment.ref.width, attachment.ref.height, nextEdge) + } } function cachePath(root: string, hash: string): string { @@ -131,6 +169,7 @@ async function readCached( ): Promise { try { const data = new Uint8Array(await readFile(path, { signal })) + if (data.byteLength > target.maxImageBytes) return undefined const detected = await probeImage(data) if (detected.depth !== 'uchar' || detected.space !== 'srgb' || detected.width > target.width || detected.height > target.height @@ -174,7 +213,8 @@ async function writeCached(path: string, data: Uint8Array): Promise { * Generate or reuse one request image below the local attachment cache root. * @param root - absolute attachment cache root; variants use its `request-images` child. * @param attachment - verified normalized attachment bytes and reference. - * @param target - exact route-chosen dimensions and byte target; a target above the source keeps the source size. + * @param target - maximum dimensions, hard byte limit, and preferred byte target; small sources are never enlarged. + * @param policy - resolved size-reduction controls. * @param signal - optional cancellation for cache I/O and image transformation. * @returns verified request bytes and deterministic variant identity. */ @@ -182,16 +222,17 @@ export async function readRequestImageFile( root: string, attachment: StoredImageAttachment, target: ImageRequestTarget, + policy: RequestImageResizePolicy, signal?: AbortSignal, ): Promise { signal?.throwIfAborted() validateTarget(target) const source = await probeImage(attachment.data) - const variantId = requestImageVariantId(attachment.ref, target) + const variantId = requestImageVariantId(attachment.ref, target, policy) const hash = String(variantId).slice('sha256:'.length) const path = cachePath(root, hash) const cached = await readCached(path, target, source.hasAlpha, signal) - const created = cached ?? await createRequestImage(attachment, target, source.hasAlpha) + const created = cached ?? await createRequestImage(attachment, target, source.hasAlpha, policy, signal) const version = cached ?? (created.data === attachment.data ? { ...created, hasAlpha: source.hasAlpha } : await verifyRequestImage(created, source.hasAlpha)) diff --git a/packages/attachment/attachment-local/tests/index.spec.ts b/packages/attachment/attachment-local/tests/index.spec.ts index 64c3977c9d..4e7f294fe5 100644 --- a/packages/attachment/attachment-local/tests/index.spec.ts +++ b/packages/attachment/attachment-local/tests/index.spec.ts @@ -66,6 +66,23 @@ describe('local attachment service', () => { } }) + it('validates request-image shrink controls in both schema and programmatic construction', () => { + for (const value of [0, 1, Infinity]) { + expect(() => LocalAttachmentStore.Config({ requestImageMinShrinkFactor: value })).toThrow() + expect(() => new LocalAttachmentStore(new Context(), { requestImageMinShrinkFactor: value })) + .toThrow(/requestImageMinShrinkFactor/) + } + for (const value of [0, 1.1, Infinity]) { + expect(() => LocalAttachmentStore.Config({ requestImageByteHeadroom: value })).toThrow() + expect(() => new LocalAttachmentStore(new Context(), { requestImageByteHeadroom: value })) + .toThrow(/requestImageByteHeadroom/) + } + expect(() => new LocalAttachmentStore(new Context(), { requestImageMinShrinkFactor: Number.NaN })) + .toThrow(/requestImageMinShrinkFactor/) + expect(() => new LocalAttachmentStore(new Context(), { requestImageByteHeadroom: Number.NaN })) + .toThrow(/requestImageByteHeadroom/) + }) + it('saves and reads through the service boundary', async () => { const dshHome = await mkdtemp(join(tmpdir(), 'dsh-attachment-service-')) try { @@ -86,7 +103,7 @@ describe('local attachment service', () => { String(ref.attachmentId).slice('sha256:'.length), )) await expect(readFile(hostPath)).resolves.toEqual(Buffer.from(data)) - const request = await service.readImageRequest(ref, { width: 1, height: 1, maxBytes: 1024 }) + const request = await service.readImageRequest(ref, { width: 1, height: 1, maxImageBytes: 1024, imageTargetBytes: 1024 }) expect(request).not.toHaveProperty('access') const fileData = Uint8Array.of(0, 1, 2, 255) diff --git a/packages/attachment/attachment-local/tests/request-image-verification.spec.ts b/packages/attachment/attachment-local/tests/request-image-verification.spec.ts index 693b36f737..11c1fea1d3 100644 --- a/packages/attachment/attachment-local/tests/request-image-verification.spec.ts +++ b/packages/attachment/attachment-local/tests/request-image-verification.spec.ts @@ -38,7 +38,9 @@ describe('request image verification', () => { const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) control.mismatch = true - await expect(attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 })) + await expect(attachments.readImageRequest(attachment, { + width: 22, height: 11, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + })) .rejects.toMatchObject({ code: 'ATTACHMENT_WRITE_FAILED', message: 'Encoded model-request image does not match its verified 8-bit sRGB metadata.', diff --git a/packages/attachment/attachment-local/tests/request-image.spec.ts b/packages/attachment/attachment-local/tests/request-image.spec.ts index bd27d0bf9d..45fddbb26d 100644 --- a/packages/attachment/attachment-local/tests/request-image.spec.ts +++ b/packages/attachment/attachment-local/tests/request-image.spec.ts @@ -4,6 +4,8 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import sharp from 'sharp' import { afterEach, describe, expect, it, vi } from 'vitest' +import * as encoding from '../src/encoding.ts' +import { readRequestImageFile } from '../src/request-image.ts' import { CompressionLimiter } from '../src/compression-limiter.ts' import LocalAttachmentStore from '../src/index.ts' @@ -25,17 +27,17 @@ async function image(width: number, height: number): Promise { }).png().toBuffer()) } -async function complexOpaqueAlphaImage(width: number, height: number): Promise { +async function complexAlphaImage(width: number, height: number, opaque = true): Promise { const pixels = new Uint8Array(width * height * 4) let state = 0x2545f491 for (let offset = 0; offset < pixels.length; offset += 4) { - for (let channel = 0; channel < 3; channel += 1) { + for (let channel = 0; channel < (opaque ? 3 : 4); channel += 1) { state ^= state << 13 state ^= state >>> 17 state ^= state << 5 pixels[offset + channel] = state & 0xff } - pixels[offset + 3] = 255 + if (opaque) pixels[offset + 3] = 255 } return new Uint8Array(await sharp(pixels, { raw: { width, height, channels: 4 }, @@ -58,7 +60,7 @@ describe('local request-image cache', () => { const stored = await attachments.readImage(attachment) const fileData = Uint8Array.of(0, 1, 2, 255) const file = await attachments.saveFile({ data: fileData, name: 'notes.bin' }) - const policy = { width: 22, height: 11, maxBytes: 4_096 } + const policy = { width: 22, height: 11, maxImageBytes: 4_096, imageTargetBytes: 4_096 } const initial = await attachments.readImageRequest(attachment, policy) const hash = String(initial.variantId).slice('sha256:'.length) const cacheRoot = join(dshHome, 'cache') @@ -86,7 +88,7 @@ describe('local request-image cache', () => { const first = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' }) const second = await attachments.saveImage({ data: await image(4, 8), mediaType: 'image/png' }) const firstStored = await attachments.readImage(first) - const policy = { width: 8, height: 8, maxBytes: 1024 * 1024 } + const policy = { width: 8, height: 8, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 } const request = await attachments.readImageRequest(first, policy) const batch = await Promise.all([first, second].map( @@ -101,12 +103,12 @@ describe('local request-image cache', () => { const attachments = await store() const attachment = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' }) - await expect(attachments.readImageRequest(attachment, { width: 0, height: 4, maxBytes: 100 })) + await expect(attachments.readImageRequest(attachment, { width: 0, height: 4, maxImageBytes: 100, imageTargetBytes: 100 })) .rejects.toThrow('Image request width must be a positive integer') - await expect(attachments.readImageRequest(attachment, { width: 8, height: 1.5, maxBytes: 100 })) + await expect(attachments.readImageRequest(attachment, { width: 8, height: 1.5, maxImageBytes: 100, imageTargetBytes: 100 })) .rejects.toThrow('Image request height must be a positive integer') - await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxBytes: 0 })) - .rejects.toThrow('Image request maxBytes must be a positive integer') + await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxImageBytes: 0, imageTargetBytes: 0 })) + .rejects.toThrow('Image request maxImageBytes must be a positive integer') }) it('resizes by the long edge to the exact target and keys the cache by target', async () => { @@ -118,13 +120,27 @@ describe('local request-image cache', () => { const wide = await attachments.saveImage({ data: await image(1920, 1080), mediaType: 'image/png' }) const tall = await attachments.saveImage({ data: await image(1080, 1920), mediaType: 'image/png' }) - const squareRequest = await attachments.readImageRequest(square, { width: 1302, height: 1302, maxBytes }) - const smallRequest = await attachments.readImageRequest(small, { width: 800, height: 800, maxBytes }) - const thinRequest = await attachments.readImageRequest(thin, { width: 4096, height: 20, maxBytes }) - const wideRequest = await attachments.readImageRequest(wide, { width: 1708, height: 961, maxBytes }) - const tallRequest = await attachments.readImageRequest(tall, { width: 961, height: 1708, maxBytes }) - const smaller = await attachments.readImageRequest(square, { width: 1024, height: 1024, maxBytes }) - const enlarged = await attachments.readImageRequest(thin, { width: 9000, height: 45, maxBytes }) + const squareRequest = await attachments.readImageRequest(square, { + width: 1302, height: 1302, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const smallRequest = await attachments.readImageRequest(small, { + width: 800, height: 800, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const thinRequest = await attachments.readImageRequest(thin, { + width: 4096, height: 20, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const wideRequest = await attachments.readImageRequest(wide, { + width: 1708, height: 961, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const tallRequest = await attachments.readImageRequest(tall, { + width: 961, height: 1708, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const smaller = await attachments.readImageRequest(square, { + width: 1024, height: 1024, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const enlarged = await attachments.readImageRequest(thin, { + width: 9000, height: 45, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) expect(squareRequest).toMatchObject({ width: 1302, height: 1302, mediaType: 'image/jpeg' }) expect(smallRequest).toMatchObject({ width: 800, height: 800, mediaType: 'image/png' }) @@ -141,28 +157,143 @@ describe('local request-image cache', () => { const attachments = await store() const attachment = await attachments.saveImage({ data: await image(1224, 1429), mediaType: 'image/png' }) const request = await attachments.readImageRequest(attachment, { - width: 1187, height: 1386, maxBytes: 2 * 1024 * 1024, + width: 1187, height: 1386, maxImageBytes: 2 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024, }) expect(request).toMatchObject({ width: 1187, height: 1386 }) await expect(sharp(request.data).metadata()).resolves.toMatchObject({ width: 1187, height: 1386 }) }) - it('keeps the smallest ladder output when the encoded-byte target is unreachable', async () => { + it('keeps dimensions when only the soft target is unreachable', async () => { const attachments = await store() const attachment = await attachments.saveImage({ data: await image(1, 1), mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 1, height: 1, maxBytes: 1 }) + const request = await attachments.readImageRequest(attachment, { width: 1, height: 1, maxImageBytes: 1024, imageTargetBytes: 1 }) expect(request.mediaType).toBe('image/jpeg') expect(request.bytes).toBeGreaterThan(1) expect(request).toMatchObject({ width: 1, height: 1 }) }) + it.each([false, true])('shrinks an oversized request until the encoded bytes fit, alpha=%s', async (alpha) => { + const attachments = await store() + let source = await complexAlphaImage(256, 128, false) + if (!alpha) source = new Uint8Array(await sharp(source).removeAlpha().png().toBuffer()) + const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) + const stored = await attachments.readImage(attachment) + const target = { width: 256, height: 128, maxImageBytes: 2048, imageTargetBytes: 2048 } + const request = await attachments.readImageRequest(attachment, target) + expect(request.bytes).toBeLessThanOrEqual(target.maxImageBytes) + expect(request.width).toBeLessThan(256) + expect(request.height).toBeLessThan(128) + await expect(sharp(request.data).metadata()).resolves.toMatchObject({ width: request.width, height: request.height }) + await expect(attachments.readImage(attachment)).resolves.toEqual(stored) + await expect(attachments.readImageRequest(attachment, target)).resolves.toEqual(request) + }) + + it('respects both dimension bounds before enforcing the byte limit', async () => { + const attachments = await store() + const source = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + const result = await attachments.readImageRequest(source, { width: 64, height: 4, maxImageBytes: 4096, imageTargetBytes: 4096 }) + expect(result).toMatchObject({ width: 8, height: 4 }) + }) + + it('makes the configured minimum shrink step when the encoded image barely exceeds its hard cap', async () => { + const attachments = await store() + const attachment = await attachments.saveImage({ data: await complexAlphaImage(128, 128, false), mediaType: 'image/png' }) + const baseline = await attachments.readImageRequest(attachment, { + width: 128, height: 128, maxImageBytes: 100_000, imageTargetBytes: 1, + }) + const result = await attachments.readImageRequest(attachment, { + width: 128, height: 128, maxImageBytes: baseline.bytes - 1, imageTargetBytes: 1, + }) + expect(result.width).toBeLessThanOrEqual(Math.floor(128 / 1.1)) + expect(result.bytes).toBeLessThan(baseline.bytes) + }) + + it('stops byte-limit resizing when the caller aborts an outstanding encoding', async () => { + const attachments = await store() + const ref = await attachments.saveImage({ data: await complexAlphaImage(128, 128, false), mediaType: 'image/png' }) + const source = await attachments.readImage(ref) + let entered!: () => void + let release!: () => void + const encodingStarted = new Promise((resolve) => { entered = resolve }) + const resumeEncoding = new Promise((resolve) => { release = resolve }) + const actual = encoding.encodeFirstWithinLimit + const encode = vi.spyOn(encoding, 'encodeFirstWithinLimit').mockImplementationOnce(async (attempts, target) => { + entered() + await resumeEncoding + return actual(attempts, target) + }) + const controller = new AbortController() + const reason = new Error('cancel between request-image encodings') + const result = readRequestImageFile(await home(), source, + { width: 128, height: 128, maxImageBytes: 1024, imageTargetBytes: 1024 }, + { minShrinkFactor: 1.1, byteHeadroom: 0.95 }, controller.signal) + .then(value => value, (error: unknown) => error) + try { + await encodingStarted + controller.abort(reason) + release() + expect(await result).toBe(reason) + expect(encode).toHaveBeenCalledTimes(1) + } finally { + release() + await result + encode.mockRestore() + } + }) + + it('rejects an impossible hard limit after reaching one pixel', async () => { + const attachments = await store() + const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + const request = attachments.readImageRequest(attachment, { width: 64, height: 32, maxImageBytes: 1, imageTargetBytes: 1 }) + await expect(request).rejects.toMatchObject({ code: 'IMAGE_REQUEST_TOO_LARGE' }) + await expect(request).rejects.toThrow('1x1 pixels') + }) + + it('rejects invalid soft targets and a soft target above the hard limit', async () => { + const attachments = await store() + const attachment = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' }) + for (const imageTargetBytes of [0, 1.5, 101]) { + await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxImageBytes: 100, imageTargetBytes })) + .rejects.toMatchObject({ code: 'INVALID_ATTACHMENT_REF' }) + } + }) + + it('rebuilds a cached image whose dimensions fit but whose actual bytes exceed the hard limit', async () => { + const dshHome = await home() + const attachments = new LocalAttachmentStore(new Context(), { dshHome }) + const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + const target = { width: 22, height: 11, maxImageBytes: 4096, imageTargetBytes: 4096 } + const initial = await attachments.readImageRequest(attachment, target) + const hash = String(initial.variantId).slice('sha256:'.length) + const path = join(dshHome, 'cache', 'attachments', 'request-images', hash.slice(0, 2), hash) + const oversized = Buffer.concat([initial.data, Buffer.alloc(target.maxImageBytes)]) + await expect(sharp(oversized).metadata()).resolves.toMatchObject({ width: 22, height: 11 }) + await writeFile(path, oversized) + const rebuilt = await attachments.readImageRequest(attachment, target) + expect(rebuilt.bytes).toBeLessThanOrEqual(target.maxImageBytes) + expect(rebuilt.data).toEqual(initial.data) + }) + + it('includes both byte limits and resize controls in the cache identity', async () => { + const dshHome = await home() + const attachments = new LocalAttachmentStore(new Context(), { dshHome }) + const source = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + const target = { width: 22, height: 11, maxImageBytes: 4096, imageTargetBytes: 1024 } + const original = await attachments.readImageRequest(source, target) + const softer = await attachments.readImageRequest(source, { ...target, imageTargetBytes: 2048 }) + const larger = await attachments.readImageRequest(source, { ...target, maxImageBytes: 8192 }) + const configured = new LocalAttachmentStore(new Context(), { dshHome, requestImageMinShrinkFactor: 1.5, requestImageByteHeadroom: 0.9 }) + const differentResize = await configured.readImageRequest(source, target) + expect(new Set([original, softer, larger, differentResize].map(item => item.variantId)).size).toBe(4) + }) + it('regenerates invalid, oversized, incompatible, or mismatched cached variants', async () => { const dshHome = await home() const attachments = new LocalAttachmentStore(new Context(), { dshHome }) const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) - const policy = { width: 22, height: 11, maxBytes: 4_096 } + const policy = { width: 22, height: 11, maxImageBytes: 4_096, imageTargetBytes: 4_096 } const initial = await attachments.readImageRequest(attachment, policy) const hash = String(initial.variantId).slice('sha256:'.length) const path = join(dshHome, 'cache', 'attachments', 'request-images', hash.slice(0, 2), hash) @@ -211,10 +342,18 @@ describe('local request-image cache', () => { data: await image(2048, 1024), mediaType: 'image/png', name: 'wide.png', }) - const squareRequest = await attachments.readImageRequest(square, { width: 800, height: 800, maxBytes: 1024 * 1024 }) - const wideRequest = await attachments.readImageRequest(wide, { width: 1130, height: 565, maxBytes: 1024 * 1024 }) - const repeated = await attachments.readImageRequest(wide, { width: 1130, height: 565, maxBytes: 1024 * 1024 }) - const low = await attachments.readImageRequest(wide, { width: 724, height: 362, maxBytes: 1024 * 1024 }) + const squareRequest = await attachments.readImageRequest(square, { + width: 800, height: 800, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const wideRequest = await attachments.readImageRequest(wide, { + width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const repeated = await attachments.readImageRequest(wide, { + width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const low = await attachments.readImageRequest(wide, { + width: 724, height: 362, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(squareRequest).toMatchObject({ width: 800, height: 800 }) expect(wideRequest).toMatchObject({ width: 1130, height: 565 }) @@ -254,8 +393,12 @@ describe('local request-image cache', () => { const photo = await attachments.saveImage({ data: photoSource, mediaType: 'image/png' }) const alpha = await attachments.saveImage({ data: alphaSource, mediaType: 'image/png' }) - const photoRequest = await attachments.readImageRequest(photo, { width: 128, height: 128, maxBytes: 1024 * 1024 }) - const alphaRequest = await attachments.readImageRequest(alpha, { width: 128, height: 128, maxBytes: 4_096 }) + const photoRequest = await attachments.readImageRequest(photo, { + width: 128, height: 128, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const alphaRequest = await attachments.readImageRequest(alpha, { + width: 128, height: 128, maxImageBytes: 64 * 1024, imageTargetBytes: 4_096, + }) expect(photoRequest.mediaType).toBe('image/jpeg') expect(alphaRequest.mediaType).toBe('image/webp') @@ -271,7 +414,9 @@ describe('local request-image cache', () => { }).toColourspace('rgb16').png().toBuffer()) const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 }) + const request = await attachments.readImageRequest(attachment, { + width: 22, height: 11, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(request.bytes).toBeLessThanOrEqual(1024 * 1024) expect(request.width * request.height).toBeLessThanOrEqual(16 * 16) @@ -282,10 +427,12 @@ describe('local request-image cache', () => { it('accepts a resized WebP request version that omits an all-opaque alpha plane', async () => { const attachments = await store() - const source = await complexOpaqueAlphaImage(64, 32) + const source = await complexAlphaImage(64, 32) const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 }) + const request = await attachments.readImageRequest(attachment, { + width: 22, height: 11, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(request.mediaType).toBe('image/webp') await expect(sharp(request.data).metadata()).resolves.toMatchObject({ hasAlpha: false }) @@ -307,7 +454,9 @@ describe('local request-image cache', () => { }).png().toBuffer()) const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 800, height: 800, maxBytes: 1024 * 1024 }) + const request = await attachments.readImageRequest(attachment, { + width: 800, height: 800, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(request).toMatchObject({ width: 800, height: 800 }) expect(request.bytes).toBeLessThanOrEqual(1024 * 1024) @@ -320,7 +469,7 @@ describe('local request-image cache', () => { }) const run = vi.spyOn(CompressionLimiter.prototype, 'run') const controller = new AbortController() - const policy = { width: 1130, height: 565, maxBytes: 1024 * 1024 } + const policy = { width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 } const cancelled = attachments.readImageRequest(attachment, policy, controller.signal) const completed = attachments.readImageRequest(attachment, policy) @@ -350,7 +499,7 @@ describe('local request-image cache', () => { const controller = new AbortController() const request = attachments.readImageRequest( attachment, - { width: 1130, height: 565, maxBytes: 1024 * 1024 }, + { width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 }, controller.signal, ) await vi.waitFor(() => { @@ -383,7 +532,7 @@ describe('local request-image cache', () => { return actualRead(ref, signal) }) const controller = new AbortController() - const policy = { width: 1130, height: 565, maxBytes: 1024 * 1024 } + const policy = { width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 } const cancelled = attachments.readImageRequest(attachment, policy, controller.signal) await vi.waitFor(() => { expect(calls).toBe(1) diff --git a/packages/attachment/attachment/README.i18n.yaml b/packages/attachment/attachment/README.i18n.yaml index 44c9125f4f..6499dbb687 100644 --- a/packages/attachment/attachment/README.i18n.yaml +++ b/packages/attachment/attachment/README.i18n.yaml @@ -39,8 +39,8 @@ en: bc4586bb4ce74464 zh: 5ffd0a0e7261bc24 /deepseek-ai-dsh-attachment/understand-the-implementation/service-operations: - en: b94d13fe133d8ce6 - zh: dd4064d20d510afc + en: f23e01288c418599 + zh: 9358d6126de1e576 /deepseek-ai-dsh-attachment/understand-the-implementation/source-map: en: 4fb4c96184c38169 zh: 015b06e4bfff4fcd diff --git a/packages/attachment/attachment/README.md b/packages/attachment/attachment/README.md index 075094dcc8..d25da84710 100644 --- a/packages/attachment/attachment/README.md +++ b/packages/attachment/attachment/README.md @@ -72,7 +72,9 @@ This section explains the design decisions behind the seam and the service opera ### Service operations -The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file and image references to `ctx.attachments.admitPromptContent()`; the method persists the encoded images, passes references unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of the upload that stored it. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, target dimensions, byte target, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). +The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file and image references to `ctx.attachments.admitPromptContent()`; the method persists the encoded images, passes references unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of the upload that stored it. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, maximum dimensions, hard and preferred byte limits, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget with optional width/height limits or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). + +Successful request-image reads satisfy `ImageRequestTarget.maxImageBytes`. `imageTargetBytes` is a preferred target no greater than the hard limit. Further resizing is allowed only when the encoded image still exceeds the hard limit; callers use the returned dimensions, and an impossible one-pixel limit fails with `IMAGE_REQUEST_TOO_LARGE`. ### Source map diff --git a/packages/attachment/attachment/README.zh.md b/packages/attachment/attachment/README.zh.md index 400cc79c1e..aa5e7a8332 100644 --- a/packages/attachment/attachment/README.zh.md +++ b/packages/attachment/attachment/README.zh.md @@ -72,7 +72,9 @@ kind: "package-reference" ### 服务操作 -服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件与图片引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化编码图片,让引用原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按存储它的那次上传的字节数计入。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、目标尺寸、字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 +服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件与图片引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化编码图片,让引用原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按存储它的那次上传的字节数计入。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、最大尺寸、硬字节上限、软字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算及可选宽高限制,或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 + +成功的请求图片读取结果满足 `ImageRequestTarget.maxImageBytes`。`imageTargetBytes` 是不大于硬上限的软目标。只有编码结果仍超过硬上限时才继续降低尺寸;调用方使用返回的实际尺寸。连一个像素的图片也无法满足上限时,以 `IMAGE_REQUEST_TOO_LARGE` 失败。 ### 源码地图 diff --git a/packages/attachment/attachment/src/error.ts b/packages/attachment/attachment/src/error.ts index 2a933daa08..0f120bbc56 100644 --- a/packages/attachment/attachment/src/error.ts +++ b/packages/attachment/attachment/src/error.ts @@ -26,6 +26,7 @@ const ATTACHMENT_ERROR_CODES = [ 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', + 'IMAGE_REQUEST_TOO_LARGE', 'ATTACHMENT_FILES_UNSUPPORTED', ] as const diff --git a/packages/attachment/attachment/src/index.ts b/packages/attachment/attachment/src/index.ts index 802df0cb6b..ab91a069d3 100644 --- a/packages/attachment/attachment/src/index.ts +++ b/packages/attachment/attachment/src/index.ts @@ -270,9 +270,9 @@ export abstract class AttachmentStore extends Service { /** * Generate or read one deterministic model-request version from the stored normalized image. * @param ref - durable provider-independent normalized attachment reference. - * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output. + * @param target - route-chosen maximum dimensions, hard byte limit, and preferred byte target. * @param signal - optional cancellation. - * @returns request bytes and the cache/upload identity covering every transform input. + * @returns request bytes within the hard limit, actual encoded dimensions, and a cache/upload identity covering every transform input. */ readImageRequest( ref: ImageAttachmentRef, diff --git a/packages/attachment/attachment/src/request-projection.ts b/packages/attachment/attachment/src/request-projection.ts index 4e809a3632..5c1d15169a 100644 --- a/packages/attachment/attachment/src/request-projection.ts +++ b/packages/attachment/attachment/src/request-projection.ts @@ -10,18 +10,22 @@ export interface ProjectedDimensions { } /** - * Compute aspect-preserving integer dimensions within a hard total-pixel budget. + * Compute aspect-preserving integer dimensions within total-pixel, width, and height limits. * @param width - positive source width. * @param height - positive source height. * @param maxPixels - positive width-times-height cap. + * @param maxWidth - optional maximum width in pixels. + * @param maxHeight - optional maximum height in pixels. * @returns inward-rounded dimensions; small images are not enlarged. */ export function requestImageDimensions( width: number, height: number, maxPixels: number, + maxWidth = Infinity, + maxHeight = Infinity, ): ProjectedDimensions { - const scale = Math.min(1, Math.sqrt(maxPixels / (width * height))) + const scale = Math.min(1, Math.sqrt(maxPixels / (width * height)), maxWidth / width, maxHeight / height) if (scale === 1) return { width, height } if (width >= height) { let projectedWidth = Math.max(1, Math.floor(width * scale)) diff --git a/packages/attachment/attachment/src/types.ts b/packages/attachment/attachment/src/types.ts index f003d65254..eb3fdfb574 100644 --- a/packages/attachment/attachment/src/types.ts +++ b/packages/attachment/attachment/src/types.ts @@ -140,12 +140,14 @@ export interface StoredImageAttachment { /** Deterministic request-image target selected by one exact model route for one attachment. */ export interface ImageRequestTarget { - /** Target width in pixels; a target above the source keeps the source width. */ + /** Maximum request width in pixels; byte-limit enforcement can produce a smaller image. */ width: number - /** Target height in pixels; a target above the source keeps the source height. */ + /** Maximum request height in pixels; byte-limit enforcement can produce a smaller image. */ height: number - /** Encoded-byte target before base64 expansion or Files API upload; the smallest quality-ladder output is kept when no quality fits. */ - maxBytes: number + /** Hard encoded-byte limit before base64 expansion or Files API upload; successful results never exceed it. */ + maxImageBytes: number + /** Preferred encoded-byte target, no greater than maxImageBytes; exceeding only this target does not reduce resolution. */ + imageTargetBytes: number } /** Cached request version derived from one provider-independent normalized attachment. */ diff --git a/packages/attachment/attachment/tests/index.spec.ts b/packages/attachment/attachment/tests/index.spec.ts index e30615e53b..d8daa3d575 100644 --- a/packages/attachment/attachment/tests/index.spec.ts +++ b/packages/attachment/attachment/tests/index.spec.ts @@ -154,12 +154,14 @@ describe('AttachmentStore.readImageRequest', () => { it('reports unsupported request projection while preserving cancellation', async () => { const store = new UnsupportedProjectionStore(new Context()) const ref = await new RecordingStore(new Context()).saveImage(image(1)) - await expect(store.readImageRequest(ref, { width: 1, height: 1, maxBytes: 1 })) + await expect(store.readImageRequest(ref, { width: 1, height: 1, maxImageBytes: 1, imageTargetBytes: 1 })) .rejects.toMatchObject({ code: 'ATTACHMENT_PROJECTION_UNSUPPORTED' }) const controller = new AbortController() const reason = new Error('cancel unsupported projection') controller.abort(reason) - expect(() => store.readImageRequest(ref, { width: 1, height: 1, maxBytes: 1 }, controller.signal)).toThrow(reason) + expect(() => store.readImageRequest(ref, { + width: 1, height: 1, maxImageBytes: 1, imageTargetBytes: 1, + }, controller.signal)).toThrow(reason) }) it('rejects generic-file storage and exposes no provider-owned host path by default', async () => { diff --git a/packages/attachment/attachment/tests/request-projection.spec.ts b/packages/attachment/attachment/tests/request-projection.spec.ts index 2db1578863..edd58c0539 100644 --- a/packages/attachment/attachment/tests/request-projection.spec.ts +++ b/packages/attachment/attachment/tests/request-projection.spec.ts @@ -23,6 +23,22 @@ describe('request image dimensions', () => { expect(projected.width * projected.height).toBeLessThanOrEqual(640_000) }) + it.each([ + [1146, 3657, 4194304, 2000, 2000, 627, 2000], + [3657, 1146, 4194304, 2000, 2000, 2000, 627], + [4000, 800, 4194304, 3000, 300, 1500, 300], + [800, 4000, 4194304, 300, 3000, 300, 1500], + [4000, 4000, 1000000, 2000, 2000, 1000, 1000], + [320, 240, 4194304, 2000, 2000, 320, 240], + [1, 8192, 4194304, 2000, 2000, 1, 2000], + ])('fits %sx%s within %s pixels and %sx%s', (width, height, pixels, maxWidth, maxHeight, expectedWidth, expectedHeight) => { + const projected = requestImageDimensions(width, height, pixels, maxWidth, maxHeight) + expect(projected).toEqual({ width: expectedWidth, height: expectedHeight }) + expect(projected.width * projected.height).toBeLessThanOrEqual(pixels) + expect(projected.width).toBeLessThanOrEqual(maxWidth) + expect(projected.height).toBeLessThanOrEqual(maxHeight) + }) + it('rounds a portrait inward when integer aspect rounding crosses the pixel cap', () => { expect(requestImageDimensions(2, 4, 5)).toEqual({ width: 1, height: 2 }) }) diff --git a/packages/boot/plugin-manager/README.i18n.yaml b/packages/boot/plugin-manager/README.i18n.yaml index 3aaf2eab14..b1769306fa 100644 --- a/packages/boot/plugin-manager/README.i18n.yaml +++ b/packages/boot/plugin-manager/README.i18n.yaml @@ -15,8 +15,8 @@ en: 87679c51aa3693f5 zh: 11684a48a5806afb /deepseek-ai-dsh-plugin-manager/use-this-package: - en: ff51b012b845dd8a - zh: 1c6131057ff98844 + en: ab504ec577c22c52 + zh: 2651009eb331ba71 /deepseek-ai-dsh-plugin-manager/use-this-package/version-compatibility-and-exemptions: en: 483285658e267dd5 zh: 846bec2daac59a96 diff --git a/packages/boot/plugin-manager/README.md b/packages/boot/plugin-manager/README.md index a010e6d6d5..5eb21327c5 100644 --- a/packages/boot/plugin-manager/README.md +++ b/packages/boot/plugin-manager/README.md @@ -28,7 +28,7 @@ Manage the current profile's plugins without editing configuration by hand. Enab ## Use this package -Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard and Creator presets. Other Web presets keep it disabled by default. The full SDK profile enables it at profile scope in native/PTC mode; without HMR, saved changes return `restart-required` with `no-hmr` and apply after the runtime restarts. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate. +Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard, PTC, and Creator presets. Other Web presets keep it disabled by default. The full SDK profile enables it at profile scope in native/PTC mode; without HMR, saved changes return `restart-required` with `no-hmr` and apply after the runtime restarts. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate. For a deployment without agent presets other than the full SDK profile, enable the tool in the profile patch. Package installation/removal requires pnpm on `PATH` or an explicit `pnpmCommand`; a launcher-provided package manager takes precedence. Preset-backed sessions use their preset’s `tool-plugin-manager` entry. diff --git a/packages/boot/plugin-manager/README.zh.md b/packages/boot/plugin-manager/README.zh.md index 8bcea7e870..e47b13bb51 100644 --- a/packages/boot/plugin-manager/README.zh.md +++ b/packages/boot/plugin-manager/README.zh.md @@ -28,7 +28,7 @@ kind: "package-reference" ## 使用本包 -基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准和 Creator 预设中启用。其他 Web 预设仍默认禁用。完整 SDK profile 在 profile 作用域为 native/PTC 模式启用此工具;没有 HMR 时,保存的变更返回 `restart-required` 和 `no-hmr`,在运行时重启后应用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 +基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准、PTC 和 Creator 预设中启用。其他 Web 预设仍默认禁用。完整 SDK profile 在 profile 作用域为 native/PTC 模式启用此工具;没有 HMR 时,保存的变更返回 `restart-required` 和 `no-hmr`,在运行时重启后应用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 除完整 SDK profile 外,未使用 Agent 预设的部署在 profile patch 中启用工具;安装/移除包要求 PATH 中有 pnpm,或显式配置 `pnpmCommand`,启动器提供的包管理器优先;使用预设的会话由其预设中的 `tool-plugin-manager` 条目控制。 diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index 0b6727fc8f..62131ae0f6 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -30,8 +30,8 @@ en: df205a26b6d49168 zh: e46ed7cf9e06248a /deepseek-ai-dsh-web-app/use-this-package/per-session-agent-setup: - en: 1e33a677bcad2e4e - zh: 7a69b71a6b98c432 + en: 99557925a59aee67 + zh: e2160750bd65505a /deepseek-ai-dsh-web-app/understand-the-implementation: en: 567cf3afa68e6b68 zh: f065cdb56c28d4e6 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index 0e88e3eea0..cd25003dc8 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -96,7 +96,7 @@ When you launch `dsh --profile web` over SSH, the URL line still prints but the ### Per-session agent setup -Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard and Creator enable the plugin-management tool only when the Host provides an editable profile. +Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard, PTC, and Creator enable the plugin-management tool only when the Host provides an editable profile. Both modes expose read-only runtime inspection through `cordis_inspect`; see [its context effects](../../extensions/tool-cordis/README.md#model-experience). Standard, PTC, and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index de93466c6d..5937ff182d 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -96,7 +96,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- ### 按会话的 agent 设置 -每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式和 Creator 才会启用插件管理工具。 +每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式、PTC 模式和 Creator 才会启用插件管理工具。 两种模式均通过 `cordis_inspect` 提供只读运行时检查;参见[其上下文影响](../../extensions/tool-cordis/README.zh.md#model-experience)。标准模式、PTC 模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index dd935b1edd..8de9ed6727 100644 --- a/packages/bundle/web-app/presets/ptc.patch.yml +++ b/packages/bundle/web-app/presets/ptc.patch.yml @@ -135,7 +135,7 @@ name: '@deepseek-ai/dsh-tool-office' - id: tool-plugin-manager name: '@deepseek-ai/dsh-plugin-manager/tools' - disabled: true + disabled: !!js "!ctx.get('profileContext')" - id: tool-plugin-market name: '@deepseek-ai/dsh-plugin-market/tools' disabled: true diff --git a/packages/client/ui-agent-preset/src/client/guide-locales.ts b/packages/client/ui-agent-preset/src/client/guide-locales.ts index 2401935497..3c4af46d2c 100644 --- a/packages/client/ui-agent-preset/src/client/guide-locales.ts +++ b/packages/client/ui-agent-preset/src/client/guide-locales.ts @@ -30,7 +30,7 @@ export const guideEn = { '### What reaches the model', 'Tool results first reach the program, which can filter and combine them. The model receives what the program prints or returns; image results are attached separately. Nested tool calls are still recorded and remain subject to tool permissions.', '### Compared with Standard mode', - 'Both modes can handle coding and batch tasks. Standard mode exposes individual tools directly; PTC organizes tool calls in code. The current PTC preset leaves the workflow and plugin management tools disabled. Speed and token use depend on the task and how the program handles its results.', + 'Both modes can handle coding and batch tasks. Standard mode exposes individual tools directly; PTC organizes tool calls in code. The current PTC preset leaves the workflow tool disabled. Speed and token use depend on the task and how the program handles its results.', ].join('\n\n'), guidePtcUsage: [ '### Check a set of configuration files', @@ -109,7 +109,7 @@ export const guideZh: Record = { '### 哪些结果交给模型', '工具返回的数据先交给程序,经过筛选、计算或合并,再通过输出或返回值交给模型;图片结果会另行附加。程序中的工具调用仍会被记录,也仍受工具权限约束。', '### 与标准模式的区别', - '两种模式都能编程、批量处理文件。标准模式直接向模型提供各个工具;PTC 让模型用代码组织工具调用。当前 PTC 预设未启用 workflow 和插件管理工具。速度和 token 用量取决于具体任务与结果处理方式。', + '两种模式都能编程、批量处理文件。标准模式直接向模型提供各个工具;PTC 让模型用代码组织工具调用。当前 PTC 预设未启用 workflow 工具。速度和 token 用量取决于具体任务与结果处理方式。', ].join('\n\n'), guidePtcUsage: [ '### 批量检查配置文件', @@ -166,7 +166,7 @@ export const guideJa = { 'guideStandardExplanation': '### 仕組み\n\nエージェントはツールを直接呼び出してファイルの読み取りや編集、検索、ターミナルコマンドの実行を行います。スキル、計画、目標、サブエージェント、ワークフロー、プラグイン管理、読み取り専用のランタイム検査、コンテキストの圧縮に対応しています。\n\n### 選ぶべき場面\n\n日々のコーディング、ファイル作業、調査はまずここから始めてください。標準モードではスクリプトの作成やファイルの一括処理も行えます。PTC はツール呼び出しの構成を変えるものであり、一括処理に必須ではありません。', 'guideStandardUsage': '### バグを修正する\n\n> 検索フォームを二度送信すると結果が消える原因を調べてください。修正して関連するテストを実行し、原因と変更内容を説明してください。\n\n期待される出力: コードの変更、関連するテスト結果、原因の説明。\n\n### プロジェクトのメモを整理する\n\n> このプロジェクト内の Markdown メモを読み、合意された決定と未解決の課題を、元ファイルへのリンク付きで要約してください。\n\n期待される出力: 元のメモと照合できる参照付きの要約。', 'guidePtcIntro': '新しいタスクを始めるときは PTC モードを選びます。入力ファイル、処理ルール、出力形式を指定してください。コードはエージェントが書きます。', - 'guidePtcExplanation': '### ツールの呼び出され方\n\nPTC は Programmatic Tool Calling の略です。この組み込みプリセットでは、エージェントは run_code を使い、生成された SDK 経由でツールを呼び出す TypeScript プログラムを書きます。プログラムではループ、条件分岐、エラー処理、必要に応じて並行呼び出しを利用できます。\n\n### モデルに届くもの\n\nツールの結果はまずプログラムに届き、そこでフィルタリングや結合ができます。モデルが受け取るのはプログラムが出力または返した内容です。画像の結果は別途添付されます。ネストされたツール呼び出しも記録され、ツール権限の対象のままです。\n\n### 標準モードとの比較\n\nどちらのモードもコーディングや一括処理のタスクを扱えます。標準モードは個々のツールを直接公開し、PTC はツール呼び出しをコードで整理します。現在の PTC プリセットではワークフローとプラグイン管理ツールが無効になっています。速度とトークン消費はタスクやプログラムの結果の扱い方によって変わります。', + 'guidePtcExplanation': '### ツールの呼び出され方\n\nPTC は Programmatic Tool Calling の略です。この組み込みプリセットでは、エージェントは run_code を使い、生成された SDK 経由でツールを呼び出す TypeScript プログラムを書きます。プログラムではループ、条件分岐、エラー処理、必要に応じて並行呼び出しを利用できます。\n\n### モデルに届くもの\n\nツールの結果はまずプログラムに届き、そこでフィルタリングや結合ができます。モデルが受け取るのはプログラムが出力または返した内容です。画像の結果は別途添付されます。ネストされたツール呼び出しも記録され、ツール権限の対象のままです。\n\n### 標準モードとの比較\n\nどちらのモードもコーディングや一括処理のタスクを扱えます。標準モードは個々のツールを直接公開し、PTC はツール呼び出しをコードで整理します。現在の PTC プリセットではワークフローツールが無効になっています。速度とトークン消費はタスクやプログラムの結果の扱い方によって変わります。', 'guidePtcUsage': '### 設定ファイルのセットを検証する\n\n> configs/ 内のすべての JSON ファイルを検査してください。schema.json に基づき、必須フィールドの欠落と無効な値を一覧にしてください。問題ごとに 1 行の CSV を保存してください。読み取れないファイルもレポートに含め、残りの検査は続けてください。元のファイルは変更しないでください。\n\n期待される出力: 問題の要約と CSV レポート。プログラムは同じ検査を繰り返し、個々の失敗に対処し、結果を集約できます。\n\n### エラーログを要約する\n\n> logs/ 内のログファイルを分析してください。エラーをサービスとエラー種別でグループ化し、頻度上位 10 グループと各 1 件の例を示してください。完全な件数を CSV に保存してください。\n\n期待される出力: 上位のエラーグループと完全な件数表。中間データは要約がモデルに届く前にプログラム内で集約できます。', 'guideMinimalIntro': '新しいタスクには最小モードを選びます。比較を行う場合は、モデル、権限、入力、開始時のワークスペース状態を実行間で一定に保ってください。', 'guideMinimalExplanation': '### 含まれるもの\n\n永続的なシェルツール 1 つ、read_image、固定のシステムプロンプト。画像の読み取りには画像対応モデルが必要です。古い履歴はコンテキストの負荷に応じて自動的に圧縮されます。エージェントがアイドル状態のときに /compact を使えば手動で圧縮できます。この組み込みプリセットはスキル、計画、標準のランタイムコンテキストを読み込みません。\n\n### 選ぶべき場面\n\n実験や比較のベースラインとして使用します。シェルコマンド経由でファイルの読み取りやスクリプトの実行はできますが、長いタスクを管理するための組み込み手段は少なくなります。ツールが少ないからといって、初心者にとって必ずしも簡単になるわけではありません。', @@ -207,7 +207,7 @@ export const guideEs = { '### Lo que llega al modelo', 'Los resultados de la herramienta llegan primero al programa, que puede filtrarlos y combinarlos. El modelo recibe lo que el programa imprime o devuelve; Los resultados de la imagen se adjuntan por separado. Las llamadas a herramientas anidadas aún se registran y permanecen sujetas a los permisos de la herramienta.', '### Comparado con el modo Estándar', - 'Ambos modos pueden manejar tareas de codificación y por lotes. El modo estándar expone herramientas individuales directamente; PTC organiza llamadas a herramientas en código. El ajuste preestablecido actual PTC deja las herramientas de administración de complementos y flujo de trabajo deshabilitadas. La velocidad y el uso de tokens dependen de la tarea y de cómo el programa maneja sus resultados.', + 'Ambos modos pueden manejar tareas de codificación y por lotes. El modo estándar expone herramientas individuales directamente; PTC organiza llamadas a herramientas en código. El ajuste preestablecido actual PTC deja deshabilitada la herramienta de flujo de trabajo. La velocidad y el uso de tokens dependen de la tarea y de cómo el programa maneja sus resultados.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Verifique un conjunto de archivos de configuración', @@ -282,7 +282,7 @@ export const guideFr = { '### Ce qui arrive au modèle', "Les résultats des outils parviennent d’abord au programme, qui peut les filtrer et les combiner. Le modèle reçoit ce que le programme imprime ou renvoie ; les résultats des images sont joints séparément. Les appels d'outils imbriqués sont toujours enregistrés et restent soumis aux autorisations de l'outil.", '### Par rapport au mode Standard', - "Les deux modes peuvent gérer les tâches de codage et par lots. Le mode standard expose directement les outils individuels ; PTC organise les appels d'outils dans le code. Le préréglage PTC actuel laisse les outils de gestion de flux de travail et de plugins désactivés. La vitesse et l'utilisation des jetons dépendent de la tâche et de la manière dont le programme gère ses résultats.", + "Les deux modes peuvent gérer les tâches de codage et par lots. Le mode standard expose directement les outils individuels ; PTC organise les appels d'outils dans le code. Le préréglage PTC actuel laisse l’outil de flux de travail désactivé. La vitesse et l'utilisation des jetons dépendent de la tâche et de la manière dont le programme gère ses résultats.", ].join('\n\n\n\n'), guidePtcUsage: [ '### Vérifier un ensemble de fichiers de configuration', @@ -357,7 +357,7 @@ export const guideDe = { '### Was das Modell erreicht', 'Werkzeugergebnisse gelangen zunächst in das Programm, das diese filtern und kombinieren kann. Das Modell empfängt, was das Programm ausgibt oder zurückgibt; Bildergebnisse sind separat beigefügt. Verschachtelte Werkzeugaufrufe werden weiterhin aufgezeichnet und unterliegen weiterhin den Werkzeugberechtigungen.', '### Im Vergleich zum Standardmodus', - 'Beide Modi können Codierungs- und Batch-Aufgaben bewältigen. Im Standardmodus werden einzelne Tools direkt verfügbar gemacht. PTC organisiert Toolaufrufe im Code. Die aktuelle Voreinstellung PTC lässt die Workflow- und Plugin-Verwaltungstools deaktiviert. Geschwindigkeit und Token-Nutzung hängen von der Aufgabe ab und davon, wie das Programm mit seinen Ergebnissen umgeht.', + 'Beide Modi können Codierungs- und Batch-Aufgaben bewältigen. Im Standardmodus werden einzelne Tools direkt verfügbar gemacht. PTC organisiert Toolaufrufe im Code. Die aktuelle Voreinstellung PTC lässt das Workflow-Tool deaktiviert. Geschwindigkeit und Token-Nutzung hängen von der Aufgabe ab und davon, wie das Programm mit seinen Ergebnissen umgeht.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Überprüfen Sie eine Reihe von Konfigurationsdateien', @@ -432,7 +432,7 @@ export const guideRu = { '### Что достигает модели', 'Результаты инструмента сначала поступают в программу, которая может их фильтровать и комбинировать. Модель получает то, что программа печатает или возвращает; Результаты изображения прилагаются отдельно. Вызовы вложенных инструментов по-прежнему записываются, и для них действуют разрешения инструмента.', '### По сравнению со стандартным режимом', - 'Оба режима могут выполнять кодирование и пакетные задачи. Стандартный режим напрямую предоставляет доступ к отдельным инструментам; PTC организует вызовы инструментов в коде. Текущая предустановка PTC оставляет инструменты управления рабочим процессом и плагинами отключенными. Скорость и использование токенов зависят от задачи и того, как программа обрабатывает ее результаты.', + 'Оба режима могут выполнять кодирование и пакетные задачи. Стандартный режим напрямую предоставляет доступ к отдельным инструментам; PTC организует вызовы инструментов в коде. Текущая предустановка PTC оставляет инструмент рабочего процесса отключенным. Скорость и использование токенов зависят от задачи и того, как программа обрабатывает ее результаты.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Проверка набора файлов конфигурации', @@ -507,7 +507,7 @@ export const guidePt = { '### O que chega ao modelo', 'Os resultados da ferramenta chegam primeiro ao programa, que pode filtrá-los e combiná-los. O modelo recebe o que o programa imprime ou retorna; os resultados da imagem são anexados separadamente. As chamadas de ferramentas aninhadas ainda são gravadas e permanecem sujeitas às permissões da ferramenta.', '### Comparado com o modo Padrão', - 'Ambos os modos podem lidar com tarefas de codificação e em lote. O modo padrão expõe ferramentas individuais diretamente; PTC organiza chamadas de ferramentas em código. A predefinição PTC atual deixa o fluxo de trabalho e as ferramentas de gerenciamento de plug-ins desativados. A velocidade e o uso do token dependem da tarefa e de como o programa lida com seus resultados.', + 'Ambos os modos podem lidar com tarefas de codificação e em lote. O modo padrão expõe ferramentas individuais diretamente; PTC organiza chamadas de ferramentas em código. A predefinição PTC atual deixa a ferramenta de fluxo de trabalho desativada. A velocidade e o uso do token dependem da tarefa e de como o programa lida com seus resultados.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Verifique um conjunto de arquivos de configuração', diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 6f5dab646a..d8b36381cf 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: fe90de63be885e2d - zh: 8ab904422097357f + en: 793a61adeee867e0 + zh: 732017ffb439a73b /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e @@ -45,8 +45,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: c65789c64093eb47 - zh: b58cccbeea767849 + en: 0db84c3de00194e4 + zh: bf4c4115b90387fb /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 946c5b45bb..b0d9d42936 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -90,11 +90,13 @@ The composer exposes `retry(failureSeq)` for failed-generation recovery. The inp The composer uses the shared [text-input focus policy](../ui-primitives/README.md#use-this-package) on mount, Session switching, and unlock. Identified phones and tablets require tapping the input; desktop devices retain automatic focus. On these mobile devices, a submission that empties the focused draft moves focus to the non-text composer card, dismissing the keyboard while retaining its navigation position. Rejected submissions, retained newer draft text, and another control already holding focus preserve focus. The [Lexical patch](../../../patches/lexical@0.49.0.patch) keeps caret scrolling in the same coordinate system as DOM geometry when a mobile keyboard pans the page. +Unmodified ArrowUp and ArrowDown recall the text of human prompts in the loaded Session history when no candidate menu consumes the key and the caret sits at the end of the draft. Browsing starts only from an empty draft and continues only while the draft is the unedited prompt it last showed; any edit, including undo, ends browsing and leaves an ordinary draft, so typed or edited text is never replaced. While browsing, an arrow with the caret elsewhere moves the caret inside the shown prompt. Prompts are read newest first from the Session's event window when the arrow arrives; prompts without text and consecutive repeats are skipped, and moving past the newest prompt returns to the empty draft. Each step is an ordinary undoable edit: undo returns to the draft shown before the step. + The context-occupancy button shows a ring and percentage below the input card, after the Session statistics. Clicking it opens the token breakdown in a CSS-anchored panel bounded by the layout viewport, including when no statistics are shown; the button stays hidden until context usage and capacity are available. Browser zoom and panning move the panel with the page, so it may extend beyond the visual viewport. Outside the Hero, that row keeps one reading's height while it is empty, so statistics and context usage arriving later do not change the composer's height; the Hero shows no empty row. With Coding Tools off, the shell hides only Trajectory; other plugin-contributed Views remain available. The View tab bar is hidden when fewer than two Views are available. Turning Coding Tools off while Trajectory is active returns to Chat; stored View preferences and recorded Session data remain intact. Turning it on makes Trajectory available again. View owners receive the available roster so their navigation actions can follow the same visibility. -While the root-scoped `conversation.session.header.views.actions` list has registrations, a **More conversation views** button with a tooltip follows the View tabs in the tab row. It opens a menu whose rows are that list's registrations. Each receives `entries` (Views outside the header in registration order with `id`, `label`, `pinned`, and `active`; Chat is never listed), `onOpen(id)`, which selects the View in this Session, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The header keeps an in-memory list of unpinned View ids shared by every Session; the tab bar omits unpinned Views and places registered Chat first so it always remains outside More. Plugin reload resets pin choices, and legacy localStorage values are ignored. The tab bar's visibility counts available Views, not pinned ones, so the bar and More stay while every other View is unpinned. Unpinning the active View hides its tab immediately without changing the selected content. More lists only Views outside the header and identifies the current View through `active`. The header reads its available row width, reserves 48px for More and padding, and estimates 120px per tab. Remaining Views keep registration order in More. A single ResizeObserver watches the tab row so window resizing and sidebar expansion update the split; active selection does not change the order. The observer disconnects when the row is removed. If ResizeObserver is unavailable, the initial width calculation still applies without subsequent observation. The More button highlights when the active View is folded. Each tab label estimates its text width from the glyphs; its full-name tooltip appears only when that estimate exceeds the 88px cell. At least one preferred tab remains outside. Unregistered View ids remain in the in-memory pin list until plugin reload. +While the root-scoped `conversation.session.header.views.actions` list has registrations, a **More conversation views** button with a tooltip follows the View tabs in the tab row. It opens a menu whose rows are that list's registrations. Each receives `entries` (Views outside the header in registration order with `id`, `label`, `pinned`, and `active`; Chat is never listed), `onOpen(id)`, which selects the View in this Session, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The header keeps an in-memory list of unpinned View ids shared by every Session; the tab bar omits unpinned Views and places registered Chat first so it always remains outside More. Plugin reload resets pin choices, and legacy localStorage values are ignored. The tab bar's visibility counts available Views, not pinned ones, so the bar and More stay while every other View is unpinned. Unpinning the active View hides its tab immediately without changing the selected content. More lists only Views outside the header and identifies the current View through `active`. The header reads its available row width, reserves 48px for More and padding, and estimates 120px per tab. Remaining Views keep registration order in More. After the initial measurement, the header uses the tab row width delivered by ResizeObserver when the window or sidebar resizes; active selection does not change the order. The observer disconnects when the row is removed. If ResizeObserver is unavailable, the initial width calculation still applies without subsequent observation. The More button highlights when the active View is folded. Each tab label estimates its text width from the glyphs; its full-name tooltip appears only when that estimate exceeds the 88px cell. At least one preferred tab remains outside. Unregistered View ids remain in the in-memory pin list until plugin reload. The composer registers the File command action and owns its label, availability, and native file-dialog callback. Menu availability and invocation both consult the mounted composer's current attachment-intake policy. Unmounting or locking the composer disables that action; disposing the plugin removes its registration. The callback binding stays inside the input module. @@ -126,7 +128,11 @@ The width-handle indicator follows the pointer only during a captured drag; ordi -The main Conversation body can keep room free at its inline end for something that stays beside the transcript, such as the docked [Session panel](../ui-session-panel/README.md#docking). A stylesheet asks for it by setting the `--dsh-chat-end-reserve` length on the `[data-conversation-content]` element. The scrollport then pads its end by `--dsh-chat-end-inset`, twice the missing gutter, which moves the centered transcript column and the composer toward the start edge at their own widths until the space after the column equals the reserve. `--dsh-chat-end-reserve-max` is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger request gets no inset, so whatever asks for room reads the maximum before it relies on that room. The body derives these lengths from the scrollport's width, which it publishes as `--dsh-conversation-viewport-width`, so they have the same values in the scrollport, the width handles, and the Chat aside layer. The width handles move with the column. While the inset is above zero the reserve holds the column's end edge, so a drag on either handle moves only the start edge and changes the width by the pointer's travel instead of twice it; a column dragged wider than the start gutter can give gets no inset and centers again. The inset applies at once. A stylesheet that wants a change of it animated also sets `--dsh-chat-end-reserve-transition`, a duration and an easing, on the same element for as long as that change lasts; the scrollport's padding and the Chat aside layer's margin then follow it together. An embedded occurrence makes no room: its maximum and its inset are 0. +The main Conversation body can keep room free at its inline end for something that stays beside the transcript, such as the docked [Session panel](../ui-session-panel/README.md#docking). A stylesheet asks for it by setting the `--dsh-chat-end-reserve` length on the `[data-conversation-content]` element. The scrollport then pads its end by `--dsh-chat-end-inset`, twice the missing gutter, which moves the centered transcript column and the composer toward the start edge at their own widths until the space after the column equals the reserve. `--dsh-chat-end-reserve-max` is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger request gets no inset, so whatever asks for room reads the maximum before it relies on that room. The maximum changes on every resize and is not inherited: a stylesheet reads it on the `[data-conversation-content]` element itself and derives what its descendants need there as a registered length, which changes only when the derived value does. The body keeps its other varying inputs uninherited as well and gives descendants `--dsh-chat-content-width` and `--dsh-chat-end-inset` as computed lengths, so resizing restyles the transcript only when one of those changes. The body derives these lengths from the scrollport's width, which it publishes as `--dsh-conversation-viewport-width`, so they have the same values in the scrollport, the width handles, and the Chat aside layer. The width handles move with the column. While the inset is above zero the reserve holds the column's end edge, so a drag on either handle moves only the start edge and changes the width by the pointer's travel instead of twice it; a column dragged wider than the start gutter can give gets no inset and centers again. The inset applies at once. A stylesheet that wants a change of it animated also sets `--dsh-chat-end-reserve-transition`, a duration and an easing, on the same element for as long as that change lasts; the scrollport's padding and the Chat aside layer's margin then follow it together. An embedded occurrence makes no room: its maximum and its inset are 0. + +The built-in composer exposes `conversation.input.placeholder` for an empty, editable Session input. A chain entry matches the owner's `sessionId` and renders localized text or non-interactive inline JSX such as `/`. The visible hint supplies the textbox's accessible name. When every selector returns `null`, the composer shows its usual home, Plan, or default hint. Workspace selection, blocked input, unavailable Sessions, and queue steering use the composer's own prompts. + +For plugins that replace `conversation.composer.bar`, `ComposerBarProps` defaults to a fixed set of child slots, so adding a slot to the built-in composer preserves existing plugin types. A replacement can use `ComposerBarProps` to derive its render keys from the `children` table it passes to `slots.register`. The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), the claimed slash command is an atomic leading chip that carries its claim, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews use the [UserText Factory](#sent-user-text) (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in the ui-primitives `InlineEditor`, so line breaks survive re-editing. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. On Apple platforms, Home and End move the caret to the start or end of the current visual line instead of scrolling the conversation, and Shift extends the selection; End immediately before a quote takes the same path as Cmd+Right to the end of that line. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. @@ -240,6 +246,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **A reload discards draft attachments** — only switching between Sessions keeps them; after a reload the reopened composer reports the loss and asks the user to add them again, and a crash leaves no notice. While a Session is not shown, a pasted image keeps its bytes in memory ([decision](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md)). - **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). +- **Prompt recall reads loaded history as plain text** — only prompts already in the Client event window are recalled, so older pages are reachable only after they load. Recall restores the prompt's text blocks: reference chips return as their mention text, quotes as their Markdown, and attachments are not restored. Prompts without text, such as an attachment-only submission, are skipped, and commands record no user prompt, so neither is recalled. A failed submission is not recalled because it never entered the log; the draft keeps it instead. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 6fa3fd2049..11839e19ad 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -90,11 +90,13 @@ composer 提供 `retry(failureSeq)` 处理生成失败后的恢复。输入栏 composer 在挂载、切换 Session 和解除锁定时使用共享的[文字输入框聚焦策略](../ui-primitives/README.zh.md#use-this-package)。识别出的手机和平板需要点击输入框;桌面设备保留自动聚焦。在这些移动设备上,提交清空正在聚焦的草稿后,焦点移到不接受文字输入的 composer 卡片,收起键盘并保留键盘导航位置。被拒绝的提交、保留的新草稿文字,以及已经聚焦的其他控件均保留原有焦点。移动端键盘平移页面时,[Lexical 补丁](../../../patches/lexical@0.49.0.patch)让光标滚动计算与 DOM 几何使用同一坐标系。 +候选菜单未处理按键且光标位于草稿末尾时,不带修饰键的 ArrowUp 和 ArrowDown 会召回已加载的 Session 历史中用户发出的消息文本。只有草稿为空时才能开始浏览,只有草稿仍是上一次显示且未修改的消息时才能继续浏览;任何修改(包括撤销)都会结束浏览,草稿变成普通草稿,因此已输入或改过的文字不会被替换。浏览期间光标不在末尾时,方向键在当前消息内移动光标。按键时从 Session 的事件窗口由新到旧读取消息;没有文字的消息和连续重复的消息会被跳过,越过最新一条时回到空草稿。每次切换都是一次普通的、可撤销的编辑:撤销回到切换前显示的草稿。 + 上下文占用按钮在输入卡片下方、会话统计右侧显示圆环和百分比。点击按钮可在受布局视口约束的 CSS 锚定面板中查看 token 构成,没有统计项时也可打开;上下文用量和容量尚不可用时,按钮保持隐藏。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。Hero 之外,这一行为空时仍保留一项读数的高度,因此会话统计和上下文用量稍后到达不会改变 composer 的高度;Hero 不显示空行。 关闭代码工作工具时,外壳仅隐藏 Trajectory;其他插件贡献的 View 仍然可用。可用 View 少于两个时隐藏 View 标签栏。在 Trajectory 激活时关闭代码工作工具会返回 Chat;已保存的 View 偏好和 Session 记录保持不变。开启后,Trajectory 恢复可用。View 所有者接收可用列表,使导航操作跟随相同的可见性。 -root 作用域的 `conversation.session.header.views.actions` list 有注册项时,标签行中的 View 标签之后显示带提示框的**更多会话视图**按钮。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的头部之外的 View,含 `id`、`label`、`pinned` 与 `active`;不含 Chat)、在本 Session 选择 View 的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。头部在内存中保存所有 Session 共用的已收起 View id 列表;标签栏不显示已收起的 View,并将已注册的 Chat 放在首位,确保它始终留在更多菜单外。插件重新加载时 Pin 选择重置,不读取旧 localStorage 值。标签栏是否显示按可用 View 计算,不按已固定的 View 计算,因此其他 View 全部收起时,标签栏和“更多”仍然显示。收起当前激活的 View 会立即隐藏其标签,但不会切走其内容。更多菜单仅包含头部之外的 View,通过 `active` 标识当前 View。头部读取当前行可用宽度,为更多按钮与内边距预留 48px,每个标签估算 120px,其余 View 按注册顺序进入更多。单个 ResizeObserver 观察标签行,使窗口缩放和侧栏展开能够更新分组;当前选中项变化不改变顺序。标签行移除时断开观察。如果环境没有 ResizeObserver,仍按初始宽度计算,但不继续观察。当前 View 收起时,更多按钮高亮。每个标签按字符宽度估算文本宽度;只有估算结果超过 88px 单元格时,才通过提示框提供全名。至少保留一个优先展示的外部标签。未注册 View 的 id 保留在内存 Pin 列表中,直到插件重新加载。 +root 作用域的 `conversation.session.header.views.actions` list 有注册项时,标签行中的 View 标签之后显示带提示框的**更多会话视图**按钮。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的头部之外的 View,含 `id`、`label`、`pinned` 与 `active`;不含 Chat)、在本 Session 选择 View 的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。头部在内存中保存所有 Session 共用的已收起 View id 列表;标签栏不显示已收起的 View,并将已注册的 Chat 放在首位,确保它始终留在更多菜单外。插件重新加载时 Pin 选择重置,不读取旧 localStorage 值。标签栏是否显示按可用 View 计算,不按已固定的 View 计算,因此其他 View 全部收起时,标签栏和“更多”仍然显示。收起当前激活的 View 会立即隐藏其标签,但不会切走其内容。更多菜单仅包含头部之外的 View,通过 `active` 标识当前 View。头部读取当前行可用宽度,为更多按钮与内边距预留 48px,每个标签估算 120px,其余 View 按注册顺序进入更多。初次测量后,窗口或侧栏缩放时,头部使用 ResizeObserver 送达的标签行宽度更新分组;当前选中项变化不改变顺序。标签行移除时断开观察。如果环境没有 ResizeObserver,仍按初始宽度计算,但不继续观察。当前 View 收起时,更多按钮高亮。每个标签按字符宽度估算文本宽度;只有估算结果超过 88px 单元格时,才通过提示框提供全名。至少保留一个优先展示的外部标签。未注册 View 的 id 保留在内存 Pin 列表中,直到插件重新加载。 输入框注册「文件」命令动作,负责其标题、可用性和原生文件选择器回调。菜单可用性与实际调用都读取已挂载输入框当前的附件接收策略。输入框卸载或锁定后该动作不可用,插件 dispose(资源释放)时移除注册。回调绑定留在输入模块内部。 @@ -126,7 +128,11 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 -主 Conversation body 可以在行向末端空出一段位置,留给停在 transcript 旁边的内容,例如停靠的[会话面板](../ui-session-panel/README.zh.md#docking)。样式表在 `[data-conversation-content]` 元素上设置长度 `--dsh-chat-end-reserve` 来提出申请。滚动容器随即给末端加上 `--dsh-chat-end-inset` 的内边距,大小是所缺留白的两倍,居中的 transcript 列和输入框保持各自宽度向起始边缘移动,直到列后的空间等于预留值。`--dsh-chat-end-reserve-max` 是在列保持宽度和两侧内边距的前提下,起始留白能让出的最大预留;超出它的申请得不到任何内边距,因此申请方要先读取这个最大值,再依赖这段位置。主体从滚动容器的宽度推出这些长度,并把该宽度发布为 `--dsh-conversation-viewport-width`,因此它们在滚动容器、宽度拖拽条和 Chat 侧边层中的值相同。宽度拖拽条随列移动。内边距大于零时,预留固定了列的末端边缘,因此拖动任一拖拽条都只移动起始边缘,宽度的变化等于指针移动的距离而不是它的两倍;列被拖到超过起始留白能让出的宽度时不再有内边距,重新居中。内边距立即生效。样式表如果希望某次变化带动画,就在这次变化期间在同一个元素上再设置 `--dsh-chat-end-reserve-transition`(一个时长和一条缓动曲线),滚动容器的内边距和 Chat 侧边层的外边距随之一起过渡。嵌入式 occurrence 不让位:它的最大预留和内边距都是 0。 +主 Conversation body 可以在行向末端空出一段位置,留给停在 transcript 旁边的内容,例如停靠的[会话面板](../ui-session-panel/README.zh.md#docking)。样式表在 `[data-conversation-content]` 元素上设置长度 `--dsh-chat-end-reserve` 来提出申请。滚动容器随即给末端加上 `--dsh-chat-end-inset` 的内边距,大小是所缺留白的两倍,居中的 transcript 列和输入框保持各自宽度向起始边缘移动,直到列后的空间等于预留值。`--dsh-chat-end-reserve-max` 是在列保持宽度和两侧内边距的前提下,起始留白能让出的最大预留;超出它的申请得不到任何内边距,因此申请方要先读取这个最大值,再依赖这段位置。这个最大值随每次缩放变化且不继承:样式表在 `[data-conversation-content]` 元素本身上读取它,并在那里把后代需要的值推导为已注册的长度,只有推导结果变化时该长度才变化。主体的其他变化输入同样不继承,传给后代的 `--dsh-chat-content-width` 与 `--dsh-chat-end-inset` 是计算后的长度,因此缩放只有在它们变化时才重新计算正文样式。主体从滚动容器的宽度推出这些长度,并把该宽度发布为 `--dsh-conversation-viewport-width`,因此它们在滚动容器、宽度拖拽条和 Chat 侧边层中的值相同。宽度拖拽条随列移动。内边距大于零时,预留固定了列的末端边缘,因此拖动任一拖拽条都只移动起始边缘,宽度的变化等于指针移动的距离而不是它的两倍;列被拖到超过起始留白能让出的宽度时不再有内边距,重新居中。内边距立即生效。样式表如果希望某次变化带动画,就在这次变化期间在同一个元素上再设置 `--dsh-chat-end-reserve-transition`(一个时长和一条缓动曲线),滚动容器的内边距和 Chat 侧边层的外边距随之一起过渡。嵌入式 occurrence 不让位:它的最大预留和内边距都是 0。 + +内置输入栏通过 `conversation.input.placeholder` 为可编辑会话的空输入框提供占位提示。插件通过 chain 的选择器匹配拥有者传入的 `sessionId`。匹配的组件可渲染本地化文字或不参与交互的行内 JSX,例如 `/`。提示可见时,其文字用作输入框的无障碍名称。所有选择器均返回 `null` 时,输入栏按当前状态显示首页、Plan 或默认提示。选择工作区、输入受阻、会话不可用或可将排队消息送入当前轮次时,输入栏显示相应的内置提示。 + +替换 `conversation.composer.bar` 的插件可以直接使用 `ComposerBarProps`。它默认使用一组固定的子插槽,内置输入栏新增插槽时,现有插件的类型仍然兼容。替换组件也可以使用 `ComposerBarProps`,从传给 `slots.register` 的 `children` 声明中推导自己可以渲染的键。 常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 是携带认领的行首原子 chip,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览使用 [UserText Factory](#sent-user-text)(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 在 Apple 平台上,Home 与 End 把光标移到当前视觉行的行首或行末,而不是滚动对话,按住 Shift 时扩展选区;光标紧贴在 quote 左侧时,End 与 Cmd+Right 走同一路径移到该行末尾。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 @@ -240,6 +246,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **刷新会丢弃草稿附件**——只有在 Session 之间切换时附件才会保留;刷新后重新打开的输入框会提示丢失并请用户重新添加,崩溃时不会有提示。Session 未显示期间,粘贴的图片会把字节保留在内存中([决策](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md))。 - **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 +- **消息召回按纯文本读取已加载的历史**——只召回已在 Client 事件窗口中的消息,更早的分页加载后才能召回。召回只还原消息的文本块:引用 chip 以 mention 文本出现,quote 以 Markdown 出现,附件不会还原。没有文字的消息(例如只带附件的提交)会被跳过,命令不会产生用户消息,因此两者都不召回。失败的提交从未写入日志,所以不召回,草稿会保留它。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 7ddb16613a..76ac04040b 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -21,6 +21,7 @@ import { UserText, PlainUserText, SessionReference } from './user-text/UserText. import { sessionReferenceRule } from './user-text/session-reference-rule.ts' import { collapseWhitespaceRule, trimWhitespaceRule } from './user-text/whitespace-rules.ts' import type { ViewTab } from './contract/views.ts' +import { inputBarChildren } from './contract/slots.ts' import type { ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationShellInjected, ConversationSessionInjected, DraftFileUploads, UserTextInjected, @@ -464,17 +465,7 @@ export function apply(ctx: Context, config: SyncedConfig): v const registerComposerBar = () => slots.register({ name: 'conversation.composer.bar', locale: NS, - children: { - 'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' }, - 'conversation.input.overlay': { kind: 'list', scope: 'session' }, - 'conversation.input.permission': { kind: 'single', scope: 'session' }, - 'conversation.input.left': { kind: 'list', scope: 'session' }, - 'conversation.input.plan': { kind: 'single', scope: 'session' }, - 'conversation.input.right': { kind: 'list', scope: 'session' }, - 'conversation.input.model': { kind: 'single', scope: 'session' }, - 'conversation.input.activity': { kind: 'single', scope: 'session' }, - 'conversation.composer.dock': { kind: 'list', scope: 'session' }, - }, + children: inputBarChildren, inject: (sessionId: SessionId | undefined): ComposerBarInjected => { if (sessionId === undefined) { return { diff --git a/packages/client/ui-conversation/src/client/contract/draft-editor.ts b/packages/client/ui-conversation/src/client/contract/draft-editor.ts index 86592a82db..ece545cb16 100644 --- a/packages/client/ui-conversation/src/client/contract/draft-editor.ts +++ b/packages/client/ui-conversation/src/client/contract/draft-editor.ts @@ -100,6 +100,18 @@ export interface ComposerKeyboard { space(): boolean /** Dismiss the popupSelect shell (any interaction outside the box). */ dismissPopup(): void + /** + * Replace the draft with the text of an adjacent human prompt in the loaded + * Session history; the caller passes only arrows with the caret at the + * draft end. Browsing starts from an empty draft and continues only while + * the draft is the unedited prompt it last showed, so typed or edited text + * is never replaced; moving past the newest prompt returns to the empty + * draft. Each step is an ordinary undoable edit. + * @param direction - history direction. + * @returns whether an adjacent prompt exists and the replacement is scheduled; + * inside a key command it runs after that update, and the caller consumes the key. + */ + recallHistory(direction: 'older' | 'newer'): boolean /** * Bind the mounted composer's file action and live intake availability. * @param picker - availability query and native file-dialog opener. diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 4efcee6601..0e9ab07b00 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -9,7 +9,7 @@ import type { MaybeSnapshotSelectorHook, ObservableSnapshot, SnapshotSelectorHook, } from '@deepseek-ai/dsh-client-store' import type { - FactoryComponentPropsOf, FactoryLocalComponentPropsOf, + ChildrenDecl, FactoryComponentPropsOf, FactoryLocalComponentPropsOf, InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore, } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' @@ -334,6 +334,16 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * the document body because the docked composer contains them. */ 'conversation.composer.bar': { kind: 'single'; scope: 'session-maybe'; owner: ComposerBarOwnerProps } + /** + * Select by Session id to show noninteractive inline guidance in the built-in empty editor. + * Its text names the textbox. When every selector declines, the editor shows its built-in prompt. + */ + 'conversation.input.placeholder': { + kind: 'chain' + scope: 'session' + inline: true + owner: InputPlaceholderOwnerProps + } /** * Optional draft-attachment rail and drop target; fixed overlays must portal to the document * body because the docked composer contains them. @@ -657,19 +667,38 @@ export interface InputActivityOwnerProps extends InputControlOwnerProps { onActiveChange: (active: boolean) => void } -/** Full props of the resident composer bar. */ -export type ComposerBarProps = +/** Adding a key here changes the default render keys for plugins using ComposerBarProps. */ +const baseComposerChildren = { + 'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' }, + 'conversation.input.overlay': { kind: 'list', scope: 'session' }, + 'conversation.input.permission': { kind: 'single', scope: 'session' }, + 'conversation.input.left': { kind: 'list', scope: 'session' }, + 'conversation.input.plan': { kind: 'single', scope: 'session' }, + 'conversation.input.right': { kind: 'list', scope: 'session' }, + 'conversation.input.model': { kind: 'single', scope: 'session' }, + 'conversation.input.activity': { kind: 'single', scope: 'session' }, + 'conversation.composer.dock': { kind: 'list', scope: 'session' }, +} as const satisfies ChildrenDecl + +/** Child slots owned by the built-in input bar. */ +export const inputBarChildren = { + ...baseComposerChildren, + 'conversation.input.placeholder': { kind: 'chain', scope: 'session', inline: true }, +} as const satisfies ChildrenDecl + +/** Composer bar props for a registration's child keys. The default preserves the original child slots. */ +export type ComposerBarProps = PropsRuntime<'conversation.composer.bar'> - & PropsRenderSlots< - | 'conversation.input.attachments' | 'conversation.input.overlay' - | 'conversation.input.permission' - | 'conversation.input.left' | 'conversation.input.plan' - | 'conversation.input.right' | 'conversation.input.model' | 'conversation.input.activity' - | 'conversation.composer.dock' - > + & PropsRenderSlots & InjectFace & PropsLocale<'conversation'> +/** Owner data for the built-in editor's placeholder selectors. */ +export interface InputPlaceholderOwnerProps { + /** Session displayed by this editor. */ + readonly sessionId: SessionId +} + /** Owner values used to elect a composer takeover. */ export interface ComposerChainProps { /** Current Session identity used by temporary business-owned entries. */ diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 2aa335183b..f7e52fb39e 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -91,7 +91,7 @@ export type { ConversationViewActionEntry, ConversationViewActionsOwnerProps, ConversationViewsProps, ConversationWidthControlsInputProps, ConversationWidthControlsProps, ConversationStore, ConvViewOwnerProps, ConvViewProps, EmptyWorkspaceOwnerProps, - HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, HeroFrameOwnerProps, InputControlOwnerProps, InputZone, + HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, HeroFrameOwnerProps, InputControlOwnerProps, InputPlaceholderOwnerProps, InputZone, MessageImageLabels, MessageImageLoader, MessageImageSource, MessageImagesContentInput, MessageImagesOwnerProps, UseConversation, UserTextInput, UserTextInjected, UserTextNodeOwnerProps, UserTextNodeProps, WorkspaceSelectedHandler, WorkspaceSessionAdopter, diff --git a/packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx b/packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx index a51ef34160..87c8f63df2 100644 --- a/packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx +++ b/packages/client/ui-conversation/src/client/input/editor/DraftEditor.tsx @@ -1,8 +1,11 @@ -/** Stateless text-area presentation over the InputBar's borrowed editor. */ +/** Text-area presentation over the InputBar's borrowed editor. */ +import { useId } from 'react' import type { CSSProperties, KeyboardEventHandler, ReactNode, RefObject } from 'react' import type { LexicalEditor } from 'lexical' import clsx from 'clsx' import { HoverCardGroup } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { InputState } from '../../contract/input.ts' import { ComposerContentEditable } from './ComposerContentEditable.tsx' import { DecoratorPortals } from './DecoratorPortals.tsx' @@ -16,6 +19,9 @@ export interface DraftEditorProps { readonly editorDisabled: boolean readonly phase: InputState['phase'] | 'inert' readonly placeholderText: string + /** Session eligible for plugin guidance while the empty editor accepts input. */ + readonly placeholderSessionId: SessionId | undefined + readonly renderSlotChain: PropsRenderSlots<'conversation.input.placeholder'>['renderSlotChain'] readonly ariaLabel: string readonly workspaceTrigger: boolean readonly workspacePickerOpen: boolean @@ -26,13 +32,14 @@ export interface DraftEditorProps { /** * Render the existing scrollport, editable surface, placeholder, and chip portals. - * @param props - borrowed editor and presentation values; this component owns no Hooks. + * @param props - borrowed editor, presentation values and placeholder slot renderer. * @returns the existing text-area DOM without an additional wrapper. */ export function DraftEditor({ classNames: css, editor, scrollRef, editable, editorDisabled, phase, placeholderText, ariaLabel, - workspaceTrigger, workspacePickerOpen, onWorkspaceKeyDown, hint, showPlaceholder, + workspaceTrigger, workspacePickerOpen, onWorkspaceKeyDown, hint, showPlaceholder, placeholderSessionId, renderSlotChain, }: DraftEditorProps): ReactNode { + const placeholderId = useId() return (
@@ -43,9 +50,8 @@ export function DraftEditor({ data-phase={phase} aria-disabled={editorDisabled || undefined} data-placeholder={placeholderText} - // The placeholder was the textarea's accessible name; a div's - // data attribute is not, so the label restores it. aria-label={ariaLabel} + aria-labelledby={showPlaceholder && placeholderSessionId !== undefined ? placeholderId : undefined} aria-haspopup={workspaceTrigger ? 'menu' : undefined} aria-expanded={workspaceTrigger ? workspacePickerOpen : undefined} tabIndex={workspaceTrigger ? 0 : undefined} @@ -53,8 +59,10 @@ export function DraftEditor({ style={hint === null ? undefined : { '--dsh-composer-hint': JSON.stringify(hint) } as CSSProperties} /> {showPlaceholder && ( -
- {placeholderText} +
+ {placeholderSessionId === undefined + ? placeholderText + : renderSlotChain('conversation.input.placeholder', { sessionId: placeholderSessionId }, { fallback: placeholderText })}
)} diff --git a/packages/client/ui-conversation/src/client/input/editor/keymap.ts b/packages/client/ui-conversation/src/client/input/editor/keymap.ts index 8a3435d941..31c4a40c34 100644 --- a/packages/client/ui-conversation/src/client/input/editor/keymap.ts +++ b/packages/client/ui-conversation/src/client/input/editor/keymap.ts @@ -1,10 +1,11 @@ /** * Composer keymap over the Lexical command layer: menu arbitration - * (arrows/escape/enter), space adjudication, the Enter submit gesture, and - * paste routing. Registered at CRITICAL priority so it decides before - * @lexical/plain-text's own Enter/paste defaults; a handler returning false - * falls through to those defaults (Shift+Enter's line break, ordinary - * spaces, text paste the bar routes itself). + * (arrows/escape/enter), prompt recall on draft-end arrows, space + * adjudication, the Enter submit gesture, and paste routing. Registered at + * CRITICAL priority so it decides before @lexical/plain-text's own + * Enter/paste defaults; a handler returning false falls through to those + * defaults (Shift+Enter's line break, ordinary spaces, text paste the bar + * routes itself). * * IME guard: a composition-closing Enter/Space must not submit or adjudicate. * KeyboardEvent.isComposing covers most engines; Safari delivers the closing @@ -16,7 +17,7 @@ */ import type { LexicalEditor } from 'lexical' import { - $getAdjacentNode, $getSelection, $isElementNode, $isLineBreakNode, $isRangeSelection, $isTextNode, + $createRangeSelectionFromDom, $getAdjacentNode, $getSelection, $isElementNode, $isLineBreakNode, $isRangeSelection, $isTextNode, KEY_DOWN_COMMAND, MOVE_TO_END, COMMAND_PRIORITY_CRITICAL, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_UP_COMMAND, KEY_ENTER_COMMAND, KEY_ESCAPE_COMMAND, KEY_SPACE_COMMAND, KEY_TAB_COMMAND, PASTE_COMMAND, @@ -24,6 +25,7 @@ import { import { mergeRegister } from '@lexical/utils' import type { ArbitrateKey, ArbitrateOutcome } from '../../contract/draft-editor.ts' import { clipboardFiles } from '../file-intake.ts' +import { $composerLayout, $detectOffsetOfPoint } from './projection.ts' import { $isQuoteNode } from './QuoteNode.tsx' /** The bar-supplied behavior behind each intercepted gesture. */ @@ -34,6 +36,8 @@ export interface ComposerKeymapHandlers { space(): boolean /** Dismiss the popupSelect shell (Escape layering: an open overlay closes first). */ dismissPopup(): void + /** Replace the draft with an adjacent recalled prompt when recall applies; true = the arrow is consumed. */ + recallHistory(direction: 'older' | 'newer'): boolean /** Whether Enter may submit right now (locked/busy states refuse). */ canSubmit(): boolean /** Plain Enter submits; exactly Ctrl+Enter or Cmd+Enter selects accelerated delivery. */ @@ -86,6 +90,21 @@ function domCaretTouches(element: HTMLElement, backward: boolean): boolean { && (backward ? boundary.previousSibling : boundary.nextSibling) === element } +/** + * Whether the collapsed browser caret sits at the end of the draft. Must run + * inside an editor update. The DOM selection is mapped directly because + * Lexical's own selection lags a native caret move until the next + * selectionchange. + */ +function $caretAtDraftEnd(editor: LexicalEditor): boolean { + const domSelection = editor.getRootElement()?.ownerDocument.getSelection() ?? null + if (domSelection === null || domSelection.rangeCount === 0 || !domSelection.isCollapsed) return false + const point = $createRangeSelectionFromDom(domSelection, editor)?.focus + if (point === undefined) return false + const layout = $composerLayout() + return $detectOffsetOfPoint(layout, point) === layout.detectLength +} + /** Find an atomic quote immediately beside both editor and browser carets. */ function adjacentQuote(editor: LexicalEditor, backward: boolean) { const selection = $getSelection() @@ -229,6 +248,18 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer return false } + // An unmodified arrow the menu passes may recall prompts only with + // the caret at the draft end; the handler decides whether recall applies. + const history = (key: 'up' | 'down') => (event: KeyboardEvent): boolean => { + if (arrow(key)(event)) return true + if (isComposingEvent(event, recentlyComposing) + || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return false + if (!$caretAtDraftEnd(editor)) return false + if (!handlers.recallHistory(key === 'up' ? 'older' : 'newer')) return false + event.preventDefault() + return true + } + return mergeRegister( editor.registerRootListener((root, prevRoot) => { prevRoot?.removeEventListener('compositionstart', onCompositionStart) @@ -254,8 +285,8 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer return movePastQuote(editor, event) }, COMMAND_PRIORITY_CRITICAL), editor.registerUpdateListener(syncComposition), - editor.registerCommand(KEY_ARROW_UP_COMMAND, arrow('up'), COMMAND_PRIORITY_CRITICAL), - editor.registerCommand(KEY_ARROW_DOWN_COMMAND, arrow('down'), COMMAND_PRIORITY_CRITICAL), + editor.registerCommand(KEY_ARROW_UP_COMMAND, history('up'), COMMAND_PRIORITY_CRITICAL), + editor.registerCommand(KEY_ARROW_DOWN_COMMAND, history('down'), COMMAND_PRIORITY_CRITICAL), // Tab settles the highlighted completion and passes without one, keeping // native focus traversal; Shift+Tab leaves the menu like Escape whenever it // is open, highlight or not, so the two Tab gestures never disagree about diff --git a/packages/client/ui-conversation/src/client/input/editor/runtime.ts b/packages/client/ui-conversation/src/client/input/editor/runtime.ts index bed9912426..dbe711ea2d 100644 --- a/packages/client/ui-conversation/src/client/input/editor/runtime.ts +++ b/packages/client/ui-conversation/src/client/input/editor/runtime.ts @@ -11,6 +11,7 @@ import { } from 'lexical' import { registerPlainText } from '@lexical/plain-text' import { createEmptyHistoryState, registerHistory } from '@lexical/history' +import type { HistoryState } from '@lexical/history' import { mergeRegister } from '@lexical/utils' import type { DraftQuote, DraftReference, ReferenceInsert } from '../../contract/draft-editor.ts' import type { CommandClaim } from '../../contract/input.ts' @@ -79,6 +80,8 @@ export class DraftEditorRuntime { /** Live lexicon subscription disposer; undefined until the controller resolves. */ private lexiconOff: (() => void) | undefined private lexiconSource: ObservableSnapshot | undefined + /** Undo and redo state owned by the registered history listener. */ + private readonly history: HistoryState = createEmptyHistoryState() /** @param deps - model callbacks used by editor listeners and transforms. */ constructor(private readonly deps: DraftEditorRuntimeDeps) { @@ -117,7 +120,7 @@ export class DraftEditorRuntime { this.editor.registerNodeTransform(RootNode, preserveExternalSelection), registerReferenceActivation(this.editor, (source, reference) => this.deps.openReference(source, reference)), - registerHistory(this.editor, createEmptyHistoryState(), HISTORY_MERGE_DELAY_MS), + registerHistory(this.editor, this.history, HISTORY_MERGE_DELAY_MS), this.editor.registerUpdateListener(() => { this.deps.onUpdate() }), registerCommandChipSeat(this.editor), registerCommandChipSelection(this.editor), @@ -159,6 +162,19 @@ export class DraftEditorRuntime { this.editor.update(fn, { discrete: true, ...(tag === undefined ? {} : { tag }) }) } + /** + * Run a top-level edit now, or in a microtask when called from inside an + * update of this editor (a key command handler). Nested edits and update + * callbacks both run while the editor still counts as updating, so the + * edit's revision would not be observable when it returns. + * @param fn - the edit, run outside any update. + */ + afterUpdate(fn: () => void): void { + // Not an update onUpdate callback: it runs while the editor still commits, where a new update is unsafe. + if (this.editor._updating) queueMicrotask(fn) + else fn() + } + /** * Reconnect decorations when the optional trigger provider changes. * The rescan reads the current editor and does not replace its content. @@ -194,16 +210,19 @@ export class DraftEditorRuntime { /** * Replace the whole draft (persisted-draft seed and programmatic writes). * Placeholder-sanitized; newlines split paragraphs; the caret lands at the - * end. Merged into history so a seed is not an undoable step of its own. + * end. Merged into history so a seed is not an undoable step of its own, + * unless `undoable` makes the replacement its own undo step. * @param text - the full next draft. + * @param undoable - record the replacement as a separate undo step. */ - setDraft(text: string): void { + setDraft(text: string, undoable = false): void { const clean = text.replace(REFERENCE_PLACEHOLDER_RE, '') if (clean === this.projection.clipboardText && this.projection.occurrences.length === 0 && this.projection.quotes.length === 0) return + if (undoable) this.keepUndoBaseline() this.editor.update(() => { $getRoot().clear() $appendParagraphs(clean) - }, { discrete: true, tag: HISTORY_MERGE_TAG }) + }, { discrete: true, tag: undoable ? HISTORY_PUSH_TAG : HISTORY_MERGE_TAG }) } /** @@ -472,6 +491,19 @@ export class DraftEditorRuntime { }, { discrete: true, tag: HISTORY_MERGE_TAG }) } + /** + * Make the current document the undo target of the next pushed step. A cut + * history (after a submission) has no current entry to undo to, and Lexical + * refuses to restore a root without a paragraph, so an empty root gains one first. + */ + private keepUndoBaseline(): void { + if (this.history.current !== null) return + if (this.editor.getEditorState().read(() => $getRoot().isEmpty())) { + this.editor.update(() => { $getRoot().append($createParagraphNode()) }, { discrete: true, tag: HISTORY_MERGE_TAG }) + } + this.history.current = { editor: this.editor, editorState: this.editor.getEditorState() } + } + /** Cut the editor's undo history after a committed clear or restoration. */ clearHistory(): void { this.editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined) diff --git a/packages/client/ui-conversation/src/client/input/editor/text-ref.ts b/packages/client/ui-conversation/src/client/input/editor/text-ref.ts index 5221b38a57..6a09b0c741 100644 --- a/packages/client/ui-conversation/src/client/input/editor/text-ref.ts +++ b/packages/client/ui-conversation/src/client/input/editor/text-ref.ts @@ -69,6 +69,27 @@ export class TextRefNode extends TextNode { } } +/** First reference range of a text, or null. */ +type TextRefMatch = (text: string) => { start: number; end: number } | null + +/** + * Extend a text-ref over the plain text directly after it when both together + * match one reference, such as `@src/a` followed by `.ts`. A selection point + * in the moved text stays beside the same character. + * @param node - plain text node the editor marked dirty. + * @param getMatch - the reference matcher. + */ +function $growTextRef(node: TextNode, getMatch: TextRefMatch): void { + const textRef = node.getPreviousSibling() + if (!(textRef instanceof TextRefNode)) return + const length = textRef.getTextContentSize() + const match = getMatch(textRef.getTextContent() + node.getTextContent()) + if (match === null || match.end <= length) return + if (match.end - length < node.getTextContentSize()) node.splitText(match.end - length) + // A split keeps the leading text under this node's key, possibly in a new writable copy. + textRef.mergeWithSibling(node.getLatest()) +} + /** * Register the plain-text reference entity transform. * @param editor - the shell-owned editor. @@ -79,11 +100,16 @@ export function registerTextRefDecoration( editor: LexicalEditor, lexiconOf: () => ReadonlyMap<'/' | '@', readonly string[]>, ): () => void { - const getMatch = (text: string): { start: number; end: number } | null => { + const getMatch: TextRefMatch = (text) => { const range = scanTextRefs(text, lexiconOf())[0] return range === undefined ? null : { start: range.start, end: range.end } } return mergeRegister( + // The entity transforms below also extend a text-ref over following text, but collapse the + // selection to the text-ref's previous end first, so the next typed character lands before + // the moved text (https://github.com/facebook/lexical/issues/3054). Transforms of one node + // type run in registration order; this one leaves them nothing to extend. + editor.registerNodeTransform(TextNode, (node) => { $growTextRef(node, getMatch) }), ...registerLexicalTextEntity( editor, getMatch, diff --git a/packages/client/ui-conversation/src/client/input/editor/view-binding.ts b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts index 9018592b8b..477d7295bd 100644 --- a/packages/client/ui-conversation/src/client/input/editor/view-binding.ts +++ b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts @@ -136,6 +136,10 @@ export function installDraftKeymap( return keyboard.space() }, dismissPopup: () => { keyboard.dismissPopup() }, + recallHistory: (direction) => { + if (gate.current.machineBusy || gate.current.locked) return false + return keyboard.recallHistory(direction) + }, canSubmit: () => !gate.current.locked && !gate.current.machineBusy, submit: (accelerated) => { const g = gate.current diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 393c88944c..75e471df19 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -10,7 +10,8 @@ */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' -import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionEventLikeEntry, SessionEventSource, SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionSeq } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore, } from '@deepseek-ai/dsh-client-store' @@ -55,6 +56,8 @@ export interface SessionInputDeps { popup?: (() => PopupDismissFace | undefined) | undefined /** Agent Inbox projection; its next-turn list is overlaid onto InputState.queue. */ inbox?: ObservableSnapshot | undefined + /** Loaded Session event window whose human prompts the arrow keys recall; absent = no recall. */ + events?: SessionEventSource | undefined /** * Steer every still-pending queued message into the running turn, in FIFO * order (the empty-draft accelerated-Enter gesture); absent = unsupported. @@ -131,6 +134,34 @@ function errorText(error: unknown): string { const EMPTY_QUEUE: InboxState['next-turn'] = [] +/** One recallable prompt; a run of consecutive identical prompts folds into one, spanning `oldest`..`newest`. */ +interface LoadedPrompt { + readonly text: string + readonly newest: SessionSeq + oldest: SessionSeq +} + +/** + * The recallable human prompts of a loaded event window, newest first: + * their joined text blocks, skipping prompts without text and folding + * consecutive repeats. + * @param entries - the loaded window, oldest first. + * @returns prompts newest first. + */ +function loadedPrompts(entries: readonly SessionEventLikeEntry[]): readonly LoadedPrompt[] { + const prompts: LoadedPrompt[] = [] + for (let index = entries.length - 1; index >= 0; index -= 1) { + const entry = entries[index] + if (entry?.type !== 'event' || entry.event.type !== 'user/message' || entry.event.data.source.kind !== 'user') continue + const text = entry.event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + if (text.trim() === '') continue + const last = prompts.at(-1) + if (last?.text === text) last.oldest = entry.event.seq + else prompts.push({ text, newest: entry.event.seq, oldest: entry.event.seq }) + } + return prompts +} + /** Unavailable catalogs contain no named text references. */ const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() @@ -186,6 +217,14 @@ export class SessionInputShell implements SessionInput { /** The mounted composer's file-picker opener (scoped pick-files event target). */ private filePicker: Parameters[0] | undefined private readonly unsubscribeInbox: (() => void) | undefined + /** + * The log seq of the recalled prompt the draft shows and the draft revision + * that showed it. Neighbours are looked up by seq in the current window on + * every arrow, so prompts appended or loaded while browsing do not shift + * the position. Any later content change, including an undo, leaves the + * revisions unequal and ends browsing. + */ + private recallPosition: { readonly seq: SessionSeq; readonly rev: number } | undefined constructor(private readonly deps: SessionInputDeps) { this.draftEditor = new DraftEditorRuntime({ @@ -232,6 +271,7 @@ export class SessionInputShell implements SessionInput { */ setDraft(text: DraftInput): void { const draft = resolveDraftInput(text) + this.recallPosition = undefined this.cancelCommandRestore() if (draft.references.length === 0 && (draft.quotes?.length ?? 0) === 0) this.draftEditor.setDraft(draft.text) else this.draftEditor.restoreDraft(draft.text, draft.references, draft.quotes, { remove: this.deps.quoteRemoveLabel?.() ?? '' }) @@ -493,6 +533,36 @@ export class SessionInputShell implements SessionInput { // update listener re-tracks at the settled caret on its own. } + /** + * Step through the human prompts in the loaded Session history as plain + * text. Browsing starts from an empty draft and continues only while the + * draft is the unedited prompt it last showed. Inside an editor update (a + * key command), the replacement runs in a microtask after that update. + * @param direction - history direction. + * @returns whether an adjacent prompt exists and the replacement is scheduled. + */ + recallHistory(direction: 'older' | 'newer'): boolean { + const phase = this.core.state.phase + if (this.disposed || (phase !== 'plain' && phase !== 'claimed')) return false + const prompts = loadedPrompts(this.deps.events?.getSnapshot().entries ?? []) + // -1 is the empty draft before the newest prompt. + let index = -1 + const position = this.recallPosition?.rev === this.rev ? this.recallPosition : undefined + if (position !== undefined) index = prompts.findIndex(prompt => prompt.oldest <= position.seq && position.seq <= prompt.newest) + else if (this.projection.clipboardText !== '') return false + if (position !== undefined && index < 0) return false + index += direction === 'older' ? 1 : -1 + if (index < -1 || index >= prompts.length) return false + const target = index < 0 ? undefined : prompts[index] + this.draftEditor.afterUpdate(() => { + // An undoable edit: undo returns to the draft shown before the step. + this.cancelCommandRestore() + this.draftEditor.setDraft(target?.text ?? '', true) + this.recallPosition = target === undefined ? undefined : { seq: target.newest, rev: this.rev } + }) + return true + } + /** Dismiss the popupSelect shell (any interaction outside the box). */ dismissPopup(): void { this.deps.popup?.()?.dismiss() diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index ad18048d26..397a90b7a4 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -178,6 +178,7 @@ export class InputHub implements SessionInputResolver { inputTriggers: () => this.controller(actx), popup: () => this.popup(actx), inbox: session.projections.faceOf('inbox') as ObservableSnapshot, + events: binding.eventSource, defaultSink: (text, attachmentIds, mode, signal, accept) => this.sink(session, text, attachmentIds, mode, signal, accept), quoteRemoveLabel: () => this.t('quote.remove'), session: () => session.getSnapshot(), diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css index 3848b08ee1..6fba9152d4 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css @@ -454,6 +454,49 @@ flex: none; } +/* The width axis's inputs and its continuously varying derived lengths are + registered without inheritance, so they exist only on the body: a resize + that changes them every frame does not restyle the transcript below it. + The resolved lengths compute to absolute values here, and the public + aliases the body declares from them inherit text that changes only when a + resolved width changes. */ +@property --dsh-conversation-column-width { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-conversation-viewport-width { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +/* Without an initial value an unset preference stays invalid, so the body + falls back to the adaptive width. */ +@property --dsh-chat-user-width { + syntax: '*'; + inherits: false; +} + +@property --dsh-chat-content-width-resolved { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-chat-end-reserve-max { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-chat-end-inset-resolved { + syntax: ''; + inherits: false; + initial-value: 0px; +} + /* Band below the header: the scrollport plus the width handles. Anchoring the handles here keeps their full-height strips and glow under the header's bottom edge at every header height. */ @@ -467,10 +510,11 @@ /* Shared width axis for the transcript, dock cards, composer, and takeover cards. Main width controls publish the live body width and optional user preference; embedded occurrences override this adaptive axis below. */ - --dsh-chat-content-width: var( + --dsh-chat-content-width-resolved: var( --dsh-chat-user-width, - clamp(680px, calc(var(--dsh-conversation-column-width, 0px) * 0.64), 880px) + clamp(680px, calc(var(--dsh-conversation-column-width) * 0.64), 880px) ); + --dsh-chat-content-width: var(--dsh-chat-content-width-resolved); --dsh-composer-card-max-width: calc(var(--dsh-chat-content-width) + 32px); --dsh-composer-side-clearance: 16px; --dsh-composer-dock-inset: 8px; @@ -484,23 +528,26 @@ --dsh-chat-end-reserve-max is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger one gets no inset at all, so the surface reads the maximum before it relies - on the room. Every length derives from the scrollport's measured width, + on the room. The maximum varies with every resize and is not inherited: + a stylesheet derives what it needs on this element, as a registered + length that changes only when its own value does. Every length derives from the scrollport's measured width, so the same values hold where a percentage would resolve against another box. The inset applies at once unless the stylesheet also sets --dsh-chat-end-reserve-transition, a duration and an easing, for as long as it wants a change of the inset animated. */ --dsh-chat-end-reserve-max: calc( - var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width) - var(--dsh-composer-side-clearance) - 16px + var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved) - var(--dsh-composer-side-clearance) - 16px ); /* The first term is 0 for a reserve above the maximum and at least 1000px, above any inset, otherwise: a step at the maximum, within a ten-thousandth of a pixel. */ - --dsh-chat-end-inset: min( + --dsh-chat-end-inset-resolved: min( max(0px, calc((var(--dsh-chat-end-reserve-max) - var(--dsh-chat-end-reserve, 0px)) * 10000000 + 1000px)), calc(2 * max( 0px, - var(--dsh-chat-end-reserve, 0px) - (var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width)) / 2 + var(--dsh-chat-end-reserve, 0px) - (var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved)) / 2 )) ); + --dsh-chat-end-inset: var(--dsh-chat-end-inset-resolved); } /* An embedded occurrence makes no room: its column already follows its frame's width. */ diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx index 83b3af7029..82ef114f86 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx @@ -123,13 +123,19 @@ export function ConversationSessionHeader({ useLayoutEffect(() => { const row = tabRow.current if (row === null || !hasEntryActions) return - const updateLimit = (): void => { - setVisibleViewLimit(Math.max(1, Math.floor((row.clientWidth - 48) / 120))) + const updateLimit = (width: number): void => { + setVisibleViewLimit(Math.max(1, Math.floor((width - 48) / 120))) } - updateLimit() + updateLimit(row.clientWidth) if (typeof ResizeObserver === 'undefined') return - const observer = new ResizeObserver(updateLimit) - observer.observe(row) + // The row has padding but no border or scrollbar. Its delivered border-box width, + // rounded like clientWidth, preserves the tab thresholds without forcing layout again. + const observer = new ResizeObserver((entries) => { + for (const entry of entries) { + for (const size of entry.borderBoxSize) updateLimit(Math.round(size.inlineSize)) + } + }) + observer.observe(row, { box: 'border-box' }) return () => { observer.disconnect() } }, [showTabs, hasEntryActions]) const { visibleTabs, moreTabs } = useMemo(() => { diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx index 824fac86ad..577b31830c 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx @@ -158,20 +158,23 @@ function WidthHandle(props: { * @returns two active-phase width handles, or no controls outside the active phase. */ export function ConversationWidthControls({ container, phase }: ConversationWidthControlsProps) { - const publishWidths = useCallback((container: HTMLDivElement): void => { - const target = container.parentElement ?? container - const column = container.offsetWidth - target.style.setProperty('--dsh-conversation-column-width', `${column}px`) + const publishWidths = useCallback((container: HTMLDivElement, column: number): void => { + // The axis registers these inputs without inheritance, so they belong on the body that derives from them. + container.style.setProperty('--dsh-conversation-column-width', `${column}px`) const preference = readWidthPreference() - if (preference === null) target.style.removeProperty('--dsh-chat-user-width') - else target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(column, preference)}px`) + if (preference === null) container.style.removeProperty('--dsh-chat-user-width') + else container.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(column, preference)}px`) }, []) useLayoutEffect(() => { if (container === null) return - const observer = new ResizeObserver(() => { publishWidths(container) }) - observer.observe(container) - publishWidths(container) + const observer = new ResizeObserver((entries) => { + for (const entry of entries) { + for (const size of entry.borderBoxSize) publishWidths(container, Math.round(size.inlineSize)) + } + }) + observer.observe(container, { box: 'border-box' }) + publishWidths(container, container.offsetWidth) return () => { observer.disconnect() } }, [container, publishWidths]) @@ -181,15 +184,14 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt }, [container]) const onDrag = useCallback((width: number): void => { if (container === null) return - const target = container.parentElement ?? container - target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(container.offsetWidth, width)}px`) + container.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(container.offsetWidth, width)}px`) }, [container]) const onCommit = useCallback((width: number): void => { if (container === null) return localStorage.setItem(WIDTH_PREF_KEY, `${resolveContentWidth(container.offsetWidth, width)}`) }, [container]) const onEnd = useCallback((): void => { - if (container !== null) publishWidths(container) + if (container !== null) publishWidths(container, container.offsetWidth) }, [container, publishWidths]) if (container === null || phase !== 'active') return null diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index f7957393d3..37962cf49f 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -28,7 +28,7 @@ import type {} from '@deepseek-ai/dsh-goal/client' // wire types: apiproxy's sessions contract declares it, and client-runtime's // api-remotes import already places it in every client program. import type { Translate } from '@deepseek-ai/dsh-client-ui-slots' -import type { ComposerBarProps } from '../contract/slots.ts' +import type { ComposerBarProps, inputBarChildren } from '../contract/slots.ts' import { DraftEditor } from '../input/editor/DraftEditor.tsx' import { focusDraftEditor, installDraftFilePicker, installDraftKeyboardDismissal, installDraftKeymap, installDraftWheel, @@ -41,13 +41,13 @@ import { ContextMeter } from './ContextMeter.tsx' import { observeControlRow } from './control-row-layout.ts' import css from './InputBar.module.css' -export type InputBarProps = ComposerBarProps +export type InputBarProps = ComposerBarProps export const InputBar = memo(function InputBar({ useSession, useInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, retryFileUpload, registerFileIntake, toggleCommandMenu, stop, retry, t, - renderSlot, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, useStopShortcut, + renderSlot, renderSlotChain, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, useStopShortcut, useAccess, useProjection, sessionId, variant, occurrence, disabled: inert = false, blocked, workspacePickerOpen = false, onRequestWorkspace, @@ -494,6 +494,8 @@ export const InputBar = memo(function InputBar({ editorDisabled={editorDisabled} phase={input?.phase ?? 'inert'} placeholderText={placeholderText} + placeholderSessionId={editable && !canSteerQueue ? sessionId : undefined} + renderSlotChain={renderSlotChain} ariaLabel={workspaceTrigger ? t('hero.chooseWorkspace') : placeholderText} workspaceTrigger={workspaceTrigger} workspacePickerOpen={workspacePickerOpen} diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index 06e4ccd5cb..b99aaef353 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -610,7 +610,7 @@ describe('Conversation inject API', () => { text.select(0, 2) }, { discrete: true }) const off = registerComposerKeymap(editor, { - arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit: () => {}, pasteText: (text) => { composer.keyboard!.paste(text) }, intakeFiles: (files, directories) => { expect(composer.addFiles?.(files, directories)).toBeNull() }, }) diff --git a/packages/client/ui-conversation/tests/composer-bar-props.client.spec.ts b/packages/client/ui-conversation/tests/composer-bar-props.client.spec.ts new file mode 100644 index 0000000000..bfb8475f02 --- /dev/null +++ b/packages/client/ui-conversation/tests/composer-bar-props.client.spec.ts @@ -0,0 +1,46 @@ +import { expect, expectTypeOf, it, vi } from 'vitest' +import type { ComposerBarInjected, ComposerBarProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { SlotCore, type ChildrenDecl, type PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' + +it('accepts props supplied by existing composer bar registrations', () => { + const slots = new SlotCore() + slots.register({ + name: 'root', + children: { 'conversation.composer.bar': { kind: 'single', scope: 'session-maybe' } }, + }, (_props: PropsRenderSlots<'conversation.composer.bar'>) => null) + + const children = { + 'conversation.composer.dock': { kind: 'list', scope: 'session' }, + 'conversation.input.activity': { kind: 'single', scope: 'session' }, + 'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' }, + 'conversation.input.left': { kind: 'list', scope: 'session' }, + 'conversation.input.model': { kind: 'single', scope: 'session' }, + 'conversation.input.overlay': { kind: 'list', scope: 'session' }, + 'conversation.input.permission': { kind: 'single', scope: 'session' }, + 'conversation.input.plan': { kind: 'single', scope: 'session' }, + 'conversation.input.right': { kind: 'list', scope: 'session' }, + } satisfies ChildrenDecl + + const ExistingBar = ({ renderSlot }: ComposerBarProps) => renderSlot('conversation.input.left', {}) + slots.register({ + name: 'conversation.composer.bar', + locale: 'conversation', + children, + inject: vi.fn<() => ComposerBarInjected>(), + }, ExistingBar) + + expect(slots.entries('conversation.composer.bar')[0]?.component).toBe(ExistingBar) + expectTypeOf[0]>().toEqualTypeOf() + expectTypeOf().not.toHaveProperty('renderSlotChain') +}) + +it('dispatches only the children declared by a custom composer bar', () => { + const children = { + 'conversation.input.placeholder': { kind: 'chain', scope: 'session', inline: true }, + 'conversation.input.left': { kind: 'list', scope: 'session' }, + } satisfies ChildrenDecl + type Props = ComposerBarProps + + expectTypeOf[0]>().toEqualTypeOf<'conversation.input.left'>() + expectTypeOf[0]>().toEqualTypeOf<'conversation.input.placeholder'>() +}) diff --git a/packages/client/ui-conversation/tests/composer-history.client.spec.ts b/packages/client/ui-conversation/tests/composer-history.client.spec.ts new file mode 100644 index 0000000000..9df661774a --- /dev/null +++ b/packages/client/ui-conversation/tests/composer-history.client.spec.ts @@ -0,0 +1,428 @@ +// @vitest-environment jsdom +/** Prompt recall from the loaded Session history through the real input shell and the composer keymap. */ +import { setImmediate } from 'node:timers/promises' +import { Context } from '@deepseek-ai/cordis' +import { MutableSessionEventSource } from '@deepseek-ai/dsh-api-session-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' +import { SessionSeq } from '@deepseek-ai/dsh-session/types' +import { fireEvent } from '@testing-library/react' +import { + $createLineBreakNode, $createParagraphNode, $createTextNode, $getRoot, CLEAR_HISTORY_COMMAND, createEditor, KEY_ARROW_UP_COMMAND, + UNDO_COMMAND, +} from 'lexical' +import { registerPlainText } from '@lexical/plain-text' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { CommandClaim, InputTriggerController, SubmitOutcome } from '../src/client/contract/input.ts' +import { registerComposerKeymap } from '../src/client/input/editor/keymap.ts' +import { installDraftKeymap } from '../src/client/input/editor/view-binding.ts' +import { SessionInputShell, type SessionInputDeps } from '../src/client/input/facade.ts' + +/** A loaded event window; `prompt` appends one durable user message, newest last. */ +function history() { + const events = new MutableSessionEventSource() + // Starts above zero so a test can prepend an older page. + let seq = 10 + const message = (content: readonly ContentBlock[], source: MessageSource = { kind: 'user' }): void => { + events.append({ type: 'event', event: { + type: 'user/message', seq: SessionSeq(seq++), time: 0, surfaceOp: 'append', + data: createUserMessage({ content: [...content], source }), + } }) + } + return { events, message, prompt: (text: string) => { message([{ type: 'text', text }]) } } +} + +function makeShell(overrides: Partial = {}): SessionInputShell { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const shell = new SessionInputShell({ + actx: ctx, + defaultSink: () => Promise.resolve({ kind: 'success' }), + commandAttachments: { serialize: () => Promise.resolve([]), release: () => {}, unsupportedNotice: token => token }, + ...overrides, + }) + onTestFinished(() => { shell.dispose() }) + return shell +} + +function withPrompts(...prompts: readonly string[]) { + const h = history() + for (const text of prompts) h.prompt(text) + return { ...h, shell: makeShell({ events: h.events }) } +} + +function triggers(claim: CommandClaim): InputTriggerController { + return { + lexicon: createSnapshotStore(new Map()), + launcher: createSnapshotStore(null), + track: () => {}, + arbitrate: () => 'pass', + onSpace: () => false, + serializeReference: (_source, ref) => Promise.resolve(ref), + adjudicate: () => Promise.resolve(undefined), + resolveClaim: () => Promise.resolve(claim), + openReference: () => false, + toggleSource: () => {}, + } +} + +async function undo(shell: SessionInputShell): Promise { + shell.editor.dispatchCommand(UNDO_COMMAND, undefined) + await setImmediate() + return shell.snapshot.draft +} + +describe('loaded prompt recall', () => { + it('steps through loaded prompts from an empty draft and returns to it past the newest', () => { + const { shell } = withPrompts('first', 'second') + expect(shell.recallHistory('newer')).toBe(false) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('first') + expect(shell.recallHistory('older')).toBe(false) + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('') + expect(shell.recallHistory('newer')).toBe(false) + }) + + it('recalls nothing without an event window or loaded prompts', () => { + expect(makeShell().recallHistory('older')).toBe(false) + expect(withPrompts().shell.recallHistory('older')).toBe(false) + }) + + it('never replaces typed text', () => { + const { shell } = withPrompts('sent') + shell.setDraft('typed') + expect(shell.recallHistory('older')).toBe(false) + expect(shell.snapshot.draft).toBe('typed') + }) + + it('ends browsing once a recalled prompt is edited', () => { + const { shell } = withPrompts('first', 'second') + expect(shell.recallHistory('older')).toBe(true) + shell.paste(' edited') + expect(shell.recallHistory('older')).toBe(false) + expect(shell.recallHistory('newer')).toBe(false) + expect(shell.snapshot.draft).toBe('second edited') + shell.setDraft('') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + }) + + it('ends browsing when the draft is replaced programmatically', () => { + const { shell } = withPrompts('sent') + expect(shell.recallHistory('older')).toBe(true) + shell.setDraft('replacement') + expect(shell.recallHistory('newer')).toBe(false) + expect(shell.snapshot.draft).toBe('replacement') + }) + + it('undoes each step as an ordinary edit, back to the empty draft', async () => { + const { shell } = withPrompts('first', 'second') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.recallHistory('older')).toBe(true) + shell.paste(' edited') + expect(await undo(shell)).toBe('first') + expect(shell.recallHistory('newer')).toBe(false) + expect(await undo(shell)).toBe('second') + expect(await undo(shell)).toBe('') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + }) + + it('keeps an undo target after a submission cut the history', async () => { + const h = history() + const shell = makeShell({ events: h.events }) + shell.setDraft('sent') + shell.submit() + await setImmediate() + h.prompt('sent') + expect(shell.snapshot.draft).toBe('') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('sent') + expect(await undo(shell)).toBe('') + }) + + it('undoes the first step to the existing empty paragraph after the history was cut', async () => { + const { shell } = withPrompts('sent') + shell.setDraft('draft') + shell.setDraft('') + shell.editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined) + expect(shell.recallHistory('older')).toBe(true) + expect(await undo(shell)).toBe('') + }) + + it('recalls only human prompts with text, as plain text, and folds consecutive repeats', () => { + const h = history() + h.prompt('older') + h.prompt('again') + h.prompt('again') + h.message([{ type: 'text', text: 'injected context' }], { kind: 'retry' } as MessageSource) + h.message([{ type: 'text', text: '' }]) + h.message([{ type: 'text', text: 'see ' }, { type: 'reasoning', text: 'not prompt text ' }, { type: 'text', text: '@src/a.ts' }]) + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('see @src/a.ts') + expect(shell.snapshot.occurrences).toHaveLength(0) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('again') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('older') + expect(shell.recallHistory('older')).toBe(false) + }) + + it('keeps its place when a prompt is appended or an older page loads while browsing', () => { + const h = history() + h.prompt('A') + h.prompt('B') + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('B') + h.prompt('C') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('A') + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('B') + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('C') + h.events.prepend([{ type: 'event', event: { + type: 'user/message', seq: SessionSeq(0), time: 0, surfaceOp: 'append', + data: createUserMessage({ content: [{ type: 'text', text: 'older page' }], source: { kind: 'user' } }), + } }], false) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('B') + }) + + it('stays on a folded repeat when its newest copy is appended while browsing', () => { + const h = history() + h.prompt('A') + h.prompt('B') + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + h.prompt('B') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('A') + }) + + it('stops browsing when the shown prompt left the window', () => { + const h = history() + h.prompt('A') + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + h.events.replace([], false) + expect(shell.recallHistory('older')).toBe(false) + expect(shell.snapshot.draft).toBe('A') + }) + + it('reads the window as it is when the arrow arrives', () => { + const h = history() + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(false) + h.prompt('arrived later') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('arrived later') + }) + + it('replaces a claimed command draft and cancels its pending chip restore', async () => { + const claim: CommandClaim = { name: 'goal', token: '/goal ', submit: () => Promise.resolve({ kind: 'success' }) } + const pending = Promise.withResolvers() + const h = history() + h.prompt('plain') + const shell = makeShell({ events: h.events, inputTriggers: () => ({ ...triggers(claim), resolveClaim: () => pending.promise }) }) + shell.setDraft({ text: '', references: [], command: { token: '/goal ' } }) + expect(shell.recallHistory('older')).toBe(true) + pending.resolve(claim) + await setImmediate() + expect(shell.draftSnapshot).toEqual({ text: 'plain', references: [] }) + expect(shell.snapshot.phase).toBe('plain') + }) + + it('recalls through the key command after its update commits', async () => { + const { shell } = withPrompts('sent') + const root = document.createElement('div') + root.contentEditable = 'true' + document.body.append(root) + onTestFinished(() => { shell.editor.setRootElement(null); root.remove() }) + shell.editor.setRootElement(root) + onTestFinished(registerComposerKeymap(shell.editor, { + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: direction => shell.recallHistory(direction), + canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, + })) + window.getSelection()?.collapse(root.firstElementChild ?? root, 0) + expect(fireEvent.keyDown(root, { key: 'ArrowUp' })).toBe(false) + await setImmediate() + expect(shell.snapshot.draft).toBe('sent') + }) + + it('refuses while a submission holds the draft and after disposal', async () => { + let release: (outcome: SubmitOutcome) => void = () => {} + const claim: CommandClaim = { + name: 'goal', token: '/goal ', + submit: () => new Promise((resolve) => { release = resolve }), + } + const { shell } = withPrompts('sent') + shell.setDraft('/goal ') + shell.beginCommand(claim, { start: 0, end: 6, draftRev: shell.snapshot.draftRev }) + shell.submit() + expect(shell.snapshot.phase).toBe('submitting') + expect(shell.recallHistory('older')).toBe(false) + release({ kind: 'success' }) + await setImmediate() + shell.dispose() + expect(shell.recallHistory('older')).toBe(false) + }) +}) + +describe('history arrow routing', () => { + function bench(...lines: readonly string[]) { + const editor = createEditor({ namespace: 'history-arrows', onError: (error) => { throw error } }) + const root = document.createElement('div') + root.contentEditable = 'true' + document.body.append(root) + onTestFinished(() => { editor.setRootElement(null); root.remove() }) + editor.setRootElement(root) + onTestFinished(registerPlainText(editor)) + const recallHistory = vi.fn<(direction: 'older' | 'newer') => boolean>(() => true) + const arbitrate = vi.fn((): 'consumed' | 'pass' => 'pass') + onTestFinished(registerComposerKeymap(editor, { + arbitrate, space: () => false, dismissPopup: () => {}, recallHistory, + canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, + })) + editor.update(() => { + for (const line of lines) { + const paragraph = $createParagraphNode() + for (const [index, part] of line.split('\n').entries()) { + if (index > 0) paragraph.append($createLineBreakNode()) + if (part !== '') paragraph.append($createTextNode(part)) + } + $getRoot().append(paragraph) + } + }, { discrete: true }) + /** Collapse the DOM caret at a child offset of one paragraph, or inside that child's text. */ + const caret = (line: number, offset = 0, child?: number): void => { + const block = root.children.item(line) + if (block === null) throw new Error(`missing line ${String(line)}`) + const text = child === undefined ? undefined : block.childNodes.item(child)?.firstChild + if (child !== undefined && (text === undefined || text === null)) throw new Error(`missing text ${String(child)}`) + window.getSelection()?.collapse(text ?? block, offset) + } + const key = (name: 'ArrowUp' | 'ArrowDown', init: KeyboardEventInit = {}): boolean => + fireEvent.keyDown(root, { key: name, ...init }) + return { root, recallHistory, arbitrate, caret, key } + } + + it('recalls on unmodified arrows the menu passes and consumes the key', () => { + const b = bench('draft') + b.caret(0, 5, 0) + expect(b.key('ArrowUp')).toBe(false) + expect(b.recallHistory).toHaveBeenLastCalledWith('older') + expect(b.key('ArrowDown')).toBe(false) + expect(b.recallHistory).toHaveBeenLastCalledWith('newer') + b.recallHistory.mockReturnValue(false) + expect(b.key('ArrowUp')).toBe(true) + }) + + it.each([{ shiftKey: true }, { altKey: true }, { ctrlKey: true }, { metaKey: true }, { isComposing: true }])( + 'leaves %j arrows to the browser', (init) => { + const b = bench('draft') + b.caret(0, 5, 0) + expect(b.key('ArrowUp', init)).toBe(true) + expect(b.recallHistory).not.toHaveBeenCalled() + }, + ) + + it('lets an open menu consume the arrow first', () => { + const b = bench('draft') + b.caret(0, 5, 0) + b.arbitrate.mockReturnValue('consumed') + expect(b.key('ArrowUp')).toBe(false) + expect(b.recallHistory).not.toHaveBeenCalled() + }) + + it('recalls only with a collapsed caret at the draft end', () => { + const b = bench('top', '', 'bottom') + b.caret(0, 0, 0) + expect(b.key('ArrowUp')).toBe(true) + b.caret(1) + expect(b.key('ArrowDown')).toBe(true) + b.caret(2, 3, 0) + expect(b.key('ArrowUp')).toBe(true) + b.caret(2, 0, 0) + window.getSelection()?.extend(window.getSelection()?.anchorNode ?? b.root, 6) + expect(b.key('ArrowUp')).toBe(true) + expect(b.recallHistory).not.toHaveBeenCalled() + b.caret(2, 6, 0) + expect(b.key('ArrowUp')).toBe(false) + expect(b.key('ArrowDown')).toBe(false) + expect(b.recallHistory).toHaveBeenCalledTimes(2) + }) + + it('treats the end after typed line breaks as the draft end', () => { + const b = bench('a\n\nb') + // Children: text a,
,
, text b. + b.caret(0, 2) + expect(b.key('ArrowUp')).toBe(true) + b.caret(0, 1, 3) + expect(b.key('ArrowUp')).toBe(false) + expect(b.recallHistory).toHaveBeenCalledOnce() + }) + + it('treats an empty draft as at its end and a missing or outside selection as not', () => { + const b = bench('') + b.caret(0) + expect(b.key('ArrowUp')).toBe(false) + window.getSelection()?.removeAllRanges() + expect(b.key('ArrowDown')).toBe(true) + const outside = document.createElement('span') + document.body.append(outside) + onTestFinished(() => { outside.remove() }) + window.getSelection()?.collapse(outside, 0) + expect(b.key('ArrowDown')).toBe(true) + expect(b.recallHistory).toHaveBeenCalledOnce() + }) + + it('does not recall without a mounted root to read the caret from', () => { + const b = bench('draft') + b.caret(0, 5, 0) + const editor = createEditor({ namespace: 'detached', onError: (error) => { throw error } }) + const recallHistory = vi.fn(() => true) + onTestFinished(registerComposerKeymap(editor, { + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory, + canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, + })) + editor.update(() => { $getRoot().append($createParagraphNode()) }, { discrete: true }) + expect(editor.dispatchCommand(KEY_ARROW_UP_COMMAND, new KeyboardEvent('keydown', { key: 'ArrowUp' }))).toBe(false) + expect(recallHistory).not.toHaveBeenCalled() + }) + + it.each([ + { locked: true, machineBusy: false, recalls: false }, + { locked: false, machineBusy: true, recalls: false }, + { locked: false, machineBusy: false, recalls: true }, + ])( + 'the view gate passes recall through only when open: %j', ({ recalls, ...gate }) => { + const editor = createEditor({ namespace: 'gated', onError: (error) => { throw error } }) + const root = document.createElement('div') + root.contentEditable = 'true' + document.body.append(root) + onTestFinished(() => { editor.setRootElement(null); root.remove() }) + editor.setRootElement(root) + onTestFinished(registerPlainText(editor)) + const shell = makeShell() + const recallHistory = vi.spyOn(shell, 'recallHistory') + onTestFinished(installDraftKeymap(editor, shell, { + current: { + ...gate, canSteerQueue: false, running: false, steeringAvailable: false, busyEnter: 'queue', + intakeFiles: () => {}, uploadsPending: false, uploadsHeldText: '', showToast: () => {}, canAcceptDrop: false, + }, + })) + window.getSelection()?.collapse(root.firstElementChild ?? root, 0) + expect(fireEvent.keyDown(root, { key: 'ArrowUp' })).toBe(true) + expect(recallHistory).toHaveBeenCalledTimes(recalls ? 1 : 0) + }, + ) +}) diff --git a/packages/client/ui-conversation/tests/draft-document.client.spec.ts b/packages/client/ui-conversation/tests/draft-document.client.spec.ts index 8e50e1ad3a..957fdd9f1e 100644 --- a/packages/client/ui-conversation/tests/draft-document.client.spec.ts +++ b/packages/client/ui-conversation/tests/draft-document.client.spec.ts @@ -14,6 +14,7 @@ import { scanTextRefs } from '../src/client/input/decorations.ts' import { ReferenceChipNode } from '../src/client/input/editor/chip-node.tsx' import { CommandChipNode } from '../src/client/input/editor/command-chip-node.tsx' import { QuoteNode } from '../src/client/input/editor/QuoteNode.tsx' +import { $selectDetectSpan } from '../src/client/input/editor/span-map.ts' import { TextRefNode } from '../src/client/input/editor/text-ref.ts' import { SessionInputShell, type SessionInputDeps } from '../src/client/input/facade.ts' @@ -856,3 +857,54 @@ describe('plain-text reference catalogs', () => { expect(slices('drill @"open dir/。')).toEqual(['@"open dir/']) }) }) + +describe('path references typed one character at a time', () => { + /** Insert each character at the live selection as its own edit, the way key presses arrive. */ + function typeText(shell: SessionInputShell, text: string): void { + for (const char of text) shell.paste(char) + } + + it.each([ + ['@src/index.ts', ['@src/index.ts']], + ['@vite.config.ts', ['@vite.config.ts']], + ['@out/v1.2/readme', ['@out/v1.2/readme']], + ['@out/w1,x', ['@out/w1,x']], + ['看下 @src/app.test.ts 有问题', ['@src/app.test.ts']], + ])('keeps %s in typed order with the caret after the last character', (text, references) => { + const shell = makeShell() + typeText(shell, text) + expect(shell.snapshot.draft).toBe(text) + expect(shell.caretSpan()).toEqual({ start: text.length, end: text.length }) + expect(textReferences(shell)).toEqual(references) + }) + + it('leaves punctuation that ends a sentence outside the reference', () => { + const shell = makeShell() + typeText(shell, '@src/a.ts. Next') + expect(shell.snapshot.draft).toBe('@src/a.ts. Next') + expect(shell.caretSpan()).toEqual({ start: 15, end: 15 }) + expect(textReferences(shell)).toEqual(['@src/a.ts']) + }) + + it('extends a reference over the start of a longer run and keeps the caret after the typed character', () => { + const shell = makeShell() + typeText(shell, '@src/a. x') + expect(textReferences(shell)).toEqual(['@src/a']) + shell.editor.update(() => { $selectDetectSpan({ start: 7, end: 7 }) }, { discrete: true }) + typeText(shell, 't') + expect(shell.snapshot.draft).toBe('@src/a.t x') + expect(shell.caretSpan()).toEqual({ start: 8, end: 8 }) + expect(textReferences(shell)).toEqual(['@src/a.t']) + }) + + it('leaves the text after a named reference in place when its catalog drops the name', async () => { + const lexicon = createSnapshotStore>(new Map([['@', ['alice']]])) + const provider = triggerProvider(lexicon) + const shell = makeShell({ inputTriggers: () => provider }) + typeText(shell, '@alice.') + expect(textReferences(shell)).toEqual(['@alice']) + lexicon.set(new Map()) + await vi.waitFor(() => { expect(textReferences(shell)).toEqual([]) }) + expect(shell.snapshot.draft).toBe('@alice.') + }) +}) diff --git a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts index b662a89141..d5a246296d 100644 --- a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts +++ b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts @@ -27,13 +27,33 @@ describe('Conversation body end reserve', () => { it('derives the largest reserve and the inset from the scrollport width, the content width, and the side inset', () => { expect(body['--dsh-composer-side-clearance']).toBe('16px') expect(body['--dsh-chat-end-reserve-max']).toBe( - 'calc(var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width) - var(--dsh-composer-side-clearance) - 16px)', + 'calc(var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved) - var(--dsh-composer-side-clearance) - 16px)', ) - expect(body['--dsh-chat-end-inset']).toBe( + expect(body['--dsh-chat-end-inset-resolved']).toBe( 'min(max(0px, calc((var(--dsh-chat-end-reserve-max) - var(--dsh-chat-end-reserve, 0px)) * 10000000 + 1000px)),' + ' calc(2 * max(0px, var(--dsh-chat-end-reserve, 0px)' - + ' - (var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width)) / 2)))', + + ' - (var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved)) / 2)))', ) + expect(body['--dsh-chat-end-inset']).toBe('var(--dsh-chat-end-inset-resolved)') + }) + + it('keeps the continuously varying lengths on the body and publishes resolved lengths to its descendants', () => { + // Registered without inheritance: a resize that changes them every frame does not restyle the transcript. + const registered = Object.fromEntries([...css.matchAll(/@property\s+(--[\w-]+)\s*\{([^{}]*)\}/g)] + .map((match): [string, string] => [match[1] ?? '', (match[2] ?? '').replace(/\s+/g, ' ').trim()])) + expect(registered).toEqual({ + '--dsh-conversation-column-width': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-conversation-viewport-width': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-user-width': "syntax: '*'; inherits: false;", + '--dsh-chat-content-width-resolved': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-end-reserve-max': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-end-inset-resolved': "syntax: ''; inherits: false; initial-value: 0px;", + }) + // The inherited public names repeat a computed length, whose text changes only with the resolved width. + expect(body['--dsh-chat-content-width-resolved']).toBe( + 'var(--dsh-chat-user-width, clamp(680px, calc(var(--dsh-conversation-column-width) * 0.64), 880px))', + ) + expect(body['--dsh-chat-content-width']).toBe('var(--dsh-chat-content-width-resolved)') }) it('moves the column aside by twice the missing gutter at its own width, and makes no room once the start gutter is at the side inset', () => { diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index 630ad9e2cd..25ecc67fb4 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -14,7 +14,7 @@ import './control-row-dom.ts' import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' -import { act, cleanup, fireEvent, render } from '@testing-library/react' +import { act, cleanup, fireEvent, render, within } from '@testing-library/react' import { createPortal } from 'react-dom' import { $getRoot, $isTextNode } from 'lexical' import { @@ -32,6 +32,7 @@ import { SessionInputShell } from '../src/client/input/facade.ts' import { $replaceDetectSpanWithText, $selectDetectSpan } from '../src/client/input/editor/span-map.ts' import type { ComposerAttachment, ComposerAttachmentsOwnerProps, ComposerFileIntake, DraftFileUploads, InputActivityOwnerProps, + InputPlaceholderOwnerProps, } from '../src/client/contract/slots.ts' import type { DraftAttachmentId } from '../src/client/contract/input.ts' import { InputBar } from '../src/client/skeleton/InputBar.tsx' @@ -99,6 +100,7 @@ interface BenchOptions { occurrence?: 'main' | 'embedded' registerFileIntake?: ComposerFileIntake placeholder?: string + renderSlotChain?: InputBarProps['renderSlotChain'] t?: InputBarProps['t'] accessory?: React.ReactNode overlay?: React.ReactNode @@ -233,6 +235,7 @@ function bench(over?: BenchOptions) { // Mirrors the real lookup chain (conversation namespace, then common). t: over?.t ?? makeTranslate(zh, commonZh), renderSlot, + renderSlotChain: over?.renderSlotChain ?? ((_key, _owner, options) => options?.fallback), variant: over?.variant ?? 'composer', occurrence: over?.occurrence ?? 'main', ...(over?.inert === true ? { disabled: true } : {}), @@ -466,6 +469,55 @@ describe('composer focus handoff', () => { }) describe('composer placeholder visibility', () => { + const reviewHint: InputBarProps['renderSlotChain'] = (_key, owner, options) => + (owner as InputPlaceholderOwnerProps).sessionId === SID ? Review @ files : options?.fallback + + it('names each empty editor from its own Session hint and restores its name after typing', () => { + const options = { plan: { active: true, pending: false }, renderSlotChain: reviewHint } + const first = bench(options) + const second = bench(options) + second.view.rerender() + + expect(first.view.getByRole('textbox', { name: 'Review @ files' })).toBe(first.textarea) + expect(second.view.getByRole('textbox', { name: zh['placeholder.plan'] })).toBe(second.textarea) + expect(first.view.container.querySelector('[data-composer-placeholder] kbd')?.textContent).toBe('@') + writeDraft(first.shell, 'My draft') + expect(first.view.container.querySelector('[data-composer-placeholder]')).toBeNull() + expect(within(first.view.container).getByRole('textbox', { name: zh['placeholder.plan'] })).toBe(first.textarea) + writeDraft(first.shell, '') + expect(first.view.getByRole('textbox', { name: 'Review @ files' })).toBe(first.textarea) + }) + + it('restores the hint when the last attachment leaves an empty draft', () => { + const id = 'image' as DraftAttachmentId + const { view, shell, textarea } = bench({ + renderSlotChain: reviewHint, + attachments: [{ kind: 'image', id, file: new File([], 'x.png'), previewUrl: 'blob:test' }], + }) + expect(view.container.querySelector('[data-composer-placeholder]')).toBeNull() + act(() => { shell.removeAttachment(id) }) + expect(view.getByRole('textbox', { name: 'Review @ files' })).toBe(textarea) + }) + + it.each([ + { + state: 'Workspace picker', + options: { inert: true, onRequestWorkspace: () => {}, placeholder: zh['placeholder.workspace'] }, + text: zh['placeholder.workspace'], name: zh['hero.chooseWorkspace'], + }, + { + state: 'composer block', + options: { blocked: { reason: 'Select a model' }, placeholder: 'Select a model' }, + text: 'Select a model', + }, + { state: 'unavailable Session', options: { disabled: true }, text: zh['placeholder.unavailable'] }, + { state: 'queued messages', options: { running: true, queue: [row('pending')] }, text: zh['placeholder.steerQueue'] }, + ])('keeps the $state guidance when a plugin supplies a hint', ({ options, text, name }) => { + const { view, textarea } = bench({ ...options, renderSlotChain: reviewHint }) + expect(view.container.querySelector('[data-composer-placeholder]')?.textContent).toBe(text) + expect(view.getByRole('textbox', { name: name ?? text })).toBe(textarea) + }) + it.each([' ', ' ', '\t', '\n'])('hides for whitespace %j and returns after deletion', async (draft) => { const { view, shell, textarea, button, sink, props } = bench() const placeholder = () => view.container.querySelector('[data-composer-placeholder]') diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index cca80d2934..84181584d8 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -94,6 +94,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled useLexicon: bindSnapshotSelector(shell.lexicon), useMenuLauncher: bindSnapshotSelector(createSnapshotStore(null)), renderSlot: (() => null) as InputBarProps['renderSlot'], + renderSlotChain: (_key, _owner, options) => options?.fallback, stop: vi.fn(), t: makeTranslate(zh, commonZh), variant: 'composer', diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 1f73eaf740..771325d6b0 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -203,6 +203,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo useLexicon: bindSnapshotSelector(shell.lexicon), useMenuLauncher: bindSnapshotSelector(controller.launcher), renderSlot: (() => null) as InputBarProps['renderSlot'], + renderSlotChain: (_key, _owner, options) => options?.fallback, stop: vi.fn(), retry: undefined, useStopShortcut: bindSnapshotSelector(createSnapshotStore([])), diff --git a/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx b/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx index 66008b4c7b..d061bd06f5 100644 --- a/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx +++ b/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx @@ -25,7 +25,7 @@ describe('keymap keydown routing', () => { }) editor.setRootElement(first) const unregister = registerComposerKeymap(editor, { - arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => false, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, }) onTestFinished(unregister) @@ -57,7 +57,7 @@ describe('keymap keydown routing', () => { registerComposerKeymap(editor, { arbitrate: () => 'pass', space: () => false, - dismissPopup: () => {}, + dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit, intakeFiles: () => {}, @@ -88,7 +88,7 @@ describe('keymap keydown routing', () => { const submit = vi.fn() const arbitrate = vi.fn(() => 'pass' as const) onTestFinished(registerComposerKeymap(editor, { - arbitrate, space: () => false, dismissPopup: () => {}, canSubmit: () => true, + arbitrate, space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit, intakeFiles: () => {}, pasteText: () => {}, })) editor.update(() => { @@ -125,7 +125,7 @@ describe('keymap keydown routing', () => { registerComposerKeymap(editor, { arbitrate, space: () => false, - dismissPopup: () => {}, + dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, @@ -164,7 +164,7 @@ describe('keymap keydown routing', () => { editor.setRootElement(root) onTestFinished(registerPlainText(editor)) onTestFinished(registerComposerKeymap(editor, { - arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, canSubmit: () => true, + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, })) return { editor, root, modify } diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index acb3f5dc6e..49aed1dcfd 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -79,9 +79,14 @@ class ResizeObserverStub { } /** Fires every recorded observer whose target list includes the element. */ -function fireResize(el: Element): void { +function fireResize(el: Element, inlineSize = 0): void { + const size = [{ inlineSize, blockSize: 0 }] + const change: ResizeObserverEntry = { + target: el, contentRect: new DOMRectReadOnly(0, 0, inlineSize, 0), + borderBoxSize: size, contentBoxSize: size, devicePixelContentBoxSize: size, + } for (const entry of resizeObservers) { - if (entry.targets.includes(el)) entry.callback([], undefined as never) + if (entry.targets.includes(el)) entry.callback([change], undefined as never) } } @@ -327,6 +332,7 @@ function mount( useMenuLauncher={bindSnapshotSelector(createSnapshotStore(null))} stop={stop} t={t} + renderSlotChain={(_key, _owner, options) => options?.fallback} renderSlot={((key: string, seatOwner: object) => { // The bar's own seats: recorded so a case can assert what share // each tool-row control received. @@ -836,22 +842,22 @@ describe('ConversationRoot resident composer', () => { }) it('folds and restores Views on container resize without changing selection, and disconnects on unmount', () => { - let width = 1000 - vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => width) + const liveWidth = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(1000) const viewTabs = ['chat', 'trajectory', 'timeline', 'inspector', 'notes'].map(id => ({ id, label: id })) const b = mount(sessionSnapshotOf(), undefined, undefined, { viewTabs, entryActions: true }) const row = b.view.getByRole('tablist').parentElement! const external = () => within(b.view.getByRole('tablist')).getAllByRole('tab').map(tab => tab.textContent) expect(external()).toEqual(viewTabs.map(tab => tab.label)) act(() => { b.store.actions.setView('notes') }) - width = 300 - act(() => { fireResize(row) }) + liveWidth.mockClear() + // 287.6px rounds to 288px (two Views); do not re-read a changed DOM during delivery. + act(() => { fireResize(row, 287.6) }) expect(external()).toEqual(['chat', 'trajectory']) fireEvent.click(b.view.getByRole('button', { name: zh['session.moreViews'] })) expect(b.actionsOwner().entries.map(entry => entry.id)).toEqual(['timeline', 'inspector', 'notes']) expect(b.actionsOwner().entries.find(entry => entry.id === 'notes')?.active).toBe(true) - width = 1000 - act(() => { fireResize(row) }) + act(() => { fireResize(row, 1000) }) + expect(liveWidth.mock.contexts).not.toContain(row) expect(external()).toEqual(viewTabs.map(tab => tab.label)) expect(b.view.getByRole('tab', { name: 'notes' }).getAttribute('aria-selected')).toBe('true') expect(b.actionsOwner().entries).toEqual([]) @@ -950,26 +956,23 @@ describe('ConversationRoot resident composer', () => { expect(b.view.queryByRole('button', { name: 'Retry' })).toBeNull() }) - it('publishes the column width as a px variable for the shared width axis', () => { + it('publishes the column width as a px variable on the body for the shared width axis', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement - const root = content.parentElement as HTMLElement - // jsdom offsetWidth is 0 until faked: the observer publishes whatever the - // layout reports, and the CSS clamp() floors the axis at 680px either way. - Object.defineProperty(content, 'offsetWidth', { value: 1200, configurable: true }) - act(() => { fireResize(content) }) - expect(root.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px') + const readWidth = vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get') + act(() => { fireResize(content, 1199.75) }) + expect(content.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px') + expect(readWidth.mock.contexts).not.toContain(content) // No dragged preference: the user-width override stays absent so the // adaptive clamp term applies. - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('') }) it('drag → persist → window clamp round-trip on a width handle', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement - const root = content.parentElement as HTMLElement Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true }) - act(() => { fireResize(content) }) + act(() => { fireResize(content, 1600) }) const handle = b.view.container.querySelector('[data-width-handle="right"]') as HTMLElement expect(handle).not.toBeNull() // jsdom lacks pointer capture: emulate per-element so hasPointerCapture @@ -991,13 +994,13 @@ describe('ConversationRoot resident composer', () => { expect(handle.style.getPropertyValue('--dsh-width-handle-pointer-y')).toBe('300px') fireEvent.pointerUp(handle, { pointerId: 1, clientX: 825, clientY: 300 }) expect(handle.hasAttribute('data-dragging')).toBe(false) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px') expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') // Window shrinks: the displayed width re-clamps (900 − 176 = 724) but the // preference stays. Object.defineProperty(content, 'offsetWidth', { value: 900, configurable: true }) - act(() => { fireResize(content) }) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') + act(() => { fireResize(content, 900) }) + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') // A press without travel (a real double-click delivers two such // press/release rounds) must not commit the clamped display value over @@ -1005,7 +1008,7 @@ describe('ConversationRoot resident composer', () => { fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 }) fireEvent.pointerUp(handle, { pointerId: 1, clientX: 800, clientY: 300 }) expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') // No reset affordance on the handle: double-click leaves the preference alone. fireEvent.doubleClick(handle) expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') @@ -1020,10 +1023,9 @@ describe('ConversationRoot resident composer', () => { it('changes the width by the pointer travel, not twice it, while the scrollport pads its end for a reserve', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement - const root = content.parentElement as HTMLElement const scrollport = content.querySelector('[data-conversation-scroll]') as HTMLElement Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true }) - act(() => { fireResize(content) }) + act(() => { fireResize(content, 1600) }) const handle = b.view.container.querySelector('[data-width-handle="left"]') as HTMLElement const names = ['setPointerCapture', 'releasePointerCapture', 'hasPointerCapture'] as const const originals = names.map(name => @@ -1042,12 +1044,12 @@ describe('ConversationRoot resident composer', () => { // The reserve holds the column's end edge: 25px outward on the start handle moves the start edge 25px → 880 + 25. fireEvent.pointerDown(handle, { pointerId: 1, clientX: 400, clientY: 300 }) fireEvent.pointerUp(handle, { pointerId: 1, clientX: 375, clientY: 300 }) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('905px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('905px') // Without the inset the column is centered and both edges move: 905 + 2 × 10. inset = '0px' fireEvent.pointerDown(handle, { pointerId: 1, clientX: 400, clientY: 300 }) fireEvent.pointerUp(handle, { pointerId: 1, clientX: 390, clientY: 300 }) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('925px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('925px') } finally { for (const [name, descriptor] of originals) { if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name) diff --git a/packages/client/ui-dockkit/README.i18n.yaml b/packages/client/ui-dockkit/README.i18n.yaml index 73075677d1..ba8a0d242d 100644 --- a/packages/client/ui-dockkit/README.i18n.yaml +++ b/packages/client/ui-dockkit/README.i18n.yaml @@ -21,8 +21,8 @@ en: 5e025290e8881fa8 zh: 2bc9c3ff83914241 /deepseek-ai-dsh-client-ui-dockkit/interaction-rules-worth-keeping: - en: cf2d00ce2b7d5719 - zh: 5510420f8872e23a + en: a34ab619b8c1d740 + zh: b645bb7600e640db /deepseek-ai-dsh-client-ui-dockkit/build-shape: en: 69f87827f149270f zh: 65e41db2b2400cd5 diff --git a/packages/client/ui-dockkit/README.md b/packages/client/ui-dockkit/README.md index a8d99c1568..e3f725493f 100644 --- a/packages/client/ui-dockkit/README.md +++ b/packages/client/ui-dockkit/README.md @@ -80,9 +80,9 @@ The split control accepts localized tooltip text, separate effective keys throug These are not stylistic; each one fixes a defect found in a real browser. - **Capture the pointer** when a gesture starts. Without it any scroll container the pointer crosses can claim the gesture, which the browser reports as a cancelled pointer and an abandoned drag. Capture is hardening — the window listeners carry the gesture either way, so an environment without the API still works. -- **The chips give way; the strip's end controls never do.** The chip box is the strip's one shrinking part (`flex: 0 1 auto; min-width: 0; overflow-x: auto`): chips shrink down to an 80px floor and then scroll on the wheel with no scrollbar drawn, and the box fades its chips out over 24px at each side that hides some (`data-dockkit-strip-scroll`, written from the box's scroll reading after each commit, scroll, and resize). Whenever the active tab or the row of chips changes, the box scrolls so the active chip stands clear of the fade band; a chip already in view moves nothing. Where `DockLayout` draws a new strip for each newly selected tab, that strip first jumps to the offset the pane's previous strip recorded, so only the remaining distance animates; a strip with no recorded offset jumps straight to the active chip instead of scrolling from the row's start. A chip's title is never ellipsized: `TabTitle` reads its text against its box and sets `data-dockkit-tab-clipped` while the text is wider, which fades the text out over its last 16px. A chip's close control shows while the chip is active, hovered, or holds focus, over the title's last 14px, which fade under it, so the chip is the same width either way. The two slots beside the active chip draw no hairline, so the filled capsule stands between bare chips. The add, split, and chrome controls are `flex: none`, so they keep their width and place in any pane at least as wide as they are (about 130px with the chrome, 72px without). The surface's `min-width: 0` and the pane's `overflow: hidden` stop a body's longest unwrapped line from widening the pane past its box, which is what carried the controls and the body's scrollbar off-screen. +- **The chips give way; the strip's end controls never do.** The chip box is the strip's one shrinking part (`flex: 0 1 auto; min-width: 0; overflow-x: auto`): chips shrink down to an 80px floor and then scroll on the wheel with no scrollbar drawn, and the box fades its chips out over 24px at each side that hides some (`data-dockkit-strip-scroll`, written from the box's scroll reading after each commit, scroll, and resize). Whenever the active tab or the row of chips changes, the box scrolls so the active chip stands clear of the fade band; a chip already in view moves nothing. Where `DockLayout` draws a new strip for each newly selected tab, that strip first jumps to the offset the pane's previous strip recorded, so only the remaining distance animates; a strip with no recorded offset jumps straight to the active chip instead of scrolling from the row's start. A chip's title is never ellipsized: the last 16px of the title box always fade, including when a title just fits. The fade needs no width measurement. A chip's close control shows while the chip is active, hovered, or holds focus, over the title's last 14px, which fade under it, so the chip is the same width either way. The two slots beside the active chip draw no hairline, so the filled capsule stands between bare chips. The add, split, and chrome controls are `flex: none`, so they keep their width and place in any pane at least as wide as they are (about 130px with the chrome, 72px without). The surface's `min-width: 0` and the pane's `overflow: hidden` stop a body's longest unwrapped line from widening the pane past its box, which is what carried the controls and the body's scrollbar off-screen. - **The chip box scrolls, but never claims a gesture.** A horizontal scroller would take press-and-move for itself and cancel the pointer; the box, the chips, and the strip set `touch-action: none` and the gesture captures the pointer, so a press-and-move on a chip is a drag and only the wheel scrolls the box. -- **A split needs room for two working halves.** A pane splits into equal halves, so each half must hold what cannot shrink: the strip's fixed part — measured as the strip's width minus the chip box and the fill, which is the padding, the gaps, and every control that pane draws (its own chrome included, so the top-right pane asks more) — plus one chip at its minimum — `.tab` declares `min-width: 80px` on a content-box, so its footprint is 80px plus 10px + 10px of padding, 100px, read from a rendered chip's computed style (the stylesheet figure when none can be read); the divider between the halves takes its rendered thickness (0 — its hairline paints over the seam without taking layout room, so a body's own rules run unbroken past it). A column split, which only an edge drop makes, needs each half to hold the strip (34px) plus a 48px body: one 13px secondary line at 1.6 line-height inside 12px of the body's own insets — the pane body itself is unpadded, so a tab's body reaches the strip's bottom edge and the pane's edges and draws its own. `halvesFit` in `geometry.ts` is the arithmetic; `measure.ts` reads the rectangles after every commit and whenever the surface resizes, because the layout state carries fractions, never pixels, and the engine's planners stay that way. A pane without room keeps its split control, disabled with `splitPaneNarrow` (hidden instead under `hideSplitWhenBlocked`), and offers no edge drop zone for that axis (the release is then not a move). Under `hideSplitWhenBlocked` the split control's own footprint — its box plus the strip's gap — is left out of the fixed part: hiding the control sheds exactly that footprint from the strip, so a reading that counted it would flip with the control's visibility and re-render forever; leaving it out is also what the half being asked about would carry, since a half too narrow to split hides its own control. A pane the user narrows afterwards — a divider or the embedder's column dragged — keeps its size: the rule only decides its next split. +- **A split needs room for two working halves.** A pane splits into equal halves, so each half must hold what cannot shrink: the strip's fixed part — measured as the strip's width minus the chip box and the fill, which is the padding, the gaps, and every control that pane draws (its own chrome included, so the top-right pane asks more) — plus one chip at its minimum — `.tab` declares `min-width: 80px` on a content-box, so its footprint is 80px plus 10px + 10px of padding, 100px, read from a rendered chip's computed style (the stylesheet figure when none can be read); the divider between the halves takes its rendered thickness (0 — its hairline paints over the seam without taking layout room, so a body's own rules run unbroken past it). A column split, which only an edge drop makes, needs each half to hold the strip (34px) plus a 48px body: one 13px secondary line at 1.6 line-height inside 12px of the body's own insets — the pane body itself is unpadded, so a tab's body reaches the strip's bottom edge and the pane's edges and draws its own. `halvesFit` in `geometry.ts` is the arithmetic; `measure.ts` reads the rectangles when the dock layout or split policy changes, and on size notifications for the surface, panes, and strip boxes. An embedder resizing its column does not require a separate measurement during its render commit. A pane without room keeps its split control, disabled with `splitPaneNarrow` (hidden instead under `hideSplitWhenBlocked`), and offers no edge drop zone for that axis (the release is then not a move). Under `hideSplitWhenBlocked` the split control's own footprint — its box plus the strip's gap — is left out of the fixed part: hiding the control sheds exactly that footprint from the strip, so a reading that counted it would flip with the control's visibility and re-render forever; leaving it out is also what the half being asked about would carry, since a half too narrow to split hides its own control. A pane the user narrows afterwards — a divider or the embedder's column dragged — keeps its size: the rule only decides its next split. - **Focus lands on click, not on press.** A state change between `pointerdown` and the first `pointermove` rebuilds the pressed subtree, and a replaced element cancels the pointer. It also keeps a drag from recording a redundant focus operation first. Clicks on the chips, the strip's controls, and the embedder's chrome stop at the strip: the intent each reports already decides the active pane, or is the embedder's own, so the pane's click-to-focus records nothing extra. A floating panel's grip and corner report through their gesture the same way — a press released in place is a click that raises the panel, and a drag records only the move or resize, whose operation raises it — while a press on the panel's body raises it directly. A click on the pane that is active already, a click or key on that pane's selected chip, or a press on the panel that is active and on top already, changes nothing and records nothing. - **A control nested inside a draggable chip stops its own press.** Otherwise the press starts a drag, captures the pointer, and the nested control's click never lands. - **Emphasis takes the platform's accent, never `--dsw-alias-brand-primary`.** This platform binds `brand-primary` to its near-black (light) or near-white (dark) foreground, so the drop caret and the drop-zone hint use `--dsw-alias-brand-primary-new-colorprimary-new-color`, as the trajectory views do; a hovered divider takes the caption label ink instead, reading as a handle rather than a highlight. A floating panel draws no border — the menu's shadow (`--dsw-elevation-prominent`) outlines it — and the active panel gets no heavier frame: it is already on top and casts the same shadow; a darker frame around it read as a defect. diff --git a/packages/client/ui-dockkit/README.zh.md b/packages/client/ui-dockkit/README.zh.md index 6fbacf6dd5..67a227ff0b 100644 --- a/packages/client/ui-dockkit/README.zh.md +++ b/packages/client/ui-dockkit/README.zh.md @@ -80,9 +80,9 @@ Sidebar 使用的 `DockLayout` 在选中项变化、跨格移动与浮动期间 这些不是风格偏好;每一条都修复了在真实浏览器里发现的缺陷。 - **手势开始时捕获指针。** 不捕获的话,指针经过的任何滚动容器都可能接管手势,浏览器会将其报告为指针取消和拖动中止。捕获是加固——无论如何都由 window 监听器承载手势,所以没有该 API 的环境照样可用。 -- **chip 让位;tab 条末端的控件永不让位。** chip 盒是 tab 条里唯一会收缩的部分(`flex: 0 1 auto; min-width: 0; overflow-x: auto`):chip 先缩到 80px 下限,再在盒内随滚轮横向滚动、不画滚动条,且盒在每个藏有 chip 的一侧把 chip 在 24px 内渐隐(`data-dockkit-strip-scroll`,在每次提交、滚动与尺寸变化后由盒的滚动读数写入)。每当活动 tab 或 chip 的排列变化,盒会滚动到让活动 chip 避开渐隐带;已在视野内的 chip 不动。`DockLayout` 为每个新选中的 tab 画出新 tab 条时,新 tab 条先跳到该格上一条 tab 条记录的偏移,只让剩余距离带动画;没有记录偏移的 tab 条直接跳到活动 chip,而不是从排列起点滚动过去。chip 的标题从不加省略号:`TabTitle` 拿文字宽度对照它的盒子,文字更宽时置 `data-dockkit-tab-clipped`,让文字在末端 16px 内渐隐。chip 的关闭控件在 chip 活动、悬停或持有焦点时显示,压在标题末端 14px 之上、标题在其下渐隐,因此 chip 宽度两种情况下都一样。活动 chip 两侧的槽不画细线,让填色胶囊立在裸 chip 之间。添加、分栏与 chrome 控件都是 `flex: none`,因此在任何不窄于它们自身的格里(带 chrome 约 130px,不带约 72px)都保持宽度与位置。停靠面的 `min-width: 0` 与格的 `overflow: hidden` 阻止正文里最长的不换行行把格撑出自己的盒子——正是那种情况把控件和正文滚动条推到了屏幕外。 +- **chip 让位;tab 条末端的控件永不让位。** chip 盒是 tab 条里唯一会收缩的部分(`flex: 0 1 auto; min-width: 0; overflow-x: auto`):chip 先缩到 80px 下限,再在盒内随滚轮横向滚动、不画滚动条,且盒在每个藏有 chip 的一侧把 chip 在 24px 内渐隐(`data-dockkit-strip-scroll`,在每次提交、滚动与尺寸变化后由盒的滚动读数写入)。每当活动 tab 或 chip 的排列变化,盒会滚动到让活动 chip 避开渐隐带;已在视野内的 chip 不动。`DockLayout` 为每个新选中的 tab 画出新 tab 条时,新 tab 条先跳到该格上一条 tab 条记录的偏移,只让剩余距离带动画;没有记录偏移的 tab 条直接跳到活动 chip,而不是从排列起点滚动过去。chip 的标题从不加省略号:标题盒的末端 16px 始终渐隐,文字刚好放得下时也一样,无需测量宽度。chip 的关闭控件在 chip 活动、悬停或持有焦点时显示,压在标题末端 14px 之上、标题在其下渐隐,因此 chip 宽度两种情况下都一样。活动 chip 两侧的槽不画细线,让填色胶囊立在裸 chip 之间。添加、分栏与 chrome 控件都是 `flex: none`,因此在任何不窄于它们自身的格里(带 chrome 约 130px,不带约 72px)都保持宽度与位置。停靠面的 `min-width: 0` 与格的 `overflow: hidden` 阻止正文里最长的不换行行把格撑出自己的盒子——正是那种情况把控件和正文滚动条推到了屏幕外。 - **chip 盒会滚动,但绝不认领手势。** 横向滚动容器会把按下并移动的手势据为己有并取消指针;盒、chip 与 tab 条都设 `touch-action: none`,手势又捕获了指针,所以在 chip 上按下并移动是拖动,只有滚轮滚动盒子。 -- **分栏需要给两个可用的半格留出空间。** 格被等分成两半,因此每一半都必须容得下不可收缩的部分:tab 条的固定部分——按 tab 条宽减去 chip 盒与填充条测得,即内边距、间隙以及该格绘制的每个控件(含它自己的 chrome,所以右上格要求更多)——加上一枚最小尺寸的 chip——`.tab` 在 content-box 上声明 `min-width: 80px`,所以它的足印是 80px 加 10px + 10px 内边距,即 100px,从已渲染 chip 的计算样式读取(读不到时用样式表数值);两半之间的分隔条取其渲染厚度(0——它的细线画在接缝上、不占布局空间,因此正文自己画的分隔线能不断线地穿过接缝)。纵向分栏只由边缘落下产生,它要求每一半容得下 tab 条(34px)加 48px 正文:正文自留的 12px 内边距内一行 13px、行高 1.6 的次级文字——格的正文容器本身没有内边距,tab 的正文直接贴到 tab 条底边和格的边缘,由自己留白。`geometry.ts` 里的 `halvesFit` 是算术;`measure.ts` 在每次提交后与停靠面尺寸变化时读取矩形,因为布局状态只携带比例、从不携带像素,引擎的 planner 也保持如此。没有空间的格保留分栏控件,以 `splitPaneNarrow` 禁用(开启 `hideSplitWhenBlocked` 时改为隐藏),并且在该轴上不提供边缘落区(松手就不是移动)。开启 `hideSplitWhenBlocked` 时,分栏控件自己的占位——它的盒子加 tab 条的间隙——不计入固定部分:隐藏控件让 tab 条卸下的恰是这份占位,把它算进去的读数会随控件的可见性来回翻转、无限重渲染;不计入也正是被询问的那一半会承载的量,因为窄到无法分栏的一半会隐藏自己的控件。用户随后拖窄的格——通过拖动分隔条或嵌入方的列——会保持原尺寸:规则只决定它的下一次分栏。 +- **分栏需要给两个可用的半格留出空间。** 格被等分成两半,因此每一半都必须容得下不可收缩的部分:tab 条的固定部分——按 tab 条宽减去 chip 盒与填充条测得,即内边距、间隙以及该格绘制的每个控件(含它自己的 chrome,所以右上格要求更多)——加上一枚最小尺寸的 chip——`.tab` 在 content-box 上声明 `min-width: 80px`,所以它的足印是 80px 加 10px + 10px 内边距,即 100px,从已渲染 chip 的计算样式读取(读不到时用样式表数值);两半之间的分隔条取其渲染厚度(0——它的细线画在接缝上、不占布局空间,因此正文自己画的分隔线能不断线地穿过接缝)。纵向分栏只由边缘落下产生,它要求每一半容得下 tab 条(34px)加 48px 正文:正文自留的 12px 内边距内一行 13px、行高 1.6 的次级文字——格的正文容器本身没有内边距,tab 的正文直接贴到 tab 条底边和格的边缘,由自己留白。`geometry.ts` 里的 `halvesFit` 是算术;`measure.ts` 在停靠布局或分栏策略变化时读取矩形,也会响应停靠面、格和 tab 条各盒子的尺寸通知。嵌入方调整列宽时,不必在它的渲染提交中另测一次。没有空间的格保留分栏控件,以 `splitPaneNarrow` 禁用(开启 `hideSplitWhenBlocked` 时改为隐藏),并且在该轴上不提供边缘落区(松手就不是移动)。开启 `hideSplitWhenBlocked` 时,分栏控件自己的占位——它的盒子加 tab 条的间隙——不计入固定部分:隐藏控件让 tab 条卸下的恰是这份占位,把它算进去的读数会随控件的可见性来回翻转、无限重渲染;不计入也正是被询问的那一半会承载的量,因为窄到无法分栏的一半会隐藏自己的控件。用户随后拖窄的格——通过拖动分隔条或嵌入方的列——会保持原尺寸:规则只决定它的下一次分栏。 - **焦点落在 click 而不是按下。** 在 `pointerdown` 与第一次 `pointermove` 之间的状态变化会重建被按下的子树,而被替换的元素会取消指针。这也避免拖动先记录一条多余的焦点操作。chip、标签条各控件以及嵌入方 chrome 上的 click 都止于标签条:它们各自上报的意图已决定了活动格,或本就是嵌入方自己的事,所以格自身的点击聚焦不再多记一条。浮动面板的抓手与角柄同样通过手势上报——原地松开的按下是一次 click,抬起面板;真正的拖动只记录移动或缩放,由该操作自己抬起面板——而按在面板主体上则直接抬起它。点击本已活动的格、点击或按键选中该格本已选中的 chip,或按下本已活动且在最上层的面板,什么都不改变,也什么都不记录。 - **嵌套在可拖动 chip 里的控件要拦住自己的按下。** 否则按下会开始拖动、捕获指针,嵌套控件的 click 就永远落不下。 - **强调色用平台的强调 token,绝不用 `--dsw-alias-brand-primary`。** 本平台把 `brand-primary` 绑定到近黑(浅色)或近白(深色)的前景色,因此落点光标与落区提示都用 `--dsw-alias-brand-primary-new-colorprimary-new-color`,与轨迹视图一致;悬停的分隔条改用 caption 文字色,读起来是把手而不是高亮。浮窗不画边框——菜单同款阴影(`--dsw-elevation-prominent`)已勾出它的轮廓——活动浮窗也不加重边框:它本就在最上层、投同样的阴影;围它一圈更深的边框读起来像缺陷。 diff --git a/packages/client/ui-dockkit/src/components/DockSurface.tsx b/packages/client/ui-dockkit/src/components/DockSurface.tsx index 36ec07ca0b..72c4a3dffd 100644 --- a/packages/client/ui-dockkit/src/components/DockSurface.tsx +++ b/packages/client/ui-dockkit/src/components/DockSurface.tsx @@ -191,25 +191,31 @@ function Surface({ use(root) }, []) - // The room rule reads pixels, which the layout state does not carry: measure - // after every commit (a split, a divider drag, a closed tab all move panes) - // and whenever the surface itself is resized (the embedder's column dragged - // wider or narrower). A reading that changed nothing renders nothing. const remeasure = useCallback((): void => { withSurface((root) => { const next = measurePaneFits(root, hideSplitWhenBlocked) setFits(current => sameFits(current, next) ? current : next) }) }, [withSurface, hideSplitWhenBlocked]) - useLayoutEffect(() => { remeasure() }) - useEffect(() => { onRoom?.(fits) }, [fits, onRoom]) - useEffect(() => { + useLayoutEffect(() => { + if (typeof ResizeObserver === 'undefined') remeasure() + }) + useLayoutEffect(() => { const root = surface.current if (root === null || typeof ResizeObserver === 'undefined') return undefined - const observer = new ResizeObserver(() => { remeasure() }) + // A layout change can replace a selected tab's pane and strip. Measure its + // initial fit before paint; parent width changes need only the resize delivery. + remeasure() + const observer = new ResizeObserver(remeasure) observer.observe(root) + // A divider can resize a pane without resizing the surface. At fixed pane + // width, changing the strip controls takes space from its chips or its fill. + for (const box of root.querySelectorAll('[data-dockkit-pane], [data-dockkit-strip], [data-dockkit-strip-tabs], [data-dockkit-strip-fill]')) { + observer.observe(box, { box: 'border-box' }) + } return () => { observer.disconnect() } - }, [remeasure]) + }, [remeasure, state, canSplit]) + useEffect(() => { onRoom?.(fits) }, [fits, onRoom]) /** Why a pane cannot split right now: the budget first, then its own width. */ const splitBlock = (paneId: PaneId): SplitBlock | undefined => { diff --git a/packages/client/ui-dockkit/src/components/TabTitle.tsx b/packages/client/ui-dockkit/src/components/TabTitle.tsx index 679a27da02..477afa0f69 100644 --- a/packages/client/ui-dockkit/src/components/TabTitle.tsx +++ b/packages/client/ui-dockkit/src/components/TabTitle.tsx @@ -1,37 +1,8 @@ -/** - * A chip's title: one line, clipped at the chip's inset, never ellipsized. - * While the text is wider than its box the span carries - * `data-dockkit-tab-clipped`, and the stylesheet fades the text out at the - * clipped edge in place of an ellipsis. Written to the DOM directly rather - * than through state: a reading changes nothing that renders, only how the - * stylesheet paints it. Re-read after every commit (the text may have - * changed) and whenever the span's box resizes (the chip shrank or grew). - */ -import { useLayoutEffect, useRef } from 'react' +/** Title content shared by strip chips and floating-panel headers. */ import type { ReactNode } from 'react' import css from './dockkit.module.css' -/** Set or clear the span's `data-dockkit-tab-clipped` from its current geometry. */ -function markClipped(element: HTMLElement): void { - // Sub-pixel widths: the text counts as clipped past one whole pixel. - if (element.scrollWidth > element.clientWidth + 1) element.dataset.dockkitTabClipped = '' - else delete element.dataset.dockkitTabClipped -} - -/** The title span of a strip chip or a floating panel's header chip. */ +/** The chip stylesheet fades the trailing edge without measuring the title. */ export function TabTitle({ children }: { readonly children: ReactNode }): ReactNode { - const span = useRef(null) - useLayoutEffect(() => { - /* v8 ignore next -- the span is rendered unconditionally. */ - if (span.current !== null) markClipped(span.current) - }) - useLayoutEffect(() => { - const element = span.current - /* v8 ignore next -- the span is rendered unconditionally. */ - if (element === null || typeof ResizeObserver === 'undefined') return undefined - const observer = new ResizeObserver(() => { markClipped(element) }) - observer.observe(element) - return () => { observer.disconnect() } - }, []) - return {children} + return {children} } diff --git a/packages/client/ui-dockkit/src/components/dockkit.module.css b/packages/client/ui-dockkit/src/components/dockkit.module.css index 4499d879c5..51f2ba58a8 100644 --- a/packages/client/ui-dockkit/src/components/dockkit.module.css +++ b/packages/client/ui-dockkit/src/components/dockkit.module.css @@ -377,11 +377,8 @@ centres on the text's line rather than sitting on its baseline and keeps one distance from it. The clip is horizontal in intent; the line box must hold the descenders it would otherwise cut, hence a line-height above the - chip's own 1. No ellipsis: a title wider than its box (`TabTitle` sets - `data-dockkit-tab-clipped`) fades out over its last 16px instead. A mask on - the title rather than a painted gradient: the chip's fill is bare, - translucent hover, or the active tag colour, and a mask matches every one - without naming it. */ + chip's own 1. Only the last 16px of the title box fade, whether or not + the text overflows. A mask keeps the chip's fill visible underneath. */ .tabTitle { display: flex; flex: 1 1 auto; @@ -390,25 +387,20 @@ min-width: 0; overflow: hidden; line-height: 1.4; -} - -.tabTitle[data-dockkit-tab-clipped] { mask-image: linear-gradient(to right, black calc(100% - 16px), transparent); } /* While the close shows, the title is gone under the close's circle and fades out over the 16px before it: the circle spans the chip's last 24px and the title ends 10px inside the chip, so the title's last 14px are under it. - Later than the clipped mask, so a clipped chip showing its close fades - under the close. A floating panel's header chip has no close, so it keeps - the clipped mask alone. */ -.tab:not(.floatTitle):focus-within .tabTitle, -.tabActive .tabTitle { + Quiet and floating titles have no overlaid close. */ +.tab:not(.floatTitle, .tabQuiet):focus-within .tabTitle, +.tabActive:not(.tabQuiet) .tabTitle { mask-image: linear-gradient(to right, black calc(100% - 30px), transparent calc(100% - 14px)); } @media (hover: hover) { - .tab:not(.floatTitle):hover .tabTitle { + .tab:not(.floatTitle, .tabQuiet):hover .tabTitle { mask-image: linear-gradient(to right, black calc(100% - 30px), transparent calc(100% - 14px)); } } @@ -493,7 +485,7 @@ /* A pane's lone unclosable chip is a label, not a choice: no tab, no hover fill — the primary ink on the pane's own ground. Its title never - yields to a close control, so it keeps the clipped fade alone. */ + yields to a close control, so it keeps the ordinary title fade. */ .tab.tabQuiet { color: var(--dsw-alias-label-primary); background: transparent; @@ -508,21 +500,6 @@ } } -.tab.tabQuiet .tabTitle, -.tab.tabQuiet:focus-within .tabTitle { - mask-image: none; -} - -@media (hover: hover) { - .tab.tabQuiet:hover .tabTitle { - mask-image: none; - } -} - -.tab.tabQuiet .tabTitle[data-dockkit-tab-clipped] { - mask-image: linear-gradient(to right, black calc(100% - 16px), transparent); -} - .tabDragging { opacity: 0.5; } diff --git a/packages/client/ui-dockkit/tests/components.client.spec.tsx b/packages/client/ui-dockkit/tests/components.client.spec.tsx index 2954c76afb..8b3cdb9daa 100644 --- a/packages/client/ui-dockkit/tests/components.client.spec.tsx +++ b/packages/client/ui-dockkit/tests/components.client.spec.tsx @@ -19,6 +19,7 @@ import { applyOp } from '../src/engine/operations.ts' import { FLOAT_DEFAULT_SIZE, FLOAT_MIN_SIZE } from '../src/engine/constraints.ts' import { floatRectAt } from '../src/engine/geometry.ts' import { DockSurface, type DockSurfaceProps } from '../src/components/DockSurface.tsx' +import { TabTitle } from '../src/components/TabTitle.tsx' import type { TabMenuExtras } from '../src/contract/adapter.ts' import { FloatLayer, type FloatLayerProps } from '../src/components/FloatLayer.tsx' import { dockPaneIds, getPane } from '../src/engine/tree.ts' @@ -574,51 +575,14 @@ describe('DockSurface', () => { } }) - it('marks a chip title clipped while its text is wider than its box, re-reading on resize', () => { - class FakeResizeObserver implements ResizeObserver { - static readonly all: FakeResizeObserver[] = [] - readonly observe = vi.fn() - readonly unobserve = vi.fn() - readonly disconnect = vi.fn() - constructor(private readonly callback: ResizeObserverCallback) { - FakeResizeObserver.all.push(this) - } - - fire(): void { - this.callback([], this) - } - } - vi.stubGlobal('ResizeObserver', FakeResizeObserver) - let clientWidth = 200 - const descriptors = ['scrollWidth', 'clientWidth'].map(name => - [name, Object.getOwnPropertyDescriptor(Element.prototype, name)] as const) - const title = (element: Element): boolean => element.hasAttribute('data-dockkit-tab-title') - Object.defineProperty(Element.prototype, 'scrollWidth', { configurable: true, get(this: Element) { return title(this) ? 120 : 0 } }) - Object.defineProperty(Element.prototype, 'clientWidth', { configurable: true, get(this: Element) { return title(this) ? clientWidth : 0 } }) - try { - const controller = seededController() - const { unmount } = renderSurface(controller, spyIntents()) - const span = document.querySelector('[data-dockkit-tab-title]') - if (span === null) throw new Error('expected a chip title') - const observer = FakeResizeObserver.all.find(candidate => candidate.observe.mock.calls.some(([target]) => target === span)) - if (observer === undefined) throw new Error('expected the title to observe its own size') - expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(false) - // The chip narrowed under the text. - clientWidth = 80 - act(() => { observer.fire() }) - expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(true) - clientWidth = 200 - act(() => { observer.fire() }) - expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(false) - unmount() - expect(observer.disconnect).toHaveBeenCalledTimes(1) - } finally { - for (const [name, descriptor] of descriptors) { - if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name) - else Object.defineProperty(Element.prototype, name, descriptor) - } - vi.unstubAllGlobals() - } + it('renders and renames a chip title without querying its width', () => { + const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get') + const clientWidth = vi.spyOn(Element.prototype, 'clientWidth', 'get') + const view = render(Files) + view.rerender(A long renamed file.ts) + expect(view.getByText('A long renamed file.ts').hasAttribute('data-dockkit-tab-title')).toBe(true) + expect(scrollWidth).not.toHaveBeenCalled() + expect(clientWidth).not.toHaveBeenCalled() }) it('asks for the seeded tab from the strip\'s add control, naming the pane and nothing else', () => { diff --git a/packages/client/ui-dockkit/tests/split-room.client.spec.tsx b/packages/client/ui-dockkit/tests/split-room.client.spec.tsx new file mode 100644 index 0000000000..ead65d6349 --- /dev/null +++ b/packages/client/ui-dockkit/tests/split-room.client.spec.tsx @@ -0,0 +1,93 @@ +// @vitest-environment jsdom +/** Split availability in the horizontal layout used by the right sidebar. */ +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { DockLayout } from '../src/components/DockSurface.tsx' +import { seededController, TEST_LABELS } from './fixtures.client.ts' + +afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) + +/** Deliver only size notifications for the given box, as opposed to a window resize. */ +function observeSizes() { + const observers = new Set() + class Observer { + readonly boxes = new Set() + constructor(readonly notify: () => void) { observers.add(this) } + observe(box: Element): void { this.boxes.add(box) } + disconnect(): void { observers.delete(this) } + } + vi.stubGlobal('ResizeObserver', Observer) + return (box: Element) => { + act(() => { + for (const observer of observers) if (observer.boxes.has(box)) observer.notify() + }) + } +} + +function panel() { + const controller = seededController() + controller.setExpanded(true) + const onRoom = vi.fn() + const paneReads = vi.fn() + let width = 300 + let fixed = 80 + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (this.hasAttribute('data-dockkit-pane')) { paneReads(); return new DOMRect(0, 0, width, 600) } + if (this.hasAttribute('data-dockkit-strip')) return new DOMRect(0, 0, width, 38) + if (this.hasAttribute('data-dockkit-strip-tabs')) return new DOMRect(0, 0, 100, 28) + if (this.hasAttribute('data-dockkit-strip-fill')) return new DOMRect(0, 0, width - fixed - 100, 0) + return new DOMRect() + }) + const tree = () =>
+
{tab.title}
} renderTabTitle={tab => {tab.title}} + chrome={} onRoom={onRoom} /> +
+ const view = render(tree()) + return { + controller, paneReads, onRoom, + box: (selector: string) => view.container.querySelector(selector)!, + blocked: () => view.getByRole('button', { name: TEST_LABELS.splitPane }).hasAttribute('disabled'), + redraw: (size: number, controls = fixed) => { width = size; fixed = controls; view.rerender(tree()) }, + } +} + +it('measures the mounted pane immediately but not on width-only React commits', () => { + const resized = observeSizes() + const h = panel() + expect(h.blocked()).toBe(true) + h.paneReads.mockClear() + h.redraw(450) + h.redraw(500) + expect(h.paneReads).not.toHaveBeenCalled() + resized(h.box('[data-dockkit-surface]')) + expect(h.blocked()).toBe(false) + expect(h.onRoom).toHaveBeenLastCalledWith(new Map([[h.controller.getSnapshot().state.rootId, { row: true, column: true }]])) +}) + +it('tracks changing strip controls at fixed pane width, including after the selected tab replaces its strip', () => { + const resized = observeSizes() + const h = panel() + h.redraw(500) + resized(h.box('[data-dockkit-surface]')) + expect(h.blocked()).toBe(false) + const oldFill = h.box('[data-dockkit-strip-fill]') + h.controller.openContent({ kind: 'file', contentId: 'file:a', title: 'A' }) + h.redraw(500, 180) + expect(h.blocked()).toBe(true) + const fill = h.box('[data-dockkit-strip-fill]') + expect(fill).not.toBe(oldFill) + h.redraw(500, 80) + resized(fill) + expect(h.blocked()).toBe(false) +}) + +it('keeps commit-time measurements when size observation is unavailable', () => { + vi.stubGlobal('ResizeObserver', undefined) + const h = panel() + expect(h.blocked()).toBe(true) + h.redraw(500) + expect(h.blocked()).toBe(false) + h.redraw(500, 180) + expect(h.blocked()).toBe(true) +}) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index fc75758078..582d7bc76d 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: b4c2e8c1f7ab4de5 - zh: 5dd0e14aa5f9d334 + en: f4537e50ab2086e2 + zh: abff90e56f102612 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: en: a11207241d0606e8 zh: 6e4f3fb27527f5b6 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 3e384a3eea..26dc990c97 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -61,7 +61,7 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPane({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.pane` slot; the invoking button's `data-model-menu-pane` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail panes share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu exposes a detail pane as a group named by `title`; the pane places its own initial focus, and focus otherwise stays on the menu surface. Escape returns focus to the invoking row; Tab closes a detail pane without activating its switch. +The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Render each interactive entry as a `button` with role `menuitem`, `menuitemradio`, or `switch`; Arrow keys and Tab reach only those rows. Entries call `openPane({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.pane` slot; the invoking button's `data-model-menu-pane` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail panes share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu exposes a detail pane as a group named by `title`; the pane places its own initial focus, and focus otherwise stays on the menu surface. Escape returns focus to the invoking row; Tab closes a detail pane without activating its switch. ----- diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index c30111f669..5542cf5bee 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -61,7 +61,7 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPane({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.pane` 的内容;入口按钮的 `data-model-menu-pane` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级面板共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单把二级面板呈现为以 `title` 命名的分组;面板自行设置初始焦点,未设置时焦点停留在菜单容器上。Escape 将焦点还给入口行;Tab 关闭二级面板而不激活开关。 +会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。每个可交互的贡献项都应渲染为 `button`,role 取 `menuitem`、`menuitemradio` 或 `switch`;方向键与 Tab 只会到达这些行。贡献项调用 `openPane({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.pane` 的内容;入口按钮的 `data-model-menu-pane` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级面板共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单把二级面板呈现为以 `title` 命名的分组;面板自行设置初始焦点,未设置时焦点停留在菜单容器上。Escape 将焦点还给入口行;Tab 关闭二级面板而不激活开关。 ----- diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 6cd67bdcc4..fa6b304920 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -482,8 +482,18 @@ export function ModelSelect( onKeyDown={onRootKeyDown} onBlur={onBlur} onMouseDown={(event) => { - // WebKit blurs a focused row before click unless the button's mousedown keeps focus. - if (event.target instanceof Element && event.target.closest('button') !== null) event.preventDefault() + // WebKit blurs a focused row before click unless the button's mousedown + // keeps focus. Pressing non-focusable card content (a provider heading, + // padding, status text) would move focus to the body and close the card + // through onBlur; other focusable controls, which plugin options may + // render, keep their default focus, and a detail pane keeps the default + // so its prose stays selectable. + const { target } = event + if (target instanceof Element && ( + target.closest('button') !== null + || (pane.kind !== 'detail' && menuRef.current?.contains(target) === true + && target.closest('a[href], input, select, textarea, [role="button"], [contenteditable], [tabindex]') === null) + )) event.preventDefault() }} > + return <>{extraOption} } if (name === 'conversation.input.model.pane') { const controls = owner as object as OwnerOf<'conversation.input.model.pane'> @@ -48,6 +48,8 @@ it('dispatches a keyed page and returns focus to its invoking summary on Escape' expect(screen.getByRole('group', { name: 'Fixture settings' })).toBeTruthy() fireEvent.blur(toggle, { relatedTarget: null }) expect(screen.getByText('Fixture explanation')).toBeTruthy() + // Explanation text keeps its default press so it stays selectable. + expect(fireEvent.mouseDown(screen.getByText('Fixture explanation'))).toBe(true) fireEvent.keyDown(toggle, { key: 'Escape' }) expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Fixture settings' })) expect(screen.queryByRole('switch')).toBeNull() @@ -86,6 +88,23 @@ it.each([false, true])('closes a detail pane on Tab without changing its setting expect(change).not.toHaveBeenCalled() }) +it('keeps the default press on focusable plugin options that are not buttons', () => { + const { trigger } = setup(true, <> +
Tabbable option
+ Fixture link + Plain option text + ) + const tabbable = screen.getByTestId('tabbable') + // true = default kept, so the browser can move focus to the control. + expect(fireEvent.mouseDown(screen.getByText('Tabbable option'))).toBe(true) + expect(fireEvent.mouseDown(screen.getByRole('link', { name: 'Fixture link' }))).toBe(true) + // Non-focusable option content still keeps the current focus. + expect(fireEvent.mouseDown(screen.getByText('Plain option text'))).toBe(false) + act(() => { tabbable.focus() }) + expect(document.activeElement).toBe(tabbable) + expect(trigger.getAttribute('aria-expanded')).toBe('true') +}) + it('keeps the baseline model-save lock on both summary and detail controls', () => { const { directory } = setup() act(() => { directory.update((state) => { state.pending = { provider: 'fixture', model: 'fixture' } }) }) diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index d9dea25c57..438f964611 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -474,8 +474,9 @@ describe('ModelSelect reasoning effort', () => { expect(menu.style.left).toBe('') expect(menu.style.top).toBe('') expect(measure).not.toHaveBeenCalled() - // Interactions inside the trigger subtree or the portaled card stay open. - expect(fireEvent.mouseDown(menu)).toBe(true) + // Interactions inside the trigger subtree or the portaled card stay open; + // presses on the card keep focus where it is. + expect(fireEvent.mouseDown(menu)).toBe(false) expect(fireEvent.mouseDown(trigger)).toBe(false) fireEvent.blur(trigger, { relatedTarget: menu }) expect(screen.getByRole('menu')).toBeTruthy() @@ -593,6 +594,23 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ })) }) + it('keeps focus and the card open when non-focusable model pane content is pressed', () => { + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + const search = screen.getByRole('searchbox') + const heading = document.querySelector('[data-menu-group-heading]')! + // false = preventDefault ran, so the browser keeps focus where it was. + expect(fireEvent.mouseDown(heading)).toBe(false) + expect(fireEvent.mouseDown(screen.getAllByRole('menu')[0]!)).toBe(false) + // Text inputs keep their default so the caret can still be placed. + expect(fireEvent.mouseDown(search)).toBe(true) + expect(screen.getAllByRole('menu').length).toBeGreaterThan(0) + }) + it('↑↓ walk the rows of the shown pane, wrapping, and stay open', () => { mountOpen() // The trigger holds focus while the menu opens: the first forward step diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml index 9eebb14d6c..708a107bed 100644 --- a/packages/client/ui-session-panel/README.i18n.yaml +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -27,8 +27,8 @@ en: 27fdd4ec3c830299 zh: 0e70ac367e4176f8 /deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: - en: 78a25420651971d2 - zh: 8bd34e5624f08208 + en: a772926387782a82 + zh: 909966795290c52e /deepseek-ai-dsh-client-ui-session-panel/further-exploration: en: decfa1b92e25ec6c zh: 255c7862690a2f23 diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md index b9e600aedd..26b04ec3bf 100644 --- a/packages/client/ui-session-panel/README.md +++ b/packages/client/ui-session-panel/README.md @@ -83,7 +83,7 @@ A row whose single line clips its name or leaves out its owner, state, or measur
Implementation internals — click to expand -The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights. +The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`, which is readable only on the body, so the panel's stylesheet turns it there into a registered 0px or 1px step, `--dsh-session-panel-reserve-room`, that changes only when the reserve starts or stops covering the gutter; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The message flow does not inherit that step; crossing the docking threshold does not restyle its rows. The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights. While the docking preference is on, the probe carries `data-session-panel-reserve`, and a `:has()` rule in the panel's stylesheet sets `--dsh-chat-end-reserve` to 348px on the Conversation body, which then pads its scrollport's end by the missing gutter ([end reserve](../ui-conversation/README.md#end-reserve)). The probe's second term reads the largest reserve, not the padding, so its answer is the same before and after the transcript moves: the room the transcript makes never changes the decision that asked for it. diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md index 07c9732b39..3e29442737 100644 --- a/packages/client/ui-session-panel/README.zh.md +++ b/packages/client/ui-session-panel/README.zh.md @@ -83,7 +83,7 @@ kind: "package-reference"
实现内幕——点击展开 -面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。 +面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`,它只能在主体上读取,因此面板样式表在主体上把它转换为已注册的 0px 或 1px 阶跃值 `--dsh-session-panel-reserve-room`,只有预留开始或不再覆盖这段留白时才变化;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。消息流不继承这个阶跃值,因此跨过停靠阈值不会让消息行重算样式。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。 停靠偏好开启时,探针带有 `data-session-panel-reserve`,面板样式表中的一条 `:has()` 规则据此在 Conversation 主体上把 `--dsh-chat-end-reserve` 设为 348px,主体随即按所缺的留白给滚动容器的末端加上内边距([末端预留](../ui-conversation/README.zh.md#end-reserve))。探针的第二项读取的是最大预留而不是内边距,因此正文移动前后它的结果相同:正文让出的位置不会反过来改变提出让位的那项判断。 diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css index 9451d4b3c1..e66f108901 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -6,8 +6,10 @@ /* The docked panel's inline metrics: 40px clear of the transcript column, past its width handle, 8px from the end edge, and at least 300px wide. The - panel's width and the dock probe both derive from them, so the gutter that - docks the panel is exactly the one that holds its minimum width. */ + panel's width, the dock probe, and the reserve it asks the Conversation + body for all derive from them, so the gutter that docks the panel is + exactly the one that holds its minimum width. */ +:global([data-conversation-content]), .panel, .dockProbe { --panel-clear: 40px; @@ -15,6 +17,31 @@ --panel-min-width: 300px; } +/* Whether the Conversation body's largest end reserve covers the docked + panel's gutter: 1px when it does, otherwise 0. The body's maximum is not + inherited and changes on every resize, so this step derives on the body + itself, and as a registered length it reaches the dock probe only when the + decision flips. */ +@property --dsh-session-panel-reserve-room { + syntax: ''; + inherits: true; + initial-value: 0px; +} + +:global([data-conversation-content]) { + --dsh-session-panel-reserve-room: clamp( + 0px, + calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px), + 1px + ); +} + +/* The dock probe lives in the aside, not the message flow. Crossing its + threshold must not change the inherited style of every message. */ +:global([data-slot='conversation.chat.flow']) { + --dsh-session-panel-reserve-room: initial; +} + /* While the docking preference is on, the dock probe carries a mark, and the panel asks the Conversation body to keep the gutter that docks it: the three metrics above, 348px. Where the gutter is narrower, the body @@ -22,7 +49,7 @@ (ui-conversation's end reserve) and makes no room when the start gutter cannot give it. */ :global([data-conversation-content]):has(.dockProbe[data-session-panel-reserve]) { - --dsh-chat-end-reserve: calc(40px + 8px + 300px); + --dsh-chat-end-reserve: calc(var(--panel-clear) + var(--panel-edge) + var(--panel-min-width)); } .panel { @@ -104,7 +131,7 @@ right: 0; width: max( calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px), - calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px) + var(--dsh-session-panel-reserve-room) ); max-width: 1px; height: 0; diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts index 0f494e5d1e..0502f0042d 100644 --- a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -31,10 +31,12 @@ const px = (value: string | undefined): number => { } describe('SessionPanel.module.css docking geometry', () => { - const metrics = declarationsOf('.panel, .dockProbe') + const metrics = declarationsOf(':global([data-conversation-content]), .panel, .dockProbe') const clear = px(metrics['--panel-clear']) const edge = px(metrics['--panel-edge']) const minWidth = px(metrics['--panel-min-width']) + /** The body's reserve step, evaluated: clamped to 0..1px. */ + const reserveRoom = (reserveMax: number): number => Math.min(1, Math.max(0, (reserveMax - clear - edge - minWidth) * 10000000 + 1)) it('derives the docked width and the dock probe from one set of metrics', () => { expect([clear, edge, minWidth]).toEqual([40, 8, 300]) @@ -46,15 +48,28 @@ describe('SessionPanel.module.css docking geometry', () => { const probe = declarationsOf('.dockProbe') expect(probe['width']).toBe( 'max(calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px),' - + ' calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px))', + + ' var(--dsh-session-panel-reserve-room))', ) expect(probe['max-width']).toBe('1px') }) + it('derives the reserve step on the Conversation body, where the non-inherited maximum is readable', () => { + expect(declarationsOf(':global([data-conversation-content])')).toEqual({ + '--dsh-session-panel-reserve-room': 'clamp(0px,' + + ' calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px),' + + ' 1px)', + }) + expect(declarationsOf(":global([data-slot='conversation.chat.flow'])")['--dsh-session-panel-reserve-room']).toBe('initial') + // The aside inherits the computed step when it flips; the message rows keep the initial value. + expect(css.replace(/\s+/g, ' ')).toContain( + "@property --dsh-session-panel-reserve-room { syntax: ''; inherits: true; initial-value: 0px; }", + ) + }) + it('makes the probe 1px wide exactly from the gutter that holds the panel at its minimum width', () => { // The declarations above, evaluated: a width below 0 is used as 0, and max-width caps the probe at 1px. const probeWidth = (gutter: number, reserveMax = 0): number => - Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, (reserveMax - clear - edge - minWidth) * 10000000 + 1)) + Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, reserveRoom(reserveMax))) const dockedWidth = (gutter: number): number => Math.min(360, Math.max(minWidth, gutter - clear - edge)) expect([probeWidth(0), probeWidth(347), probeWidth(347.5), probeWidth(348), probeWidth(900)]).toEqual([0, 0, 0.5, 1, 1]) // At the first gutter that docks, the panel is at its minimum width and keeps both clearances. @@ -65,7 +80,7 @@ describe('SessionPanel.module.css docking geometry', () => { it('gives the probe room as well from the largest end reserve that covers the gutter, whatever the gutter is', () => { const probeWidth = (gutter: number, reserveMax: number): number => - Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, (reserveMax - clear - edge - minWidth) * 10000000 + 1)) + Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, reserveRoom(reserveMax))) // A 260px gutter holds no panel, and the transcript can leave 348px: room. This term is a step at 348px, as the // body's end inset is, so the probe has room exactly where the body makes it. expect([probeWidth(260, 347), probeWidth(260, 347.96), probeWidth(260, 348), probeWidth(260, 900)]).toEqual([0, 0, 1, 1]) @@ -77,8 +92,7 @@ describe('SessionPanel.module.css docking geometry', () => { it('asks the Conversation body for exactly the gutter that docks the panel while the probe carries the mark', () => { const request = declarationsOf(':global([data-conversation-content]):has(.dockProbe[data-session-panel-reserve])') - expect(request).toEqual({ '--dsh-chat-end-reserve': 'calc(40px + 8px + 300px)' }) - expect(40 + 8 + 300).toBe(clear + edge + minWidth) + expect(request).toEqual({ '--dsh-chat-end-reserve': 'calc(var(--panel-clear) + var(--panel-edge) + var(--panel-min-width))' }) }) it('keeps the probe out of sight, out of the layout flow, and away from the pointer', () => { diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 33de787b77..525375e149 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -21,8 +21,8 @@ en: fa2cefbf8c4fdafe zh: 3a4689591b50f6ea /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 8331324ea4998b91 - zh: 029a13927dc5ee21 + en: ec4760c00d39902a + zh: f15acdefb2c72b4d /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index ebd3b7dead..6f65e051bf 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -55,7 +55,7 @@ Leaving the saved mask untouched preserves existing authentication. A saved cred An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. -The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the placeholder shows the endpoint the profile resolves to, the public endpoint for deepseek, else the `defaultBaseURL` the configurable-provider directory reports for a pi-ai catalog route), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. There is no provider-scoped reasoning-effort field: effort is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, input types, and, on a hand-declared pi-ai route, reasoning levels; unrelated model fields survive edits. +The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the placeholder shows the endpoint the profile resolves to, the public endpoint for deepseek, else the `defaultBaseURL` the configurable-provider directory reports for a pi-ai catalog route), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. There is no provider-scoped reasoning-effort field: effort is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, input types, and, on a pi-ai route, reasoning levels; unrelated model fields survive edits. The same fold edits the provider's `retryPolicy` for both families. **Retry policy** defaults to the inherited policy and names its mode; choosing **Transient errors** or **All errors** writes a user-layer policy. Transient mode edits the maximum retry count and the retried error codes, ticked from the choices the `retryableCodes` schema publishes, shown in words (for example **Rate limited** for `RATE_LIMIT`), plus any inherited or stored code outside them, shown verbatim. A third-party code is typed into **Custom error code** and added with **Add** or Enter, which never submits the card: surrounding whitespace is trimmed, case is kept, an empty entry is ignored, and a code already listed is selected instead of duplicated. An added code is selected in the draft only, stays listed after it is unchecked during the same edit, and appears again on reopening once saved; the last ticked code cannot be cleared, and ticking exactly the inherited codes keeps the field inherited; both modes edit the initial delay, maximum delay, and jitter ratio under a **Backoff** fold, which starts open only when the stored policy customizes backoff. Each empty field shows and keeps the inherited value, read from the composition layer, then the schema default. Apply is disabled while a field holds a value the adapter refuses, such as a fractional retry count, a delay that is not positive, or a jitter ratio above 1. The refusal appears below the fields, or above the card actions while the fold is closed. A stored policy without a mode shows the inherited mode, or the schema's first mode when none is inherited, and Apply saves that mode. Switching modes keeps only the fields the new mode declares. Clearing a field unsets it, so the inherited value applies again; choosing the default again removes the user-layer policy. @@ -63,9 +63,9 @@ The DeepSeek API card edits the `llm-deepseek` endpoint, credentials, retry poli Drag a model’s reorder handle to change its position within the provider, or focus the handle and use the up and down arrow keys. Apply saves the order; Cancel discards it. Each model keeps its settings, expanded options, and unfinished capacity text when moved. The full-row drag preview and reduced-motion-aware row animations share primitives with workspace reordering; before/after insertion markers follow the same style. Row spacing and the adjoining drop targets share one gap value so the space between rows accepts drops. -Expand **Customized settings → Model options** to edit each model. When the model row is narrow, the main row shows only the model ID; expand the row to view or edit its display name. Wider rows show both fields side by side. Focusing a display name expands its row and keeps it open until explicitly collapsed. Tab reaches the option and delete buttons before the display name at every width. Both provider families share the same row layout, labels, and icons: context window and max output tokens occupy two columns, and **Input types** occupies a separate row with **Text** and **Image** checkboxes. A row without an input declaration displays the installed model’s input types, then the provider default, then Text. Known pi-ai providers load their installed catalog without endpoint I/O; opening a row does not write an override. Explicit input selections take precedence, including text-only overrides of vision models. Checkbox edits save the selected types, with at least one type required. DeepSeek writes `inputModalities`; pi-ai writes `input`. Unchecking Image for DeepSeek also removes `imagePixelBudget` and `imageMaxBytes`, because the adapter rejects those limits without image input. Clearing the input field in `cordis.patch.yml` restores adapter inheritance; **Restore default models** resets the entire catalog override. Declare only input types the upstream model can actually process. +Expand **Customized settings → Model options** to edit each model. When the model row is narrow, the main row shows only the model ID; expand the row to view or edit its display name. Wider rows show both fields side by side. Focusing a display name expands its row and keeps it open until explicitly collapsed. Tab reaches the option and delete buttons before the display name at every width. Both provider families share the same row layout, labels, and icons: context window and max output tokens occupy two columns, and **Input types** occupies a separate row with **Text** and **Image** checkboxes. A row without an input declaration displays the installed model’s input types, then the provider default, then Text. Known pi-ai providers load their installed catalog without endpoint I/O; opening a row does not write an override. Explicit input selections take precedence, including text-only overrides of vision models. Checkbox edits save the selected types, with at least one type required. DeepSeek writes `inputModalities`; pi-ai writes `input`. Unchecking Image for DeepSeek also removes `imagePixelBudget` and `imageTargetBytes`, because the adapter rejects those limits without image input. Clearing the input field in `cordis.patch.yml` restores adapter inheritance; **Restore default models** resets the entire catalog override. Declare only input types the upstream model can actually process. -A model row on a hand-declared pi-ai route also edits its **Reasoning levels**, the `reasoningEfforts` the adapter already reads from `cordis.patch.yml`; the **?** beside the label explains the two columns. With the switch off the field is absent, so the model does not reason and the model picker offers no level; a stored `false` is kept until the switch is used. Turning it on always starts from rows for off, low, medium, and high; it does not restore levels removed earlier, and **Cancel** discards the edit instead. Each row pairs a level select — the keys `llm-pi-ai`'s configuration schema accepts in `reasoningEfforts`, read from the namespace schema like the protocol choices and today `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`, each usable once — with the **API value** sent for it, which starts as the level name; a field cleared while typing stores the level name and shows it once the field is left. Off only turns reasoning off, so its value field is disabled; a value already written for it in `cordis.patch.yml` is shown and kept. Changing a row's level resets a value still spelled as the old level; a custom value carries over only between two thinking levels, so changing a row to or from Off resets it. A stored key the schema does not list keeps its row and stays selectable there. Rows can be added and deleted and are saved in row order, while the model picker lists the levels in escalation order. The section refuses what the adapter refuses: no level besides Off — including a `reasoningEfforts:` left without a value, which shows the switch on with no rows — or a value that is missing on a level besides Off or empty on any level. A refused value marks its field invalid, and leaving that field fills in the level name. The rows keep no state of their own, so a model row reused after a deletion, a reset, or a fold shows only its own model. On a Gemini API route the level select offers only `minimal`, `low`, `medium`, and `high`, turning the switch on starts from low, medium, and high, and each value field is disabled and holds the level name, which changing a row's level keeps; the Gemini implementation accepts only those four names as values. A stored level, or a value other than its level name, blocks saving with a message under the rows, in the create card and in the editor alike; the editor checks inherited models as well once the protocol is Gemini. Routes served from the installed catalog and the DeepSeek API card keep the adapter's levels and show no reasoning control. +A model row on a pi-ai route, catalog or hand-declared, also edits its **Reasoning levels**, the `reasoningEfforts` the adapter already reads from `cordis.patch.yml`; the **?** beside the label explains the two columns. With the switch off the field is absent: a model the installed catalog describes keeps the catalog's levels, and any other model does not reason and the model picker offers it no level; a stored `false` is kept until the switch is used. Turning it on always starts from rows for off, low, medium, and high; it does not restore levels removed earlier, and **Cancel** discards the edit instead. Each row pairs a level select — the keys `llm-pi-ai`'s configuration schema accepts in `reasoningEfforts`, read from the namespace schema like the protocol choices and today `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`, each usable once — with the **API value** sent for it, which starts as the level name; a field cleared while typing stores the level name and shows it once the field is left. Off only turns reasoning off, so its value field is disabled; a value already written for it in `cordis.patch.yml` is shown and kept. Changing a row's level resets a value still spelled as the old level; a custom value carries over only between two thinking levels, so changing a row to or from Off resets it. A stored key the schema does not list keeps its row and stays selectable there. Rows can be added and deleted and are saved in row order, while the model picker lists the levels in escalation order. The section refuses what the adapter refuses: no level besides Off — including a `reasoningEfforts:` left without a value, which shows the switch on with no rows — or a value that is missing on a level besides Off or empty on any level. A refused value marks its field invalid, and leaving that field fills in the level name. The rows keep no state of their own, so a model row reused after a deletion, a reset, or a fold shows only its own model. On a route whose `api` names the Gemini API the level select offers only `minimal`, `low`, `medium`, and `high`, turning the switch on starts from low, medium, and high, and each value field is disabled and holds the level name, which changing a row's level keeps; the Gemini implementation accepts only those four names as values. A stored level, or a value other than its level name, blocks saving with a message under the rows, in the create card and in the editor alike; the editor checks inherited models as well once the protocol is Gemini. A catalog route normally stores no `api`; its rows then offer every level with an editable value, whichever protocol its models speak. The DeepSeek API card keeps the adapter's levels and shows no reasoning control. Empty pi-ai capacity fields display `1M` for the context window and `128K` for maximum output tokens. These hints use decimal K/M units; leaving the fields empty preserves adapter inheritance. Provider-level defaults can differ from the hints. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index e1b7dadd1f..880bf76686 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -55,7 +55,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 -收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(占位符显示 profile 解析出的端点,deepseek 即公共端点;没有时显示可配置提供商目录为 pi-ai 内置路由报告的 `defaultBaseURL`)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。这里没有提供商级的推理等级字段:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens`、输入类型,以及手工声明的 pi-ai 路由上的推理等级;无关的模型字段在编辑后仍会保留。 +收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(占位符显示 profile 解析出的端点,deepseek 即公共端点;没有时显示可配置提供商目录为 pi-ai 内置路由报告的 `defaultBaseURL`)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。这里没有提供商级的推理等级字段:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens`、输入类型,以及 pi-ai 路由上的推理等级;无关的模型字段在编辑后仍会保留。 同一折叠区还为两个家族编辑提供商的 `retryPolicy`。**重试策略**默认沿用继承的策略并显示其模式;选择**仅临时错误**或**所有错误**会写入用户层策略。临时错误模式编辑最大重试次数和要重试的错误码,错误码从 `retryableCodes` schema 发布的选项中勾选,选项以文字显示(例如 `RATE_LIMIT` 显示为**请求限流**),选项之外继承或已存储的错误码也会列出并原样显示。第三方错误码可在**自定义错误码**中输入,点击**添加**或按 Enter 加入,Enter 不会提交卡片:首尾空白会去除,大小写保留,空输入被忽略,已列出的错误码只会被勾选而不会重复添加。添加的错误码只在草稿中被勾选,本次编辑中取消勾选后仍保留在列表里,保存后重新打开会再次显示;最后一个勾选项不能取消,勾选的错误码与继承值完全相同时字段保持继承;两种模式都在**退避**折叠区中编辑初始延迟、最大延迟和抖动比例,只有已存储策略自定义了退避时该折叠区才默认展开。每个空字段显示并保留继承值,先取组合层的值,再取 schema 默认值。字段中有适配器会拒绝的值时,应用按钮不可用,例如小数重试次数、非正延迟或大于 1 的抖动比例。拒绝原因显示在字段下方;折叠区收起时显示在卡片操作按钮上方。未设置模式的已存储策略显示继承的模式,没有可继承的模式时显示 schema 中的第一个模式,应用时会保存该模式。切换模式时只保留新模式声明的字段。清空字段会取消该字段的设置,从而重新使用继承值;重新选择默认会移除用户层策略。 @@ -63,9 +63,9 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 拖动模型的排序手柄可调整它在当前提供商内的位置,也可以聚焦手柄后使用上下方向键。保存会保留顺序,取消会放弃修改。移动时,每个模型的参数、已展开选项和未完成的容量输入都会随模型保留。整行拖拽预览及遵循减少动态效果设置的行动画,与工作区排序共用基础组件;前后插入标记沿用相同样式。行距与相邻拖放区域共用同一个间距值,行间空白也可接收放置。 -展开**自定义设置 → 模型选项**编辑模型。模型行较窄时,主行仅显示模型 ID,展开模型行后可查看或编辑显示名称;宽度充足时,两个输入框并排显示。显示名称获得焦点时会展开该行,并保持展开,直到显式收起。所有宽度下,Tab 都先经过模型选项和删除按钮,再到显示名称。两个提供商家族共用相同的模型行布局、标签和图标:上下文窗口与最大输出 token 数分为两列,**输入类型**独占下一行,提供**文本**和**图片**复选框。未声明输入类型的模型行优先显示已安装模型的输入类型,其次是提供商默认值,最后回退为文本。已知 pi-ai 提供商会加载已安装目录,不向端点发送请求;打开模型行不会写入覆盖值。显式输入选择具有优先权,包括为视觉模型设置的仅文本覆盖。修改复选框会保存所选类型,且至少保留一种。DeepSeek 写入 `inputModalities`,pi-ai 写入 `input`。DeepSeek 取消勾选图片时,还会移除 `imagePixelBudget` 和 `imageMaxBytes`,因为适配器在没有图片输入时拒绝这些限制。在 `cordis.patch.yml` 中清除输入字段可恢复适配器继承;**恢复默认模型**会重置整个模型目录覆盖。仅声明上游模型实际能够处理的输入类型。 +展开**自定义设置 → 模型选项**编辑模型。模型行较窄时,主行仅显示模型 ID,展开模型行后可查看或编辑显示名称;宽度充足时,两个输入框并排显示。显示名称获得焦点时会展开该行,并保持展开,直到显式收起。所有宽度下,Tab 都先经过模型选项和删除按钮,再到显示名称。两个提供商家族共用相同的模型行布局、标签和图标:上下文窗口与最大输出 token 数分为两列,**输入类型**独占下一行,提供**文本**和**图片**复选框。未声明输入类型的模型行优先显示已安装模型的输入类型,其次是提供商默认值,最后回退为文本。已知 pi-ai 提供商会加载已安装目录,不向端点发送请求;打开模型行不会写入覆盖值。显式输入选择具有优先权,包括为视觉模型设置的仅文本覆盖。修改复选框会保存所选类型,且至少保留一种。DeepSeek 写入 `inputModalities`,pi-ai 写入 `input`。DeepSeek 取消勾选图片时,还会移除 `imagePixelBudget` 和 `imageTargetBytes`,因为适配器在没有图片输入时拒绝这些限制。在 `cordis.patch.yml` 中清除输入字段可恢复适配器继承;**恢复默认模型**会重置整个模型目录覆盖。仅声明上游模型实际能够处理的输入类型。 -手工声明的 pi-ai 路由上,模型行还会编辑**推理等级**,即适配器本来就从 `cordis.patch.yml` 读取的 `reasoningEfforts`;标签旁的 **?** 说明两列的含义。开关关闭时该字段不存在,模型不推理,模型选择器不提供任何档位;已存储的 `false` 在开关被操作前保持不变。打开开关总是从 off、low、medium 和 high 四行开始,不会恢复之前删掉的档位;要放弃修改请点**取消**。每行把一个档位选择框——可选值是 `llm-pi-ai` 配置 schema 允许作为 `reasoningEfforts` 键的档位,与协议选项一样从命名空间 schema 读取,目前为 `off`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`,每个档位只能用一次——与发送给它的 **API 参数值**配成一对,参数值初始为档位名;输入时清空的字段会存为档位名,离开字段后显示出来。Off 只表示关闭思考,因此它的参数值输入框是禁用的;`cordis.patch.yml` 中已为它写好的值会显示并保留。修改某行的档位时,仍是旧档位名的参数值会随之重置;自定义值只在两个思考档位之间保留,切到或切离 Off 都会重置。schema 未列出的已存键会保留自己的行,并可在该行中继续选择。行可以增删,并按行的顺序保存,模型选择器则按升级顺序列出档位。本节拒绝适配器会拒绝的配置:没有 Off 以外的档位(包括未写值的 `reasoningEfforts:`,此时开关显示为打开且没有任何行),或者 Off 以外的档位缺少参数值、任意档位的参数值为空字符串。被拒绝的值会把对应输入框标为无效,离开该输入框时会填入档位名。各行不保留自己的状态,因此删除、恢复默认或折叠之后被复用的模型行只显示它自己的模型。在 Gemini API 路由上,档位选择框只提供 `minimal`、`low`、`medium` 和 `high`,打开开关从 low、medium 和 high 三行开始,参数值输入框全部禁用并保持为档位名,修改某行档位时也随之改为新档位名;Gemini 实现只接受这四个名称作为参数值。已存储的超出范围的档位,或与档位名不同的参数值,会在行下方显示提示并阻止保存,新建卡片与编辑器都是如此;协议为 Gemini 时,编辑器也会检查继承的模型。走已安装目录的路由和 DeepSeek API 卡片沿用适配器的档位,不显示推理等级控件。 +pi-ai 路由上,无论走已安装目录还是手工声明,模型行还会编辑**推理等级**,即适配器本来就从 `cordis.patch.yml` 读取的 `reasoningEfforts`;标签旁的 **?** 说明两列的含义。开关关闭时该字段不存在:已安装目录中有的模型沿用目录的档位,其他模型不推理,模型选择器不为它提供任何档位;已存储的 `false` 在开关被操作前保持不变。打开开关总是从 off、low、medium 和 high 四行开始,不会恢复之前删掉的档位;要放弃修改请点**取消**。每行把一个档位选择框——可选值是 `llm-pi-ai` 配置 schema 允许作为 `reasoningEfforts` 键的档位,与协议选项一样从命名空间 schema 读取,目前为 `off`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`,每个档位只能用一次——与发送给它的 **API 参数值**配成一对,参数值初始为档位名;输入时清空的字段会存为档位名,离开字段后显示出来。Off 只表示关闭思考,因此它的参数值输入框是禁用的;`cordis.patch.yml` 中已为它写好的值会显示并保留。修改某行的档位时,仍是旧档位名的参数值会随之重置;自定义值只在两个思考档位之间保留,切到或切离 Off 都会重置。schema 未列出的已存键会保留自己的行,并可在该行中继续选择。行可以增删,并按行的顺序保存,模型选择器则按升级顺序列出档位。本节拒绝适配器会拒绝的配置:没有 Off 以外的档位(包括未写值的 `reasoningEfforts:`,此时开关显示为打开且没有任何行),或者 Off 以外的档位缺少参数值、任意档位的参数值为空字符串。被拒绝的值会把对应输入框标为无效,离开该输入框时会填入档位名。各行不保留自己的状态,因此删除、恢复默认或折叠之后被复用的模型行只显示它自己的模型。在 `api` 为 Gemini API 的路由上,档位选择框只提供 `minimal`、`low`、`medium` 和 `high`,打开开关从 low、medium 和 high 三行开始,参数值输入框全部禁用并保持为档位名,修改某行档位时也随之改为新档位名;Gemini 实现只接受这四个名称作为参数值。已存储的超出范围的档位,或与档位名不同的参数值,会在行下方显示提示并阻止保存,新建卡片与编辑器都是如此;协议为 Gemini 时,编辑器也会检查继承的模型。走已安装目录的路由通常不存储 `api`;此时无论其模型使用哪种协议,各行都提供全部档位且参数值可编辑。DeepSeek API 卡片沿用适配器的档位,不显示推理等级控件。 pi-ai 容量字段为空时,上下文窗口显示 `1M`,最大输出 token 数显示 `128K`。这些提示使用十进制 K/M 单位;保留空值会继续继承适配器配置。提供方级默认值可能与提示不同。 diff --git a/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx b/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx index a92e88ae36..2f9596235f 100644 --- a/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx +++ b/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx @@ -49,7 +49,7 @@ export function ModelInputTypes({ model, field, position, disabled, fallback, t, // DeepSeek rejects image request limits on a text-only model. if (field === 'inputModalities' && !nextSelected.includes('image')) { Reflect.deleteProperty(next, 'imagePixelBudget') - Reflect.deleteProperty(next, 'imageMaxBytes') + Reflect.deleteProperty(next, 'imageTargetBytes') } onChange(next) }} diff --git a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx index 7e7f2c1907..a7fedc6ff4 100644 --- a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx @@ -75,9 +75,8 @@ export interface ModelListEditorProps { /** Installed provider whose catalog supplies defaults without endpoint I/O. */ catalogProvider?: string | undefined /** - * Reasoning levels a hand-declared route's rows may declare in - * `reasoningEfforts`, in escalation order; absent or empty shows no - * reasoning control, leaving a catalog model's levels to the catalog. + * Reasoning levels the rows may declare in `reasoningEfforts`, in + * escalation order; absent or empty shows no reasoning control. */ reasoningLevels?: readonly string[] | undefined /** Whether the route's protocol accepts only {@link reasoningLevels}, each sent under its own name. */ diff --git a/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx b/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx index f798097710..6db89af722 100644 --- a/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx +++ b/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx @@ -1,4 +1,4 @@ -/** Reasoning-level declarations for a model on a hand-declared pi-ai route. */ +/** Reasoning-level declarations for a model on a pi-ai route. */ import { useState } from 'react' import type { ReactNode } from 'react' @@ -52,7 +52,7 @@ function readEfforts(model: DeepSeekModelDraft): Entries | undefined { function withEfforts(model: DeepSeekModelDraft, entries: Entries | undefined): DeepSeekModelDraft { const next = { ...model } if (entries === undefined) { - // Absent is how a hand-declared model says it does not reason. + // Absent keeps the installed catalog's levels; a model the catalog does not describe then does not reason. Reflect.deleteProperty(next, 'reasoningEfforts') return next } @@ -81,7 +81,7 @@ function outsideLevels(only: readonly string[], level: string, wire: unknown): b } /** - * Mirror the pi-ai refusals of a hand-declared `reasoningEfforts`, so a card + * Mirror the pi-ai refusals of a model's `reasoningEfforts`, so a card * names the row instead of failing at the write. * @param value - drafted `models` value, or `undefined` while inherited. * @param only - the levels the route's protocol accepts, each sent under its @@ -120,7 +120,7 @@ interface ModelReasoningEffortsProps { } /** - * Edit the `reasoningEfforts` a hand-declared pi-ai model offers: a switch, + * Edit the `reasoningEfforts` a pi-ai model offers: a switch, * then one row per level pairing the level with the value sent for it. Every * row is read from the model, so a reused instance shows its new model. * @param props - model declaration and row replacement action. diff --git a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx index 6dc2fb3b63..e8f6eb73a9 100644 --- a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx @@ -250,12 +250,12 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { // The model list is validated by the same per-row checker for both families, // so a bad row is named by its position rather than by a blanket message. - // Only a hand-declared pi-ai route's rows edit reasoning levels — the one - // model list with no installed catalog behind it — so only there are the - // levels read and the declarations checked. + // Every pi-ai route's rows edit reasoning levels, catalog and hand-declared + // alike: the adapter resolves a row's `reasoningEfforts` the same way on + // both, so the levels are read and the declarations checked for both. const schemaReasoningLevels = useMemo( - () => layout === 'pi-ai' && props.declared === true ? reasoningLevelChoices(namespace, schema) : [], - [layout, props.declared, namespace, schema], + () => layout === 'pi-ai' ? reasoningLevelChoices(namespace, schema) : [], + [layout, namespace, schema], ) // What the form currently shows, which is what an interrogation must ask and // what decides the protocol's own constraints: an edited-but-unsaved protocol. diff --git a/packages/client/ui-settings-models/src/client/store.ts b/packages/client/ui-settings-models/src/client/store.ts index 0877cd7da2..b1d5909a6e 100644 --- a/packages/client/ui-settings-models/src/client/store.ts +++ b/packages/client/ui-settings-models/src/client/store.ts @@ -147,7 +147,7 @@ export function protocolChoices( } /** - * The reasoning levels a hand-declared route's models may declare, read out of + * The reasoning levels a pi-ai route's models may declare, read out of * the owning namespace's own schema for the same reason as * {@link protocolChoices}: the levels the page offers and the keys the * adapter accepts in `reasoningEfforts` come from the same `Config`. diff --git a/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx b/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx index b8a37964e0..d95f43fd90 100644 --- a/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx @@ -45,12 +45,12 @@ describe.each(['inputModalities', 'input'] as const)('%s input types', (field) = it('removes DeepSeek image limits when images are unchecked', () => { const onChange = vi.fn() - const model = { id: 'vision', [field]: ['text', 'image'], description: 'kept', imagePixelBudget: 'low', imageMaxBytes: 12345 } + const model = { id: 'vision', [field]: ['text', 'image'], description: 'kept', imagePixelBudget: 'low', imageTargetBytes: 12345 } render( en[key]} onChange={onChange} />) fireEvent.click(screen.getByRole('checkbox', { name: en.modelInputImage })) expect(onChange).toHaveBeenCalledWith({ id: 'vision', description: 'kept', [field]: ['text'], - ...field === 'input' ? { imagePixelBudget: 'low', imageMaxBytes: 12345 } : {}, + ...field === 'input' ? { imagePixelBudget: 'low', imageTargetBytes: 12345 } : {}, }) expect(model[field]).toEqual(['text', 'image']) }) diff --git a/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx b/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx index a7a84026b4..9089c70f67 100644 --- a/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx @@ -1,5 +1,5 @@ // @vitest-environment jsdom -/** Reasoning levels of hand-declared pi-ai models: echo, level rows, API values, refusals, and placement. */ +/** Reasoning levels of pi-ai models: echo, level rows, API values, refusals, and placement. */ import { useState } from 'react' import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -325,10 +325,22 @@ describe('reasoning levels in the model list', () => { expect(writes.at(-1)).toEqual([{ id: 'b', reasoningEfforts: DEFAULTS }]) }) + it('edits a catalog route row', () => { + const writes: DeepSeekModelDraft[][] = [] + render( { writes.push(next) }} catalogProvider="openai" reasoningLevels={LEVELS} + probe={{ settingsNs: 'llm-pi-ai', provider: 'openai' }} + operations={operations} disabled={false} t={t} onBusyChange={() => {}} + />) + fireEvent.click(screen.getByRole('button', { name: `${en.modelAdvanced} 1` })) + fireEvent.click(toggle()) + expect(writes.at(-1)).toEqual([{ id: 'gpt-5', reasoningEfforts: DEFAULTS }]) + }) + it.each([ ['without a level list', undefined], ['with an empty level list', []], - ])('shows no reasoning control %s, leaving catalog rows to the installed catalog', (_label, reasoningLevels) => { + ])('shows no reasoning control %s', (_label, reasoningLevels) => { render( { .toContainEqual({ op: 'unset', path: ['providers', 'openai', 'models'] }) }) + it('declares reasoning levels on a catalog route model and stores them in its models list', async () => { + const { mutate } = await mountSection({ + providers: { openai: { apiKeyEnv: 'OPENAI_API_KEY', models: [{ id: 'gpt-5', name: 'GPT-5' }] } }, + }) + openEditor('openai') + expandModel(1) + // Switched off, the field is absent and the model keeps the installed catalog's levels. + const toggle = screen.getByRole('switch', { name: `${en.modelReasoning} 1` }) + expect(toggle.getAttribute('aria-checked')).toBe('false') + + fireEvent.click(toggle) + fireEvent.click(screen.getByText(en.apply)) + await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) }) + expect(firstMutate(mutate).ops).toEqual([{ + op: 'set', path: ['providers', 'openai', 'models'], + value: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: { off: null, low: 'low', medium: 'medium', high: 'high' } }], + }]) + }) }) describe('capacity spellings', () => { @@ -1228,11 +1246,11 @@ describe('hand-declared providers', () => { }) it.each([ - ['blocks a hand-declared route', true], - ['leaves a catalog route to the adapter', false], - ])('%s whose stored reasoning levels the adapter refuses', async (_label, declared) => { - // Only a hand-declared route's rows edit reasoning levels, so only there - // can the card name the row and offer the switch that repairs it. + ['a hand-declared route', true], + ['a catalog route', false], + ])('blocks %s whose stored reasoning levels the adapter refuses', async (_label, declared) => { + // The adapter refuses the same declarations on both kinds of route, and + // both edit them, so the card names the row and offers the switch that repairs it. await mountSection({ providers: { 'acme-gateway': { @@ -1244,9 +1262,8 @@ describe('hand-declared providers', () => { }) openEditor('acme-gateway') - const refusal = `${en.model} 1: ${en.modelReasoningNeedsLevel}` - expect(screen.queryByText(refusal) !== null).toBe(declared) - expect(buttonNamed(en.apply).disabled).toBe(declared) + expect(screen.getByText(`${en.model} 1: ${en.modelReasoningNeedsLevel}`)).toBeTruthy() + expect(buttonNamed(en.apply).disabled).toBe(true) }) it('retries only the key after the profile landed, and reports the provider on cancel', async () => { diff --git a/packages/client/ui-sidebar-right/README.i18n.yaml b/packages/client/ui-sidebar-right/README.i18n.yaml index 6d7698bd31..da608e47a8 100644 --- a/packages/client/ui-sidebar-right/README.i18n.yaml +++ b/packages/client/ui-sidebar-right/README.i18n.yaml @@ -18,8 +18,8 @@ en: 3b007cc4d2d89c60 zh: 74d9795c6392ad74 /deepseek-ai-dsh-client-ui-sidebar-right/presentations: - en: 5024c4e5fe5dfd2e - zh: 535a7f585e1bcd97 + en: aa03c00f30ef88f7 + zh: b9b2cbe86775a864 /deepseek-ai-dsh-client-ui-sidebar-right/the-expand-button: en: ca7a1966ad9cef31 zh: b9a7a967a14f067e diff --git a/packages/client/ui-sidebar-right/README.md b/packages/client/ui-sidebar-right/README.md index 8b0b721eb5..17af9ab49b 100644 --- a/packages/client/ui-sidebar-right/README.md +++ b/packages/client/ui-sidebar-right/README.md @@ -47,7 +47,7 @@ With a coarse pointer, a disabled split button is hidden, whether blocked by ins In Windows Electron, `html[data-windows-titlebar]` keeps fullscreen panels below the caption and to the right of the expanded sidebar. The frame's `--dsh-windows-sidebar-width` supplies that inset and maximum width; `--dsh-windows-content-radius` supplies the top-left radius. Only fullscreen panels clip overflow for that corner. -The seat reports presentation through `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()`; the frame does not inject this package. Switching fullscreen on a wide viewport leaves the center width unchanged, and the width handle appears only in expanded normal mode. Independent floating panels and `float`/`dock` operations remain available. +The seat reports presentation through `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()`; the frame does not inject this package. Switching fullscreen on a wide viewport leaves the center width unchanged, and the width handle appears only in expanded normal mode. After the panel opens, dragging changes its width without sending an inherited slide distance to tab contents. Closing moves each docked item by the full panel width, even in a split layout. Independent floating panels and `float`/`dock` operations remain available. The panel has no header row. Its two controls — the presentation switch and the collapse button — ride the kit's chrome seat at the far end of the top-right pane's tab strip, so the strip is the panel's whole top edge. Each strip reads, left to right: the tab capsules with close controls where allowed, the add control (drawn only while that pane holds no guide tab; it opens the guide there through `ctx.sidebarRight.openTab`), the pane's split control, and in the top-right pane the two panel controls. Only the chips give way in a narrow pane; the controls after them never shrink or clip. diff --git a/packages/client/ui-sidebar-right/README.zh.md b/packages/client/ui-sidebar-right/README.zh.md index b821383e49..fbdd30a557 100644 --- a/packages/client/ui-sidebar-right/README.zh.md +++ b/packages/client/ui-sidebar-right/README.zh.md @@ -47,7 +47,7 @@ kind: "package-reference" 在 Windows Electron 中,`html[data-windows-titlebar]` 让全屏面板保持在顶栏下方及展开侧栏的右侧。框架的 `--dsh-windows-sidebar-width` 提供该缩进及最大宽度;`--dsh-windows-content-radius` 提供左上圆角。仅全屏面板为该圆角裁剪溢出内容。 -席位通过 `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()` 报告呈现,框架不注入本包。宽屏切换全屏不改变中栏宽度;宽度拖拽区只在普通展开态显示。独立浮窗及 `float`/`dock` 操作保持可用。 +席位通过 `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()` 报告呈现,框架不注入本包。宽屏切换全屏不改变中栏宽度;宽度拖拽区只在普通展开态显示。面板展开后,拖动只更新面板宽度,不向标签页内容传递滑动距离。即使分栏,收起时每个停靠项也按整个面板的宽度滑动。独立浮窗及 `float`/`dock` 操作保持可用。 面板没有标题行。它的两个控件——形态切换与折叠按钮——搭在套件 chrome 席位上,位于右上格 tab 条的最末端,因此 tab 条就是面板的整条上边。每条 tab 条从左到右读作:在允许时带关闭按钮的 tab 胶囊,添加控件(只在该格没有引导 tab 时绘制;它通过 `ctx.sidebarRight.openTab` 在该格打开引导页),该格的分栏控件,以及右上格里的两个面板控件。窄格里只有 chip 让位;其后的控件从不收缩或被裁切。 diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 94d08c4f24..c1d72cec1c 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -28,7 +28,14 @@ display: none; } +@property --dsh-sidebar-right-panel-width { + syntax: ''; + inherits: false; + initial-value: 0px; +} + .panel { + width: var(--dsh-sidebar-right-panel-width); --dsh-dockkit-dock-layer: 10; --dsh-dockkit-float-layer: 60; position: absolute; @@ -47,6 +54,18 @@ pointer-events: none; } +/* A split pane slides the full panel width, not its own width. An open panel + needs this inherited distance only for items mounting during an animated opening. */ +.panel:not([data-sidebar-right-open]) { + --dsh-sidebar-width: var(--dsh-sidebar-right-panel-width); +} + +@media (prefers-reduced-motion: no-preference) { + .panel[data-sidebar-right-opening] { + --dsh-sidebar-width: var(--dsh-sidebar-right-panel-width); + } +} + /* Only docked Grid items slide. Their common ancestor remains untransformed and without a stacking context, so fixed floating children escape. */ .panel :global([data-dockkit-host='dock']), diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index 8dd62420fe..deac734d53 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -346,8 +346,7 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) }) + it('resizes the split panel without writing an inherited slide distance', async () => { + const h = await mountSeat() + h.open() + const panel = element(h.view.container, '[data-sidebar-right-panel]') + fireEvent.transitionEnd(element(panel, "[data-dockkit-host='dock']")) + act(() => { h.actions.splitPane(SESSION) }) + expect(h.view.container.querySelectorAll('[data-dockkit-pane]')).toHaveLength(2) + for (const width of [518, 620]) { + h.view.update({ width, viewportWidth: 1440, canShow: true }) + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe(`${width}px`) + expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('') + } + act(() => { h.actions.setExpanded(SESSION, false) }) + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('620px') + }) + it('fills the viewport without replacing the content tree or releasing the wide track', async () => { const h = await mountSeat() const tab = h.open() const panel = element(h.view.container, '[data-sidebar-right-panel]') const body = element(h.view.container, '[data-tab-body]') - expect(panel.style.width).toBe('420px') + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('420px') fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]')) expect(h.layout().mode).toBe('fullscreen') - expect(panel.style.width).toBe('calc(1px + 100vw)') - expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('calc(100vw + 1px)') + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('calc(100vw + 1px)') expect(panel.dataset['sidebarRightPanel']).toBe('fullscreen') expect(element(h.view.container, '[data-tab-body]')).toBe(body) expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, true) expect(h.bodies.get(tab.id)?.sidebar).toEqual({ expanded: true, fullscreen: true }) fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]')) - expect(panel.style.width).toBe('420px') + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('420px') expect(element(h.view.container, '[data-tab-body]')).toBe(body) expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, false) fireEvent.click(element(h.view.container, '[data-sidebar-right-toggle]')) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index d59a3c843f..536e183bc5 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -8,6 +8,17 @@ const css = readFileSync(fileURLToPath(new URL('../src/client/shell/SidebarRight const host = String.raw`:global\(\[data-dockkit-host='dock'\]\)` describe('SidebarRight.module.css', () => { + it('keeps panel width local except for closed docks and items joining an animated opening', () => { + const distance = String.raw`--dsh-sidebar-width:\s*var\(--dsh-sidebar-right-panel-width\);` + expect(css).toMatch(/@property --dsh-sidebar-right-panel-width\s*\{\s*syntax: '';\s*inherits: false;\s*initial-value: 0px;/) + expect(css).toMatch(/\.panel\s*\{[^{}]*\bwidth: var\(--dsh-sidebar-right-panel-width\);/) + expect(css).toMatch(new RegExp(String.raw`\.panel:not\(\[data-sidebar-right-open\]\)\s*\{\s*${distance}\s*}`)) + // Reduced motion need not produce a transitionend to clear the opening marker. + expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: no-preference\)\s*\{\s*` + + String.raw`\.panel\[data-sidebar-right-opening\]\s*\{\s*${distance}\s*}\s*}`)) + expect(css.match(/--dsh-sidebar-width:/g)).toHaveLength(2) + }) + it('starts docked items mounted by an opening at the closed position', () => { expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*\.panel\[data-sidebar-right-opening\] ${host},[^{}]*\{` + String.raw`\s*transform: translateX\(var\(--dsh-sidebar-width\)\);\s*}\s*}`)) diff --git a/packages/core/tool-executor-ptc/README.i18n.yaml b/packages/core/tool-executor-ptc/README.i18n.yaml index 0acdbc39dc..3234d5ce54 100644 --- a/packages/core/tool-executor-ptc/README.i18n.yaml +++ b/packages/core/tool-executor-ptc/README.i18n.yaml @@ -60,8 +60,8 @@ en: f4703836365dc3d4 zh: a09ff48a6550fd69 /deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work: - en: 0159ba9c4dda070f - zh: 9be2f81d398868a1 + en: 872e593c876f4057 + zh: a197742ee74eefa6 /deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/core/tool-executor-ptc/README.md b/packages/core/tool-executor-ptc/README.md index 0d01bbd4ad..52e17b42cf 100644 --- a/packages/core/tool-executor-ptc/README.md +++ b/packages/core/tool-executor-ptc/README.md @@ -163,7 +163,7 @@ These constraints apply to the host integration and accepted calls. - **No built-in reset control** — the shipped Loader plugin does not expose its executor instance through a service, GUI control or SDK endpoint. Hosts needing reset must mount and retain `PtcExecutor` in their own composition; that integration owns retries after a failed reset. - **PTC mode uses TypeScript, and presentation is per agent rather than per tool** — PTC execution requires `ctx.ptcRuntime.language === 'typescript'`; within one agent no tool can be native-only while another is ptc-only. - **PTC mode intermediate values are execution-local and unbounded by bytes** — they cannot be reconstructed from session replay and may exhaust process or worker memory; only the outer `run_code` output has the worker's configurable hard cap. -- **State depends on the runtime**: the default backend starts fresh; Node `persistent-in-memory` execution and Script mode with `scriptPersistence: true` retain memory per live Agent. Agent disposal awaits release. Restart and execution failures can clear memory; model-visible guidance explains how to recreate missing variables. Programs and results remain in the Session log, without serializing live objects. +- **State depends on the runtime**: Node `per-call` execution starts fresh; the default Node `persistent-in-memory` execution and Script mode with `scriptPersistence: true` retain memory per live Agent. Agent disposal awaits release. Restart and execution failures can clear memory; model-visible guidance explains how to recreate missing variables. Programs and results remain in the Session log, without serializing live objects. ### Dev Note diff --git a/packages/core/tool-executor-ptc/README.zh.md b/packages/core/tool-executor-ptc/README.zh.md index 876dd44b19..e9831fe6cf 100644 --- a/packages/core/tool-executor-ptc/README.zh.md +++ b/packages/core/tool-executor-ptc/README.zh.md @@ -163,7 +163,7 @@ Error: code run failed (abort): run_code exceeded its limit of 2048 tool calls ( - **没有内置重置控件**:自带的 Loader 插件不通过服务、GUI 控件或 SDK 端点暴露执行器实例。需要重置的宿主必须在自己的组合中挂载并保留 `PtcExecutor`,该集成负责失败后的重试。 - **PTC mode 使用 TypeScript,且呈现方式按 agent 而非按工具**:PTC 执行要求 `ctx.ptcRuntime.language === 'typescript'`;同一个 agent 内不能让一个工具仅使用 Native,而另一个仅使用 PTC。 - **PTC mode 中间值只存在于执行局部,且没有字节上限**:它们无法从会话回放重建,并可能耗尽进程或 worker 内存;只有外层 `run_code` 输出受 worker 可配置的硬上限约束。 -- **状态由运行时决定**:默认后端每次重新开始;Node 的 `persistent-in-memory` 执行和启用 `scriptPersistence: true` 的 Script 模式按存活 Agent 保留内存。Agent 销毁时等待环境释放。重启与执行失败可能清除内存;模型说明会指导重新创建缺失变量。程序与结果仍写入 Session 日志,不序列化运行中的对象。 +- **状态由运行时决定**:Node 的 `per-call` 执行每次重新开始;默认的 Node `persistent-in-memory` 执行和启用 `scriptPersistence: true` 的 Script 模式按存活 Agent 保留内存。Agent 销毁时等待环境释放。重启与执行失败可能清除内存;模型说明会指导重新创建缺失变量。程序与结果仍写入 Session 日志,不序列化运行中的对象。 ### 开发备注 diff --git a/packages/experimental/action-cards/README.i18n.yaml b/packages/experimental/action-cards/README.i18n.yaml index 3a8a4ee2e5..8262560581 100644 --- a/packages/experimental/action-cards/README.i18n.yaml +++ b/packages/experimental/action-cards/README.i18n.yaml @@ -18,14 +18,14 @@ en: 697aac17308c991b zh: 0e338bb18457aabc /deepseek-ai-dsh-action-cards/use-this-package/register-a-card-kind: - en: ec2c7e23b17e2d3e - zh: f6e104e7ce68c3ac + en: 2003c7c13914bb55 + zh: 296c1bf9ad1bd1fc /deepseek-ai-dsh-action-cards/use-this-package/card-rules: - en: 1720908663123d8e - zh: abc24f2874f21e59 + en: 0ba291cab3c4c773 + zh: 0ad5b6f8ec91d375 /deepseek-ai-dsh-action-cards/understand-the-implementation: - en: 2553967d926b491d - zh: 8d7edff4d39aff5e + en: 41a46e1f7647b09d + zh: 215f9b5823201daf /deepseek-ai-dsh-action-cards/further-exploration: en: b5d6fde7329f67a7 zh: db2839d22fc577c4 @@ -60,8 +60,8 @@ en: 58785543e2428dba zh: 4b082f77b3b2f482 /deepseek-ai-dsh-action-cards/known-limitations-and-deferred-work: - en: a59763d767870671 - zh: a5fce29a79e17d0f + en: 2377288074636c31 + zh: 4c0342c146ad6533 /deepseek-ai-dsh-action-cards/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: bd8a8936229e035e diff --git a/packages/experimental/action-cards/README.md b/packages/experimental/action-cards/README.md index cc4afeca09..c3527952fc 100644 --- a/packages/experimental/action-cards/README.md +++ b/packages/experimental/action-cards/README.md @@ -29,15 +29,15 @@ The [Personalized recommendations](../personalized-recommendations/README.md) bu ### Register a card kind -A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)` from its own plugin; unloading that plugin removes the kind, and actions on its cards are then refused as unavailable, except that Not now still dismisses an unstarted card. Its own skill tells the model when to offer the card and what the block holds. The kind names its action, a zod schema for the card's `details`, the user actions it accepts and the shared checks each needs (`global` Remote access, `writes` refused in a read-only Session), the recorded phases that still offer dismissal, optional status guidance, the decision data fields the status notice reports, an optional `reconcile` that updates the card's recorded decision from state outside the Session before every action, and the handler for every action except `dismiss`. The handler records each new decision with `ctx.actionCards.record()`, which refuses an action no kind registered and the derived `replaced` phase, and returns `accepted`, `settled` with the decision in effect, `refused` or `unconfirmed`. +A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)` from its own plugin; unloading that plugin removes the kind, and actions on its cards are then refused as unavailable, except that Not now still dismisses an unstarted card. Its own skill tells the model when to offer the card and what the block holds. The kind names its action, a zod schema for the card's `details`, the user actions it accepts and the shared checks each needs (`global` Remote access, `writes` refused in a read-only Session), the recorded phases that still offer dismissal, optional status guidance, the decision data fields the status notice reports, an optional `reconcile` that updates the card's recorded decision from state outside the Session before every action, and the handler for every action except `dismiss`. The handler records each new decision with `ctx.actionCards.record()`, which refuses an action no kind registered, and returns `accepted`, `settled` with the decision in effect, `refused` or `unconfirmed`. ### Card rules - A card is a fenced block whose language is `action-card` and whose content is one JSON object with `action`, `title`, `brief` and an object `details`. A block counts when its fence follows at most three spaces, or at most three spaces and a list item marker; a block in a block quote, one indented four or more spaces and one inside another fenced block offer no card. The first such block of a turn that parses becomes the card, named by the id of the assistant message that holds it. Later blocks of that turn, blocks in reasoning, blocks in an interrupted answer, blocks with a blank title or brief, and every block of a subagent Session create no card, and nothing reports this to the model. -- Admission does not check the kind: a card whose action no kind registered, or whose `details` fail the kind schema, still appears, replaces every unstarted earlier card, and refuses every action except Not now as unavailable. -- A newer card of any kind replaces every unstarted earlier card. Replacement is derived from the log and never recorded. +- Admission does not check the kind: a card whose action no kind registered, or whose `details` fail the kind schema, still appears and refuses every action except Not now as unavailable. +- Cards from different turns remain available independently. Each card takes its state from decisions recorded for its own id. - Events a forked Session inherits create no cards. -- Before every action, including Not now, the kind's `reconcile` updates the card from state outside the Session. Not now is then recorded for an unstarted card and for the phases the kind lists; dismissed and replaced cards accept no further action. Without its registered kind, Not now still dismisses an unstarted card, and every other action is refused as unavailable. +- Before every action, including Not now, the kind's `reconcile` updates the card from state outside the Session. Not now is then recorded for an unstarted card and for the phases the kind lists; dismissed cards accept no further action. Without its registered kind, Not now still dismisses an unstarted card, and every other action is refused as unavailable. - Concurrent actions on one card share one operation. Actions require the exact live Agent for the card's Session, whose `origin` must not be `subagent`. ----- @@ -48,9 +48,9 @@ A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)`
Implementation internals — click to expand -The package default-exports the `actionCards` Remote service and registers no tool. The logged answer is the durable proposal: the `actionCards` Session projection (state version 3) reads the text blocks of each `assistant/message` with [`src/fence.ts`](src/fence.ts), which finds fenced blocks at the top level and in list items by the CommonMark fence rules and matches their language the way the Chat client dispatches fences, and admits the first valid block of the turn. It also records decisions from `plugin:action-cards/decision`, and keeps unreported decisions until a status notice whose `through` covers them enters the log. The header's `origin` marks a subagent Session, whose projection admits nothing. Its Client view `{ proposals, decisions }` is excluded from Session summaries. +The package default-exports the `actionCards` Remote service and registers no tool. The logged answer is the durable proposal: the `actionCards` Session projection (state version 4) reads the text blocks of each `assistant/message` with [`src/fence.ts`](src/fence.ts), which finds fenced blocks at the top level and in list items by the CommonMark fence rules and matches their language the way the Chat client dispatches fences, and admits the first valid block of the turn. It also records decisions from `plugin:action-cards/decision`, and keeps unreported decisions until a status notice whose `through` covers them enters the log. The header's `origin` marks a subagent Session, whose projection admits nothing. Its Client view `{ proposals, decisions }` is excluded from Session summaries. -The Remote `act(sessionId, cardId, verb, payload?)` checks the owner, the live root and the card; Not now continues without a registered kind, while other verbs need the kind, the verb and Remote access. It then shares one operation per card. The kind's `reconcile` runs first and the live root is checked again; a dismissed or replaced card then settles unchanged, Not now is recorded, a writing verb is refused in a read-only Session, and every other verb goes to the kind handler under the Agent's initiator. `record()` also accepts an action whose kind has unregistered, because Cordis disposes a plugin's effects concurrently and an unloading kind still records the outcome of work it started. An `agent/pre-step` listener adds the status notice after later listeners prepared the step. +The Remote `act(sessionId, cardId, verb, payload?)` checks the owner, the live root and the card; Not now continues without a registered kind, while other verbs need the kind, the verb and Remote access. It then shares one operation per card. The kind's `reconcile` runs first and the live root is checked again; a dismissed card then settles unchanged, Not now is recorded, a writing verb is refused in a read-only Session, and every other verb goes to the kind handler under the Agent's initiator. `record()` also accepts an action whose kind has unregistered, because Cordis disposes a plugin's effects concurrently and an unloading kind still records the outcome of work it started. An `agent/pre-step` listener adds the status notice after later listeners prepared the step. | Source | Contents | |---|---| @@ -116,9 +116,7 @@ The notice is appended after the request's other new context and never rewrites - The model learns nothing about a block that creates no card: a malformed block, a second block of the turn or a subagent's block shows nothing, while the answer may already invite the user to the card. - The Host finds blocks line by line and reads only the literal language `action-card`, while the Chat client hides every `action-card` block it renders. A block in a block quote, one indented four or more spaces in a nested list item, or one whose language is written with an escape or a character reference, is hidden and offers no card; a block inside an HTML block or a `$$` or `\[ … \]` math block offers a card while its text stays visible. The skills ask for one top-level block at the end of the answer. - Sessions recorded with the removed `propose_action` tool show no card for those calls, and decision records that name a card `callId` are skipped. -- A card that fails its kind schema or names no registered kind still replaces an unstarted earlier card, which then offers no action. - Cards are offered in the main conversation only. A subagent Session, including a Creator child's, admits no card, because only a live root can act on one. -- Only one card is offered per turn across all kinds. A later card of any kind replaces every unstarted earlier card, so a second kind's card replaces an unstarted card of the first. - Refusal reasons of user actions are plain strings by design: the service defines `closing`, `not-live-root`, `unknown`, `unavailable`, `access-denied` and `read-only`, each kind adds its own, and a browser body names the reasons it knows and treats others as unavailable. - Each kind validates `details` on both sides, with its Host schema before each action and with its browser body's own schema, so the two schemas change together. diff --git a/packages/experimental/action-cards/README.zh.md b/packages/experimental/action-cards/README.zh.md index 6074c46855..76e3a9ccff 100644 --- a/packages/experimental/action-cards/README.zh.md +++ b/packages/experimental/action-cards/README.zh.md @@ -29,15 +29,15 @@ kind: "package-reference" ### 注册卡片种类 -种类所在的包注入 `actionCards`,并在自己的插件中调用 `ctx.actionCards.register(kind)`;该插件卸载时种类随之移除,此后对其卡片的操作会以 unavailable 拒绝,只有“暂不需要”仍可忽略尚未开始的卡片。种类自己的 Skill 告诉模型何时提供卡片以及代码块里写什么。种类需要给出:动作名、卡片 `details` 的 zod 校验、接受的用户操作及各自需要的共享检查(`global` 表示需要全局 Remote 权限,`writes` 表示只读会话中拒绝)、仍可忽略卡片的已记录阶段、可选的状态说明、状态通知要报告的决定数据字段、可选的 `reconcile`(每次操作前根据会话之外的状态更新卡片的已记录决定),以及处理 `dismiss` 以外所有操作的处理器。处理器用 `ctx.actionCards.record()` 记录每个新决定(该方法拒绝没有种类注册过的动作和推导得出的 `replaced` 阶段),并返回 `accepted`、带当前决定的 `settled`、`refused` 或 `unconfirmed`。 +种类所在的包注入 `actionCards`,并在自己的插件中调用 `ctx.actionCards.register(kind)`;该插件卸载时种类随之移除,此后对其卡片的操作会以 unavailable 拒绝,只有“暂不需要”仍可忽略尚未开始的卡片。种类自己的 Skill 告诉模型何时提供卡片以及代码块里写什么。种类需要给出:动作名、卡片 `details` 的 zod 校验、接受的用户操作及各自需要的共享检查(`global` 表示需要全局 Remote 权限,`writes` 表示只读会话中拒绝)、仍可忽略卡片的已记录阶段、可选的状态说明、状态通知要报告的决定数据字段、可选的 `reconcile`(每次操作前根据会话之外的状态更新卡片的已记录决定),以及处理 `dismiss` 以外所有操作的处理器。处理器用 `ctx.actionCards.record()` 记录每个新决定(该方法拒绝没有种类注册过的动作),并返回 `accepted`、带当前决定的 `settled`、`refused` 或 `unconfirmed`。 ### 卡片规则 - 卡片是语言为 `action-card` 的围栏代码块,内容是一个 JSON 对象,包含 `action`、`title`、`brief` 和对象类型的 `details`。围栏前最多有 3 个空格,或最多 3 个空格加一个列表项标记的代码块才算数;引用块里的、缩进 4 格及以上的,以及其他围栏代码块里的代码块不提供卡片。一轮中第一个能解析的这种代码块成为卡片,以所在助手消息的 id 作为卡片 id。同一轮之后的代码块、思考内容里的代码块、被打断的回答里的代码块、标题或说明为空的代码块,以及 subagent 会话里的所有代码块都不会产生卡片,也不会告知模型。 -- 收下卡片时不检查种类:动作没有种类注册、或 `details` 未通过种类校验的卡片照样出现,并替换此前所有尚未开始的卡片,除“暂不需要”外的操作一律以 unavailable 拒绝。 -- 任何种类的新卡片都会替换此前所有尚未开始的卡片。替换从日志推导,从不单独记录。 +- 收下卡片时不检查种类:动作没有种类注册、或 `details` 未通过种类校验的卡片照样出现,除“暂不需要”外的操作一律以 unavailable 拒绝。 +- 不同轮次的卡片各自可用,每张卡片的状态由其自身 ID 对应的决定记录确定。 - fork 出的会话从父会话继承的事件不会产生卡片。 -- 每次操作(包括“暂不需要”)之前,种类的 `reconcile` 先根据会话之外的状态更新卡片。之后,对尚未开始的卡片,以及处于种类列出阶段的卡片,“暂不需要”会被记录;已忽略、已替换的卡片不再接受任何操作。卡片的种类未注册时,“暂不需要”仍可忽略尚未开始的卡片,其他操作一律以 unavailable 拒绝。 +- 每次操作(包括“暂不需要”)之前,种类的 `reconcile` 先根据会话之外的状态更新卡片。之后,对尚未开始的卡片,以及处于种类列出阶段的卡片,“暂不需要”会被记录;已忽略的卡片不再接受任何操作。卡片的种类未注册时,“暂不需要”仍可忽略尚未开始的卡片,其他操作一律以 unavailable 拒绝。 - 同一张卡片上的并发操作共用一次处理。操作要求调用者是卡片所在 Session 的精确在线 Agent 实例,且 `origin` 不是 `subagent`。 ----- @@ -48,9 +48,9 @@ kind: "package-reference"
实现细节——点击展开 -本包默认导出 `actionCards` Remote 服务,不注册任何工具。日志里的回答就是持久的提议:`actionCards` 会话投影(状态版本 3)用 [`src/fence.ts`](src/fence.ts) 读取每条 `assistant/message` 的文字块,按 CommonMark 的围栏规则找出顶层和列表项里的围栏代码块,并按 Chat 客户端分派代码块的方式匹配语言,收下本轮第一个合格的代码块。投影还从 `plugin:action-cards/decision` 读取决定,并保留尚未报告的决定,直到 `through` 覆盖它们的状态通知写入日志。会话头的 `origin` 标出 subagent 会话,其投影不收任何卡片。投影的客户端视图 `{ proposals, decisions }` 不进入会话摘要。 +本包默认导出 `actionCards` Remote 服务,不注册任何工具。日志里的回答就是持久的提议:`actionCards` 会话投影(状态版本 4)用 [`src/fence.ts`](src/fence.ts) 读取每条 `assistant/message` 的文字块,按 CommonMark 的围栏规则找出顶层和列表项里的围栏代码块,并按 Chat 客户端分派代码块的方式匹配语言,收下本轮第一个合格的代码块。投影还从 `plugin:action-cards/decision` 读取决定,并保留尚未报告的决定,直到 `through` 覆盖它们的状态通知写入日志。会话头的 `origin` 标出 subagent 会话,其投影不收任何卡片。投影的客户端视图 `{ proposals, decisions }` 不进入会话摘要。 -Remote `act(sessionId, cardId, verb, payload?)` 先检查服务所有者、在线根 Agent 和卡片;“暂不需要”在种类未注册时也继续处理,其他操作还需要种类、操作和 Remote 权限。然后同一张卡片共用一次处理。种类的 `reconcile` 先运行,之后再次检查在线根 Agent;已忽略或已替换的卡片原样返回,“暂不需要”被记录,写入类操作在只读会话中被拒绝,其余操作在该 Agent 的发起方作用域内交给种类处理器。`record()` 也接受种类已注销的动作,因为 Cordis 并发释放插件的各个 effect,卸载中的种类仍要记录已开始工作的结果。一个 `agent/pre-step` 监听器在后续监听器准备好本步之后追加状态通知。 +Remote `act(sessionId, cardId, verb, payload?)` 先检查服务所有者、在线根 Agent 和卡片;“暂不需要”在种类未注册时也继续处理,其他操作还需要种类、操作和 Remote 权限。然后同一张卡片共用一次处理。种类的 `reconcile` 先运行,之后再次检查在线根 Agent;已忽略的卡片原样返回,“暂不需要”被记录,写入类操作在只读会话中被拒绝,其余操作在该 Agent 的发起方作用域内交给种类处理器。`record()` 也接受种类已注销的动作,因为 Cordis 并发释放插件的各个 effect,卸载中的种类仍要记录已开始工作的结果。一个 `agent/pre-step` 监听器在后续监听器准备好本步之后追加状态通知。 | 源码 | 内容 | |---|---| @@ -116,9 +116,7 @@ Latest status of action cards from user actions and background work. These are s - 代码块没有产生卡片时模型不会知道:格式错误的代码块、同一轮的第二个代码块或 subagent 的代码块都不显示任何东西,而回答里可能已经邀请用户点卡片。 - Host 逐行查找代码块,只认字面上就是 `action-card` 的语言,而 Chat 客户端会隐藏它渲染出的每一个 `action-card` 代码块。引用块里的代码块、嵌套列表项里缩进 4 格及以上的代码块、语言用转义或字符引用写成的代码块会被隐藏,但不提供卡片;HTML 块或 `$$`、`\[ … \]` 数学块里的代码块会提供卡片,但其文字仍然可见。各 Skill 要求在回答末尾写一个顶层代码块。 - 用已移除的 `propose_action` 工具录下的会话,这些调用不再显示卡片;用 `callId` 指代卡片的决定记录会被跳过。 -- 未通过种类校验或动作没有注册的卡片仍会替换此前尚未开始的卡片,被替换的卡片不再提供任何操作。 - 卡片只在主对话中提供。subagent 会话(包括 Creator 子 Agent 的会话)不收任何卡片,因为只有在线的根 Agent 才能对卡片进行操作。 -- 所有种类合计每轮只展示一张卡片。任何种类的新卡片都会替换此前所有尚未开始的卡片,因此第二个种类的卡片会替换第一个种类尚未开始的卡片。 - 用户操作的拒绝原因有意设计为普通字符串:服务定义 `closing`、`not-live-root`、`unknown`、`unavailable`、`access-denied` 和 `read-only`,各种类可以添加自己的原因,浏览器端正文为已知原因显示文案,其余按 unavailable 处理。 - 每个种类在两端各自校验 `details`:Host 端的 schema 在每次操作前校验,浏览器端正文用自己的 schema 校验,因此两个 schema 要一起修改。 diff --git a/packages/experimental/action-cards/src/index.ts b/packages/experimental/action-cards/src/index.ts index 4a318b5ea4..b8fa134182 100644 --- a/packages/experimental/action-cards/src/index.ts +++ b/packages/experimental/action-cards/src/index.ts @@ -19,10 +19,6 @@ declare module '@deepseek-ai/cordis' { /** The user action every card offers; the shared service records it. */ const DISMISS = 'dismiss' -/** Phases the projection derives from the log; no decision may record them. */ -const DERIVED_PHASES: readonly string[] = ['replaced'] -/** Phases after which no user action changes the card. */ -const FINAL_PHASES: readonly string[] = ['dismissed', ...DERIVED_PHASES] const STATUS_PREAMBLE = 'Latest status of action cards from user actions and background work. ' + 'These are status facts, not a request to start or retry work. Use these receipts instead of the earlier proposal when describing progress.' @@ -223,13 +219,12 @@ export class ActionCards extends TypertRemoteService { * Record a card decision in the Session log; the next model request reports it. * @param agent - agent whose Session owns the card. * @param decision - the card's new state. - * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + * @throws when no kind ever registered the decision's action with this service. */ record(agent: Agent, decision: ActionCardDecision): void { if (!this.kinds.has(decision.action) && !this.retired.has(decision.action)) { throw new Error(`action-cards: cannot record a decision for unregistered action "${decision.action}"`) } - if (DERIVED_PHASES.includes(decision.phase)) throw new Error(`action-cards: phase "${decision.phase}" is derived from the log and cannot be recorded`) this.append(agent, decision) } @@ -299,7 +294,7 @@ export class ActionCards extends TypertRemoteService { if (refusal !== undefined) return refusal const decision = ownEntry(this.projection.stateOf(agent.session).view.decisions, proposal.cardId) // Without its kind no recorded phase is known to be open, and the kind may return to act on it. - if (decision !== undefined && (FINAL_PHASES.includes(decision.phase) || kind?.openPhases.includes(decision.phase) !== true)) { + if (decision !== undefined && (decision.phase === 'dismissed' || kind?.openPhases.includes(decision.phase) !== true)) { return { status: 'settled', decision } } const data = kind?.dismissal(proposal, payload) @@ -315,7 +310,7 @@ export class ActionCards extends TypertRemoteService { const refusal = await this.reconciled(agent, kind, proposal, verb) if (refusal !== undefined) return refusal const decision = ownEntry(this.projection.stateOf(agent.session).view.decisions, proposal.cardId) - if (decision !== undefined && FINAL_PHASES.includes(decision.phase)) return { status: 'settled', decision } + if (decision?.phase === 'dismissed') return { status: 'settled', decision } if (policy.writes === true && this.ctx.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only') return refused('read-only') return await kind.act(agent, proposal, verb, payload) } diff --git a/packages/experimental/action-cards/src/projection.ts b/packages/experimental/action-cards/src/projection.ts index 601375ab9d..7ed0aca450 100644 --- a/packages/experimental/action-cards/src/projection.ts +++ b/packages/experimental/action-cards/src/projection.ts @@ -84,11 +84,11 @@ function cardFieldsOf(message: AssistantMessage): CardFields | undefined { /** * Full-Session fold. The first valid `action-card` block in a turn's answer text becomes the card, named by the id of - * its assistant message. Later blocks of that turn create no card, and a newer card replaces every unstarted earlier - * card. Interrupted answers, subagent Sessions and events inherited by a forked Session create no proposals. + * its assistant message. Later blocks of that turn create no card. Interrupted answers, subagent Sessions and events inherited + * by a forked Session create no proposals. */ export const actionCardProjection: ActionCardProjectionDefinition = { - key: 'actionCards', stateVersion: 3, stateSchema, + key: 'actionCards', stateVersion: 4, stateSchema, init: (header, inheritedEventCount) => ({ inheritedEventCount, offers: header.origin !== 'subagent', view: { proposals: {}, decisions: {} }, admittedTurn: null, pendingStatus: {}, }), @@ -106,13 +106,8 @@ export const actionCardProjection: ActionCardProjectionDefinition = { const fields = cardFieldsOf(message) if (fields === undefined) return state const cardId = brandString(message.id) - const decisions = { ...state.view.decisions } - // A newer card supersedes every unstarted card; the model made that choice, so no status is reported. - for (const earlier of Object.values(state.view.proposals)) { - if (decisions[earlier.cardId] === undefined) decisions[earlier.cardId] = { cardId: earlier.cardId, action: earlier.action, phase: 'replaced' } - } const proposals = { ...state.view.proposals, [cardId]: { cardId, turn, ...fields } } - return { ...state, admittedTurn: turn, view: { proposals, decisions } } + return { ...state, admittedTurn: turn, view: { ...state.view, proposals } } } default: { const record = pluginRecordOf(event) diff --git a/packages/experimental/action-cards/src/types.ts b/packages/experimental/action-cards/src/types.ts index 02434d235e..366d770f29 100644 --- a/packages/experimental/action-cards/src/types.ts +++ b/packages/experimental/action-cards/src/types.ts @@ -28,11 +28,7 @@ export interface ActionCardProposal { readonly details: ActionCardFields } -/** - * Latest state of one card. Kinds define their own phases; `dismissed` is shared. - * `replaced` (a later proposal superseded an unstarted card) is derived from the - * log and never recorded. - */ +/** Latest recorded decision of one card. Kinds define their own phases alongside the shared `dismissed` phase. */ export interface ActionCardDecision { readonly cardId: ActionCardId readonly action: string diff --git a/packages/experimental/action-cards/tests/act.spec.ts b/packages/experimental/action-cards/tests/act.spec.ts index 8a72eb3fa1..ef0139b582 100644 --- a/packages/experimental/action-cards/tests/act.spec.ts +++ b/packages/experimental/action-cards/tests/act.spec.ts @@ -137,13 +137,11 @@ it('refuses the action when reconciliation fails or the root closes meanwhile', expect(f.act).not.toHaveBeenCalled() }) -it('refuses to record decisions of actions no kind registered or of phases the projection derives', async () => { +it('refuses to record decisions of actions no kind registered', async () => { const f = await fixture() const cardId = f.offer() expect(() => { f.ctx.actionCards.record(f.agent, { cardId, action: 'other_action', phase: 'done' }) }) .toThrow('action-cards: cannot record a decision for unregistered action "other_action"') - expect(() => { f.ctx.actionCards.record(f.agent, { cardId, action: ACTION, phase: 'replaced' }) }) - .toThrow('action-cards: phase "replaced" is derived from the log and cannot be recorded') expect(f.view().decisions).toEqual({}) // An unloading kind still records the outcome of work it had started. await f.kindFiber.dispose() diff --git a/packages/experimental/action-cards/tests/projection.spec.ts b/packages/experimental/action-cards/tests/projection.spec.ts index 137b5d6b10..b58ce44792 100644 --- a/packages/experimental/action-cards/tests/projection.spec.ts +++ b/packages/experimental/action-cards/tests/projection.spec.ts @@ -7,6 +7,7 @@ import { import type { PluginRecordMap } from '@deepseek-ai/dsh-session/types' import { actionCardProjection, type ActionCardState } from '../src/projection.ts' import type { ActionCardId } from '../src/types.ts' +import { ACTION, fixture, proposal } from './fixture.ts' const projection = actionCardProjection const args = { action: 'test_action', title: 'Counter', brief: 'Keep count visible', details: { value: 'a' } } @@ -50,9 +51,9 @@ const notice = (through: number): SessionEvent<'user/message'> => ({ type: 'user data: createUserMessage({ content: [{ type: 'text', text: 'status' }], source: { kind: 'action-cards', through: SessionSeq(through), form: 'notice', summary: 'status' } }) }) -it('admits the first valid action-card block of an answer as a card named by the answer message id', () => { +it('admits only the first valid block across the answers of a turn, named by its message id', () => { const offered = answer(`Here is an option.\n\n${block()}\n`) - expect(fold([turn(1), offered]).view.proposals).toEqual({ [idOf(offered)]: { cardId: idOf(offered), turn: 1, ...args } }) + expect(fold([offered, answer(block())]).view.proposals).toEqual({ [idOf(offered)]: { cardId: idOf(offered), turn: 1, ...args } }) const second = answer(`${block('{broken')}\n${block({ ...args, title: ' ' })}\n${block({ ...args, title: ' Second ' })}\n${block()}`) expect(fold([second]).view.proposals[idOf(second)]?.title).toBe('Second') const split = answer([{ type: 'text', text: 'No card yet.' }, { type: 'text', text: block({ ...args, title: 'Later block' }) }]) @@ -71,23 +72,35 @@ it('admits the first valid action-card block of an answer as a card named by the expect(fold([reasoning]).view.proposals).toEqual({}) }) -it('keeps the first card of a turn across steps, and replaces only unstarted earlier cards', () => { - const firstAnswer = answer(block()) - const first = fold([turn(1), firstAnswer]) - const a = idOf(firstAnswer) - expect(fold([answer(block({ ...args, title: 'Late' }))], first)).toEqual(first) - const nextAnswer = answer(block(args), 2) - const next = fold([turn(2), nextAnswer], first) - expect(Object.keys(next.view.proposals)).toEqual([a, idOf(nextAnswer)]) - expect(next.view.decisions).toEqual({ [a]: { cardId: a, action: 'test_action', phase: 'replaced' } }) - const started = fold(records({ cardId: a, action: 'test_action', phase: 'creating' }), first) - const laterAnswer = answer(block(args), 2) - const afterStart = fold([turn(2), laterAnswer], started) - expect(afterStart.view.decisions[a]?.phase).toBe('creating') - expect(afterStart.view.decisions[idOf(laterAnswer)]).toBeUndefined() - // Replacement crosses kinds: a card of another action replaces the unstarted one too. - const otherAnswer = answer(block({ ...args, action: 'other_action' }), 2) - expect(fold([turn(2), otherAnswer], first).view.decisions).toEqual({ [a]: { cardId: a, action: 'test_action', phase: 'replaced' } }) +it('replays v3 replacements from the log and restores a current checkpoint with its suffix', async () => { + const f = await fixture() + const { session } = f.agent + const registry = f.ctx.sessionProjections + const open = f.offer() + const started = f.offer(proposal, f.agent, 2) + const creating = { cardId: started, action: ACTION, phase: 'creating' } + f.ctx.actionCards.record(f.agent, creating) + const dismissed = f.offer(proposal, f.agent, 3) + const dismissal = { cardId: dismissed, action: ACTION, phase: 'dismissed' } + f.ctx.actionCards.record(f.agent, dismissal) + const prefix = registry.checkpoint(session) + const row = prefix['actionCards']! + const legacy = projection.stateSchema.parse(row.val) + legacy.view.decisions[open] = { cardId: open, action: ACTION, phase: 'replaced' } + const stale = { ...prefix, actionCards: { ...row, ver: 3, val: legacy } } + const example = f.offer({ ...proposal, action: 'my_example' }, f.agent, 4) + const events = session.snapshotEvents() + const restore = (checkpoint: typeof prefix, offset: number) => registry.restore( + checkpoint, events.slice(offset), SessionLogOffset(offset), session.header, session.inheritedEventCount, + ) + const full = restore({}, 0) + expect(registry.restoreFloor(stale)).toBe(0) + expect(restore(stale, 0)).toEqual(full) + expect(restore(prefix, row.seq + 1)).toEqual(full) + const recovered = projection.stateSchema.parse(full.checkpoint['actionCards']!.val) + expect(Object.keys(recovered.view.proposals)).toEqual([open, started, dismissed, example]) + expect(recovered.view.decisions).toEqual({ [started]: creating, [dismissed]: dismissal }) + expect(Object.keys(recovered.pendingStatus)).toEqual([started, dismissed]) }) it('creates no card from an interrupted answer or in a subagent Session', () => { diff --git a/packages/experimental/client-ui-action-cards/README.i18n.yaml b/packages/experimental/client-ui-action-cards/README.i18n.yaml index 6fe8a12d5c..1f730149a7 100644 --- a/packages/experimental/client-ui-action-cards/README.i18n.yaml +++ b/packages/experimental/client-ui-action-cards/README.i18n.yaml @@ -18,8 +18,8 @@ en: 717a53d2170d253b zh: 4e52852690601371 /deepseek-ai-dsh-client-ui-action-cards/use-this-package/register-a-card-body: - en: f46356cea53e8c72 - zh: 76f7ee328445a5d4 + en: 924cf85fcb2804fe + zh: 6cc87fb92ffa31a3 /deepseek-ai-dsh-client-ui-action-cards/understand-the-implementation: en: 180ee8add4b750a4 zh: 8ad116b65ccd532a diff --git a/packages/experimental/client-ui-action-cards/README.md b/packages/experimental/client-ui-action-cards/README.md index 95a992a982..bfc60eaba8 100644 --- a/packages/experimental/client-ui-action-cards/README.md +++ b/packages/experimental/client-ui-action-cards/README.md @@ -29,7 +29,7 @@ Enable the [Personalized recommendations](../personalized-recommendations/README ### Register a card body -A kind's browser plugin injects `actionCards` and registers its body inside its own `ctx.effect`: `ctx.actionCards.register({ action, locale, Body })` returns the disposer. The frame renders `Body` for cards of that action with the card, its recorded or derived decision, the Session id, the frame's title and folded brief as `summary`, the frame's dismiss-only content as `fallback`, the frame's fold component as `Folded`, an `act(verb, payload?)` bound to the card, and a translator `t` for the body's own locale namespace. The body places `summary` in its own layout, renders `fallback` instead when its schema rejects the card's `details`, and owns its header, controls, status and footer. A second body for the same action is a registration error. +A kind's browser plugin injects `actionCards` and registers its body inside its own `ctx.effect`: `ctx.actionCards.register({ action, locale, Body })` returns the disposer. The frame renders `Body` for cards of that action with the card, its latest recorded decision, the Session id, the frame's title and folded brief as `summary`, the frame's dismiss-only content as `fallback`, the frame's fold component as `Folded`, an `act(verb, payload?)` bound to the card, and a translator `t` for the body's own locale namespace. The body places `summary` in its own layout, renders `fallback` instead when its schema rejects the card's `details`, and owns its header, controls, status and footer. A second body for the same action is a registration error. ----- diff --git a/packages/experimental/client-ui-action-cards/README.zh.md b/packages/experimental/client-ui-action-cards/README.zh.md index c7274c97fa..8d35060b55 100644 --- a/packages/experimental/client-ui-action-cards/README.zh.md +++ b/packages/experimental/client-ui-action-cards/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 注册卡片正文 -种类的浏览器插件注入 `actionCards`,并在自己的 `ctx.effect` 中注册正文:`ctx.actionCards.register({ action, locale, Body })` 返回注销函数。框架为该动作的卡片渲染 `Body`,并传入:卡片、已记录或推导出的决定、会话 id、框架渲染的标题与折叠说明 `summary`、只提供“暂不需要”的后备内容 `fallback`、框架的折叠组件 `Folded`、绑定到该卡片的 `act(verb, payload?)`,以及正文自己语言命名空间的翻译函数 `t`。正文把 `summary` 放进自己的布局,卡片的 `details` 未通过自己的校验时改为渲染 `fallback`,并负责自己的标题栏、控件、状态和底部操作。为同一动作注册第二个正文属于注册错误。 +种类的浏览器插件注入 `actionCards`,并在自己的 `ctx.effect` 中注册正文:`ctx.actionCards.register({ action, locale, Body })` 返回注销函数。框架为该动作的卡片渲染 `Body`,并传入:卡片、最新的已记录决定、会话 id、框架渲染的标题与折叠说明 `summary`、只提供“暂不需要”的后备内容 `fallback`、框架的折叠组件 `Folded`、绑定到该卡片的 `act(verb, payload?)`,以及正文自己语言命名空间的翻译函数 `t`。正文把 `summary` 放进自己的布局,卡片的 `details` 未通过自己的校验时改为渲染 `fallback`,并负责自己的标题栏、控件、状态和底部操作。为同一动作注册第二个正文属于注册错误。 ----- diff --git a/packages/experimental/client-ui-action-cards/src/client/Card.tsx b/packages/experimental/client-ui-action-cards/src/client/Card.tsx index 29c9d3d09e..4983207dc8 100644 --- a/packages/experimental/client-ui-action-cards/src/client/Card.tsx +++ b/packages/experimental/client-ui-action-cards/src/client/Card.tsx @@ -126,9 +126,6 @@ export function ActionCard({ proposal, decision, sessionId, act, bind, useBodies } -/** Phases the fallback can name; other kind phases leave only the summary. */ -const NAMED_PHASES: Readonly> = { dismissed: 'dismissed', replaced: 'replaced' } - /** Title, brief and Not now for a card whose kind registered no body in this browser or whose body rejects its `details`. */ function FallbackBody({ summary, decision, act, t }: { summary: ReactNode @@ -137,7 +134,6 @@ function FallbackBody({ summary, decision, act, t }: { } & PropsLocale<'actionCards'>) { const [pending, setPending] = useState(false) const [error, setError] = useState() - const phase = decision === undefined || !Object.hasOwn(NAMED_PHASES, decision.phase) ? undefined : NAMED_PHASES[decision.phase] const dismiss = async () => { setPending(true) setError(undefined) @@ -152,7 +148,7 @@ function FallbackBody({ summary, decision, act, t }: { } return
{summary} - {phase !== undefined &&

{t(phase)}

} + {decision?.phase === 'dismissed' &&

{t('dismissed')}

} {error !== undefined &&

{t(error)}

} {decision === undefined &&