Merge remote-tracking branch 'origin/master' into feat/session-persistence-sqlite

This commit is contained in:
liukx0205 committed 2026-11-17 15:12:22 +08:00
commit fa69e91481
1185 files changed
+33246 -13714

No files matched your search

@@ -9,11 +9,11 @@
en: 8d4d00e33af763b2
zh: 61977c82d66ae9bf
/agent-note-account-provider-and-active-request-cancellation/decision:
en: d5eb12a1644c6226
zh: 513d4f22ab74e039
en: 6f5463ecf88c1435
zh: 7c9e46f90c8ccffb
/agent-note-account-provider-and-active-request-cancellation/alternatives-considered:
en: a072026c1495a1ca
zh: bf053cc04fb33914
en: 7ed93136cf11074a
zh: 1ee997e271e919ad
/agent-note-account-provider-and-active-request-cancellation/consequences:
en: 8fd00b6d69b380c0
zh: 3830dc3a93d5de3c
@@ -14,11 +14,11 @@ Selecting credentials from login state changes the billing identity of an existi
Account cancellation reads each running Agent’s latest `Session.requestContext()` instead of maintaining another provider field. This logged value remains through tools and retries and follows the next bound request. Idle Agents are excluded. During a new turn’s first preparation it can still name the previous turn’s account route, so sign-out can also interrupt an API-key turn that has not bound its new request yet. A missing account credential rejects a first request without a previous context before transport.
Successful local sign-out publishes an account event. The platform account provider installs the account module’s listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. The account controller shares its predicate for sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport.
Successful local sign-out publishes an account event. The account route plugin installs a listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. It registers the same predicate with the account service as the running-task report behind sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. Requests this listener cannot reach end through the withdrawal signal of their credential, which the [route credential decision](2026-11-10-llm-route-credential-seam.md) owns.
## Alternatives considered
A historical set of providers wrongly cancels a turn after it switches to an API-key route. Current settings misclassify an older in-flight request. A second provider field or module-global map duplicates information already recorded in request context. A login-level cancellation signal duplicates the existing Agent and HTTP cancellation chain.
A historical set of providers wrongly cancels a turn after it switches to an API-key route. Current settings misclassify an older in-flight request. A second provider field or module-global map duplicates information already recorded in request context. A login-level cancellation signal in place of this chain duplicates the existing Agent and HTTP cancellation; the credential's withdrawal signal only supplements it.
## Consequences
@@ -14,11 +14,11 @@ Status: implemented
账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。
本地退登成功后发布账号事件。Platform 账号提供方安装账号模块的监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。账号控制器的退登确认复用同一判断函数。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。
本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。
## Alternatives considered
历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。登录级取消信号重复现有 Agent 与 HTTP 取消链路。
历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的撤回信号只是对它的补充。
## Consequences
@@ -9,8 +9,8 @@
en: e42db40b879fdbf4
zh: 6017da9c4da17835
/agent-note-node-ptc-execution-modes-and-in-memory-state/decision:
en: 411054071757d5fe
zh: e683ef7d80f33fc6
en: 13a72b9728d25394
zh: 1f44510fe93836dc
/agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered:
en: 396157a9fc293198
zh: a061f05b4423e26f
@@ -18,7 +18,7 @@ One npm package and one plugin entry keep existing installation and loading path
The Session records submitted programs, nested tool calls and returned output. It does not serialize the REPL heap or rerun earlier programs after restart, resume or fork: replaying automation could repeat external side effects. A missing variable is a normal program error, and the model-visible instructions require recreating variables and reacquiring resources. No environment identifier or new durable Session event is required because the provider exposes no unlogged model input.
Protocol or output-limit failure, owner disposal and process exit discard the environment. The [interruption decision](2026-10-29-retained-ptc-interruption.md) owns timeout and cancellation recovery with retained state. Ordinary exceptions retain earlier mutations. A retained function uses the active evaluation's host bindings; asynchronous work from an earlier evaluation cannot acquire a later evaluation's tool authority or output sink.
Protocol failure, owner disposal and process exit discard the environment. [Output truncation](2026-11-13-ptc-output-truncation.md) owns bounded output without state disposal. The [interruption decision](2026-10-29-retained-ptc-interruption.md) owns timeout and cancellation recovery with retained state. Ordinary exceptions retain earlier mutations. A retained function uses the active evaluation's host bindings; asynchronous work from an earlier evaluation cannot acquire a later evaluation's tool authority or output sink.
## Alternatives considered
@@ -18,7 +18,7 @@ Status: implemented
Session 记录提交的程序、嵌套工具调用和返回输出。它不序列化 REPL 堆,也不在重启、恢复或派生后重新执行旧程序,因为重放自动化可能重复外部操作。缺失变量产生普通程序错误,模型指引要求重新创建变量并获取资源。提供方没有引入日志之外的模型输入,因此不需要环境标识或新的持久 Session 事件。
协议失败、输出超限、所有者销毁和进程退出都会丢弃环境。[中断决策](2026-10-29-retained-ptc-interruption.zh.md)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。
协议失败、所有者销毁和进程退出都会丢弃环境。[输出截断](2026-11-13-ptc-output-truncation.zh.md)负责限制输出而不丢弃状态。[中断决策](2026-10-29-retained-ptc-interruption.zh.md)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。
## 考虑过的替代方案
@@ -9,8 +9,8 @@
en: 32ba2b2b42e8deb5
zh: 6a6532561f81b8e2
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision:
en: 08a54b37e157da29
zh: 65f633055d9df242
en: 023c6db0af5f9424
zh: 7bdf40c49e381ee3
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered:
en: 6da221f6b821ea44
zh: b15774011abed7ed
@@ -13,7 +13,7 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md)
Each role of the web capability seam owns one part of a per-step check:
- **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`.
- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on the `deepseek-account` route, whether `ctx.deepseekAccount.resolveToken()` returns a token for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, a token for that route's `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the [shared credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts) perform these presence checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section.
- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.providerCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section.
- **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set.
The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured.
@@ -13,7 +13,7 @@ Status: implemented
web 能力 seam 的每个角色各负责逐步骤检查的一部分:
- **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。
- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `deepseek-account` 路由上检查 `ctx.deepseekAccount.resolveToken()` 是否为其 Messages 端点返回 token,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由 `/v1/tools` 基础地址的 token 算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由[共享凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。
- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.providerCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。
- **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。
路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。
@@ -18,8 +18,8 @@
en: 9d68ffca5c8be681
zh: 36bb661f98de0ebb
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution:
en: 15f6fb26c8605260
zh: 93467641a8ff0aad
en: aa5522b172d2c580
zh: 04561ffe78d69ff4
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections:
en: 5fcd3319fbceed1d
zh: 20771646b9c36fa6
@@ -30,11 +30,11 @@ The Search and Fetch APIs read one `web-deepseek-api` namespace, and each resolv
Each of Search and Fetch has a billing setting, `web-deepseek-api.searchBilling` or `fetchBilling`, which the settings page edits as a **Billing** menu under the selected API. The default, `auto`, follows the DeepSeek credential of the conversation; `account` sends only the signed-in account's token and `api-key` only the API key, without falling back to the other. The conversation's route is the `provider` of the initiating Session's latest request context, which account sign-out also reads; `ready()` uses the route of the model request being prepared, so readiness and execution resolve the same plan.
The account token is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the active `@deepseek-ai/dsh-llm-deepseek-account` Loader entry at the entry root that the model provider directory lists, with `/v1/tools`; without that entry, the origin of that route's default base URL is used. An HTTP 401 invalidates that token. With `auto` billing on the `deepseek-account` route, the operation sends the account token when that entry exists and a token is released. Every other `auto` operation, including one in an account conversation without a sign-in or a token, sends the key under the `apiKeyEnv` of the active `@deepseek-ai/dsh-llm-deepseek-api-key` entry for `deepseek-official`, resolved with that package's own resolver (including `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that entry, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route entry whose settings its resolver rejects is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint.
The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.providerCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint.
A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`fetchBaseURL` or `fetchApiKeyEnv` for Fetch) instead, whatever its billing, always sends the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) to its `*BaseURL` (the official base when unset) and never the account token, so an intranet or third-party endpoint receives only the key chosen for it. Each capability has its own fields because a deployment can serve search and fetch from different gateways. These fields are YAML-only, and an empty value counts as unset. Stored values of fields outside the schema, including `baseURL`, `apiKeyEnv`, and `apiKey`, load without schema errors and have no effect.
The [credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts) of `@deepseek-ai/dsh-llm-deepseek` read and validate API keys, check key presence, and release account tokens for the DeepSeek model routes, Messages search, and the Search and Fetch APIs, so every DeepSeek request reads the credential store the same way; the account model route, Messages search, and the Search and Fetch APIs also invalidate the token that an HTTP 401 rejects. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key.
The DeepSeek model routes publish the credential they send through `ctx.llm.providerCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key.
### Defaults and stored selections
@@ -30,11 +30,11 @@ Search 与 Fetch API 读取同一个 `web-deepseek-api` namespace,并各自解
Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` 或 `fetchBilling`,设置页在选中的 API 下方以**计费方式**下拉框编辑它。默认值 `auto` 跟随会话的 DeepSeek 凭据;`account` 只发送已登录账号的令牌,`api-key` 只发送 API 密钥,都不回退到另一种凭据。会话的路由是发起会话最近一次请求上下文的 `provider`,账号退出登录读取的也是它;`ready()` 使用正在准备的模型请求的路由,因此就绪判断与执行解析出相同的方案。
账号令牌是 `ctx.deepseekAccount` 为模型提供方目录列出的入口根部活动 `@deepseek-ai/dsh-llm-deepseek-account` Loader 条目的 origin 加 `/v1/tools` 下的请求端点给出的令牌;没有该条目时使用该路由默认基础地址的 origin。HTTP 401 会作废该令牌。`auto` 计费在 `deepseek-account` 路由上,若存在该条目且取得令牌,操作发送账号令牌。其他所有 `auto` 操作,包括账号会话中没有登录或没有令牌的操作,都把 `deepseek-official` 的活动 `@deepseek-ai/dsh-llm-deepseek-api-key` 条目的 `apiKeyEnv` 下的密钥(用该包自己的解析函数解析,包括 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该条目时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载、但其解析函数拒绝其设置的路由条目不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。
账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.providerCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。
在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。
`@deepseek-ai/dsh-llm-deepseek` 的[凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)为 DeepSeek 模型路由、Messages 搜索以及 Search 与 Fetch API 读取并校验 API 密钥、检查密钥是否存在、取得账号令牌,因此每个 DeepSeek 请求都以同一方式读取凭据库;账号模型路由、Messages 搜索以及 Search 与 Fetch API 还会作废被 HTTP 401 拒绝的令牌。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。
DeepSeek 模型路由通过 `ctx.llm.providerCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。
### 默认值与已保存的选择
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-06-connector-account-registry.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md
/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts:
en: 3950421fb526f6b7
zh: 47c5f6cc4b735058
/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/problem:
en: 2a7b59cd509a0b9a
zh: 38130ce17829342d
/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/decision:
en: d96b43106a1ba837
zh: 97bc8f9436ec07d0
/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/alternatives-considered:
en: ee0aa3f9ea40ef15
zh: fded69a6dcc8ca87
/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/consequences:
en: 5228f32becfbdec3
zh: 013f1073e70d46f7
@@ -0,0 +1,42 @@
# Agent Note: One Host registry and one browser half for connector accounts
Status: implemented
English | [中文](2026-11-06-connector-account-registry.zh.md)
## Problem
Connector plugins show an account section on the Plugins page. CLI app plugins keep the account in their vendor CLI; MCP connectors keep an OAuth grant through the MCP manager. Both kinds need the same surfaces: a bundle's section, title tag, and activation prompt, a confirmation before an action that changes the account outside DSH, and a notice in the browser that started the operation. A client plugin cannot share runtime code with another feature plugin ([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) rule 3), so one browser half per connector kind duplicates the same code and lets the copies drift. When the browser decides an account's state or relays an identifier from one Remote to another, the Host can no longer run the flow without the browser.
## Decision
[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.md) provides one Host registry, `ctx.connectorAccounts`, one `connectorAccounts` Remote, and one browser half for every connector kind.
| Part | Contract |
|---|---|
| Registration | `register({ key, packageName?, source, operations, copy, present })` returns the disposer that withdraws the account |
| Key | Unique among registered accounts and independent of the package, so an account that no bundle owns, such as a server configured in Settings, registers too |
| Package | Decides which bundle page carries the section and tag; a package carries at most one account |
| Source | The registrant's account: `snapshot`, `observe`, `refresh`, `start`, and `cancel` |
| Display | `present(view)` on the Host gives the phase, status text, title tag, buttons and their commands, confirmations, failure, and the operation the activation prompt starts |
| Remote | `watch`, plus `start(key, operation)` and `cancel(key, id)`, which route by key to the account's source |
The Host decides everything except opening the authorization page. The browser never learns how an account connects: it receives only the display, the operation in progress with its authorization page, and the latest result with its success text. The browser half keeps only what belongs to one browser: the operations it started, so their authorization pages open and their success is reported only there; the latest notice; and whether its stream is delivering. Buttons call `start` and `cancel` on the Remote themselves, and each surface keeps its own pending state.
The page registers one title tag entry and one notice entry. It also registers a section and an activation prompt for each account that names a package, because those two slots are keyed by package.
## Alternatives considered
**Two registries behind one browser half.** Rejected: the browser would follow both Remotes and choose which one each button calls, which relays between Host services again, and the two Host registries would hold the same code.
**One browser half per connector kind.** Rejected: client plugins cannot import each other's values, so the shared surfaces would be written twice and diverge.
**Share the browser half through `PLATFORM_MODULES` or a browser-side service.** Rejected: the module table is reserved for shell-seeded and static infrastructure libraries, and a browser-side service would keep the registrations in the browser, which only repeat what the Host knows.
**Let the browser derive an account's phase and actions from the registrant's raw state.** Rejected: the rules for which actions apply would live where the Host cannot test or run them, and the browser would need the registrant's own Remote.
## Consequences
The registry and browser half exist once. A new connector kind writes a source and `present` on the Host and needs no browser code. The account rules live beside the services that own them, and the Host can run every operation without a browser.
Registrants map their account states onto five phases (checking, connecting, connected, disconnected, unavailable); a state outside them shows through its status text and detail. The Web and Desktop compositions load the registry whether or not a connector plugin is installed. An authorization page that opens after the start call answers can be blocked by the browser; the section's open button shows it again.
@@ -0,0 +1,42 @@
# Agent Note:连接器账号使用一个 Host 注册表和一个浏览器一半
Status: implemented
[English](2026-11-06-connector-account-registry.md) | 中文
## 问题
连接器插件会在插件页显示账号区块。CLI 应用插件的账号保存在厂商 CLI 中;MCP 连接器通过 MCP 管理器保存 OAuth 授权。两类插件需要同样的界面:插件包的区块、标题旁标签和开启引导,在会改变 DSH 之外账号状态的操作前确认,以及只在发起操作的浏览器中显示的提示。客户端插件不能与其他功能插件共享运行时代码([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) 第 3 条),因此每类连接器各有一个浏览器一半,就会把同样的代码写两遍,副本还会逐渐不一致。如果由浏览器决定账号状态,或在两个 Remote 之间转发标识,Host 就无法在没有浏览器的情况下完成流程。
## 决定
[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.zh.md) 为所有连接器类型提供一个 Host 注册表 `ctx.connectorAccounts`、一个 `connectorAccounts` Remote 和一个浏览器一半。
| 部分 | 约定 |
|---|---|
| 注册 | `register({ key, packageName?, source, operations, copy, present })` 返回撤下账号的销毁函数 |
| 键 | 在已注册账号中唯一,且与包无关,因此没有插件包承载的账号(如在 Settings 中配置的服务器)也能注册 |
| 包 | 决定由哪个插件包页面承载区块和标签;一个包最多承载一个账号 |
| 来源 | 注册方的账号:`snapshot`、`observe`、`refresh`、`start` 和 `cancel` |
| 展示 | Host 上的 `present(view)` 给出阶段、状态文字、标题旁标签、按钮及其命令、确认、失败信息,以及开启引导启动的操作 |
| Remote | `watch`,以及按键路由到账号来源的 `start(key, operation)` 和 `cancel(key, id)` |
除了打开授权页,其余都由 Host 决定。浏览器不知道账号如何连接:它只收到展示内容、进行中的操作及其授权页,以及带成功文本的最新结果。浏览器一半只保存属于本浏览器的东西:它发起的操作(授权页只在这里打开,成功只在这里报告)、最新提示,以及它的流是否在推送。按钮自己调用 Remote 的 `start` 和 `cancel`,每个界面自己保存未完成状态。
页面只注册一个标题旁标签条目和一个提示条目;对每个带包名的账号,再注册一个区块和一个开启引导,因为这两个插槽以包为键。
## 考虑过的替代方案
**一个浏览器一半背后有两个注册表。** 否决:浏览器要同时跟随两个 Remote,并为每个按钮选择调用哪一个,这又是在 Host 服务之间转发;两个 Host 注册表的代码也会相同。
**每类连接器各有一个浏览器一半。** 否决:客户端插件不能导入彼此的值,共用界面就要写两遍,并逐渐不一致。
**通过 `PLATFORM_MODULES` 或浏览器端服务共享浏览器一半。** 否决:模块表只留给由 shell 预置的基础设施和静态库;浏览器端服务会把注册留在浏览器中,而这些注册只是重复 Host 已知的信息。
**由浏览器根据注册方的原始状态推算账号阶段和操作。** 否决:哪些操作可用的规则会放在 Host 无法测试和执行的地方,浏览器还需要注册方自己的 Remote。
## 后果
注册表和浏览器一半只有一份。新的连接器类型只需在 Host 上编写来源和 `present`,不需要浏览器代码。账号规则与拥有它们的服务在一起,Host 不依赖浏览器就能执行每个操作。
注册方需要把账号状态映射到五个阶段(检查中、连接中、已连接、未连接、不可用);超出这些阶段的状态通过状态文字和说明表达。无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。启动调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。
@@ -27,8 +27,8 @@
en: 0676f301d5aec364
zh: 0ef43eba7bfe2f01
/agent-note-authentication-provider-integration/testing:
en: c783cb006f9962a4
zh: 79bf36b25665e49c
en: 378fd2b4f826a453
zh: bf53037b7bdaa44e
/agent-note-authentication-provider-integration/alternatives-considered:
en: 868953274abd81e8
zh: 1b2890de876a6db6
@@ -118,7 +118,7 @@ Desktop's parent owns a fresh private credential per Host process and delivers i
| Provider registration | Only built-in BrowserAuth supplied network identity | Ordered independent verifiers select one live Peer; scope unload, verifier failure, and cancellation are covered by [authentication tests](../../../../packages/client/connection/tests/authentication.host.spec.ts) |
| HTTP and upgrade integration | Consumers called Connection admission | Route auth supplies the Peer once; real [Provider transport tests](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts) exercise both carriers |
| Server isolation | Route tables were per instance; index injection was root-wide | All five events use the WebServer subject; [server](../../../../packages/host/webserver/tests/event-isolation.host.spec.ts) and [application](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts) tests cover ordinary and global listeners and a preserved external Host |
| Browser OAuth return | The callback validated state and PKCE | The scoped pre-route callback retains validation and accepts real cross-site navigation; [account tests](../../../../packages/credentials/deepseek-account/tests/account.spec.ts) retain wrong-Host and SSH-forwarding coverage, and [Chromium](../../../../apps/web/tests/account-login.e2e.ts) asserts the actual Fetch Metadata header |
| Browser OAuth return | The callback validated state and PKCE | The scoped pre-route callback retains validation and accepts real cross-site navigation; [account tests](../../../../packages/account/deepseek-account/tests/account.spec.ts) retain wrong-Host and SSH-forwarding coverage, and [Chromium](../../../../apps/web/tests/account-login.e2e.ts) asserts the actual Fetch Metadata header |
| Startup output | WebApp printed/opened one Connection-produced login URL | [Startup tests](../../../../packages/bundle/web-app/tests/startup.host.spec.ts) cover ordered entries, first eligible opening, empty lists, readiness and SSH suppression |
| Desktop runtime consumers | A tokenized ready URL was exchanged for a Cookie | [Runtime smoke tests](../../../../apps/desktop/tests/smoke-runtime.spec.ts) use the private Cookie on the HTTP probes; [built Remote tests](../../../../packages/api/remotes/tests/built-lib.e2e.ts) collect the current Provider's entry and pass the admitted Peer |
@@ -118,7 +118,7 @@ Desktop 父进程为每个 Host 进程持有新私有凭据,并在 ready 前
| Provider 注册 | 只有内置 BrowserAuth 提供网络身份 | 有序独立验证器选择一个存活 Peer;[认证测试](../../../../packages/client/connection/tests/authentication.host.spec.ts)覆盖作用域卸载、验证故障和取消 |
| HTTP 与 upgrade 接入 | 消费者调用 Connection 准入 | 路由 auth 一次提供 Peer;真实 [Provider 传输测试](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts)覆盖两种载体 |
| 服务器隔离 | 路由表按实例持有,index 注入覆盖 root | 五个事件均使用 WebServer subject;[服务器](../../../../packages/host/webserver/tests/event-isolation.host.spec.ts)和[应用](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts)测试覆盖普通/global 监听器及保留的外部 Host |
| 浏览器 OAuth 返回 | 回调校验 state 与 PKCE | 有作用域的前置回调保留校验,并接受真实跨站导航;[账号测试](../../../../packages/credentials/deepseek-account/tests/account.spec.ts)保留错误 Host 和 SSH 转发覆盖,[Chromium](../../../../apps/web/tests/account-login.e2e.ts)断言实际 Fetch Metadata header |
| 浏览器 OAuth 返回 | 回调校验 state 与 PKCE | 有作用域的前置回调保留校验,并接受真实跨站导航;[账号测试](../../../../packages/account/deepseek-account/tests/account.spec.ts)保留错误 Host 和 SSH 转发覆盖,[Chromium](../../../../apps/web/tests/account-login.e2e.ts)断言实际 Fetch Metadata header |
| 启动输出 | WebApp 打印/打开一个 Connection 生成的登录 URL | [启动测试](../../../../packages/bundle/web-app/tests/startup.host.spec.ts)覆盖按序入口、首个可打开项、空列表、就绪和 SSH 抑制 |
| Desktop runtime 消费者 | 以带 Token 的 ready URL 交换 Cookie | [Runtime smoke 测试](../../../../apps/desktop/tests/smoke-runtime.spec.ts)在 HTTP 探针中使用私有 Cookie;[产物 Remote 测试](../../../../packages/api/remotes/tests/built-lib.e2e.ts)收集当前 Provider 入口,并传递准入 Peer |
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-10-llm-route-credential-seam.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse:
en: d11883f28d5cdd99
zh: 860795ae4d93c317
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/problem:
en: 9665e1879893fe76
zh: 9da30ad0be6fc38d
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision:
en: aaa2d2c7202408d4
zh: 134987da042fd07b
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered:
en: d6b2de393add9887
zh: b5351f9a49387bd6
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences:
en: df942606f0d31fa5
zh: cb1f21dd7f60ab7f
@@ -0,0 +1,47 @@
# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse
Status: implemented
English | [中文](2026-11-10-llm-route-credential-seam.zh.md)
## Problem
Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/dsh-llm-deepseek`, the protocol transport, exported helpers that read `ctx.credentials`, the launch environment, and `ctx.deepseekAccount`, so the transport depended on both credential services although it only sends the headers a route gives it. The two route plugins resolved their credentials through those helpers and threw their own missing-credential failures from inside `resolveAuth`. The Search and Fetch API providers re-derived each route's base URL and key reference from the Loader entry of the route package with that package's own config resolver, and Messages search hard-coded the account route id, so both web packages depended on `llm-deepseek`, on both route plugins, and on the Loader. The account service, which sits below every consumer, owned Agent cancellation after sign-out and lived in the `credentials/` group beside the credential store it only uses. A change to how one route authenticates touched the transport, both web providers, and their tests.
## Decision
`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.providerCredential(provider)` publishes a `ProviderCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request.
`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The transport runs each model request and its file operations under the grant's `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers.
The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. A request in flight at sign-out ends with its grant's `revoked` signal and fails as `ACCOUNT_SIGN_IN_REQUIRED`, and its failure callback cancels the same Agents, so a request that outlives the plugin still ends its turn with the signed-out cause.
`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name.
The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service.
## Alternatives considered
**A `deepseek-auth` package holding the credential seam.** The seam needs a Service Definition only, no Cordis service, and that one Definition role belongs beside `LlmAdapter`; a package for an interface adds a dependency without an owner of behavior.
**A credential fingerprint in the published credential.** Consumers only send requests, so they need headers and a value; cache scoping by credential is the adapter's own concern, which the listing cache meets by hashing the headers it sends.
**A `credentials-env` provider instead of reference helpers.** A provider that reads the environment would change which composition is authoritative for every consumer; the helpers keep the launch-environment fallback local to the consumers that need it, so such a provider remains an independent option.
**The account service's inference origin for the web fallback without the account route.** Routing that fallback through `DEEPSEEK_BASE_URL` keeps the keyless billing snapshot and every documented deployment unchanged; the account service still refuses every origin but its own.
**Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own.
**Keeping the route plugin's sign-out listener until its tasks end.** Unloading the route then waits for a running turn: disabling the plugin blocks, and every other settings write queues behind that reload, for as long as the turn runs.
**Cancelling the route's tasks when the route unloads.** A configuration reload or a plugin update would stop turns that no sign-out touched.
**Returning the sign-out policy to the account service.** The service would again inspect Agents and know route ids, the dependencies this decision removes.
**Keeping the route's listener or report registered after its plugin unloads.** A registration that outlives the plugin that made it breaks the rule that registrations are effects of their owner, and leaves code of an unloaded plugin running in another scope for as long as the task runs.
## Consequences
Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `providerCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`.
A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns.
@@ -0,0 +1,47 @@
# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse
Status: implemented
[English](2026-11-10-llm-route-credential-seam.md) | 中文
## 问题
多个包共用同一份 DeepSeek 凭据,却没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,Messages 搜索则硬编码账号路由 id,因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。
## 决策
`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.providerCredential(provider)` 发布一个 `ProviderCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。
`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。
路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。
`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token、`reject()` 和 `revoked` 信号;`reject()` 仅在授权仍一致时删除它并隔离存储失败,`revoked` 由服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。
Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。
## 考虑过的替代方案
**用一个 `deepseek-auth` 包承载凭据 seam。** 该 seam 只需要 Service Definition,不需要 Cordis 服务,而这一个 Definition 角色应与 `LlmAdapter` 放在一起;为一个接口建包只会增加一个没有行为所有者的依赖。
**在发布的凭据中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头和值;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。
**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。
**没有账号路由时的 Web 后备使用账号服务的推理 origin。** 让该后备经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。
**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。
**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。
**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。
**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。
**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。
## 后果
新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `providerCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。
退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-13-ptc-output-truncation.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md
/agent-note-ptc-output-truncation-without-execution-cancellation:
en: 781fba10ab5fcd45
zh: 88276a5a9cdf8c19
/agent-note-ptc-output-truncation-without-execution-cancellation/problem:
en: a6430b7910bebaa2
zh: dff6c3553e22283e
/agent-note-ptc-output-truncation-without-execution-cancellation/decision:
en: b24a08b0037adab4
zh: 92fb390a0e460ba5
/agent-note-ptc-output-truncation-without-execution-cancellation/alternatives-considered:
en: 717295afe374b2e5
zh: cf4fd1365169f9e3
/agent-note-ptc-output-truncation-without-execution-cancellation/consequences:
en: 420e2556a878b48a
zh: bff5f63189562d57
@@ -0,0 +1,25 @@
# Agent Note: PTC output truncation without execution cancellation
Status: implemented
English | [中文](2026-11-13-ptc-output-truncation.zh.md)
## Problem
Stopping a program because its logs exceed the output budget can interrupt a sequence of external actions. Earlier effects remain, but the caller cannot tell which later actions ran. Repeating the program to obtain less output can repeat those effects. A full log budget can also hide a subsequent exception by replacing its kind with an output-limit failure.
## Decision
Captured output has bounded retention. Exhaustion preserves an ordered prefix, discards subsequent output and sets `outputTruncated`; it does not cancel execution or discard retained variables. Existing deadlines, cancellation, heap limits and control-message limits still apply. Finalization prioritizes the required completion value or bounded failure diagnostic within the combined payload budget. Truncated diagnostics preserve their failure kind. Required completion values remain lossless and fail if they cannot fit.
This supersedes only captured-output termination and diagnostic reclassification in [typed tool returns](../feature/2026-07-20-ptc-typed-tool-returns.md), and overflow-driven state disposal in [retained PTC](2026-09-23-best-effort-persistent-ptc.md). Those records still own lossless values and retained-state lifetime; [explicit output](2026-11-09-explicit-ptc-output.md) still owns inspection and image projection.
## Alternatives considered
**Terminate on output exhaustion.** It limits output production earlier, but turns a presentation limit into interrupted external work without rollback.
**Return success with a truncated completion value.** It violates the caller's requirement for complete JSON data. Only captured output and diagnostic text may be shortened.
## Consequences
Successful truncated runs remain successful tool results. Callers inspect current state for missing information instead of replaying completed actions. Output suppression does not bound allocations in argument evaluation or native code; existing resource controls retain that responsibility. Tests cover subsequent actions, retained variables, initialization, ordered images, byte limits and later exceptions, deadlines and cancellation.
@@ -0,0 +1,25 @@
# Agent Note: PTC 输出截断不取消执行
Status: implemented
[English](2026-11-13-ptc-output-truncation.md) | 中文
## 问题
因日志超出输出预算而停止程序,可能打断一系列外部动作。此前的效果仍然保留,但调用方无法判断后续哪些动作已经执行。为了减少输出而重跑程序,可能重复这些效果。日志预算耗尽还可能使后续异常被替换成输出超限失败,掩盖真实类型。
## 决策
捕获输出采用有界保留。预算耗尽时保留有序前缀,丢弃后续输出并设置 `outputTruncated`,但不取消执行或丢弃保留变量。原有截止时间、取消、堆限制和控制消息限制继续生效。最终结算在组合负载预算内优先保留必需完成值或有界失败诊断。截断诊断保留原来的失败类型。必需完成值保持无损,无法容纳时仍然失败。
本决策只取代[类型化工具返回值](../feature/2026-07-20-ptc-typed-tool-returns.zh.md)中的捕获输出超限终止和诊断重新分类,以及[保留状态 PTC](2026-09-23-best-effort-persistent-ptc.zh.md)中的超限清空状态规则。这些记录仍负责无损值和保留状态生命周期;[显式输出](2026-11-09-explicit-ptc-output.zh.md)仍负责检查展示与图片投影。
## 考虑过的替代方案
**输出耗尽时终止。** 能更早限制输出生产,但将展示限制变成没有回滚的外部工作中断。
**截断完成值后返回成功。** 违反调用方对完整 JSON 数据的要求。只有捕获输出和诊断文本可以缩短。
## 后果
成功但输出截断的执行仍是成功工具结果。调用方读取当前状态以获取遗漏信息,不重放已完成动作。输出抑制不限制参数求值或原生代码中的分配,这仍由现有资源控制负责。测试覆盖后续动作、保留变量、初始化、有序图片、字节上限以及后续异常、截止到期和取消。
@@ -9,11 +9,11 @@
en: c389c332bdadbbe4
zh: 217520278ccf0932
/agent-note-unambiguous-tool-argument-compatibility/decision:
en: 71c04efcfd972b02
zh: d1f842920b1b0e3f
en: c6ac657b3875c95f
zh: 7b0a4cca7baafd03
/agent-note-unambiguous-tool-argument-compatibility/alternatives-considered:
en: b2a96695819a978f
zh: c6f84b244be0dddf
/agent-note-unambiguous-tool-argument-compatibility/consequences:
en: bd24ad737c617c90
zh: dbb7fa67c41af828
en: 7d21da549466232c
zh: a373e135f79c5423
@@ -10,7 +10,7 @@ Models can populate optional fields that do not affect the requested operation.
## Decision
`grep` treats an exact empty `include` as omitted. Whitespace-only, negated, and comma-separated filters remain invalid. `update_goal` uses replacement fields only for `edit` and a blocker reason only for `blocked`; other actions ignore those known fields. Declared types, consumed values, authority, and exact revisions remain validated. Ignored fields never reach another goal operation or change unrelated state, and call summaries select only values used by the action. `write` and `edit` allow absent or blank justification when no sandbox mode is requested or the effective mode is repeated; actual widening retains its reason and approval requirements, and filesystem observation and denial checks remain active.
`grep` treats an exact empty `include` as omitted. Whitespace-only, negated, and comma-separated filters remain invalid. `update_goal` uses replacement fields only for `edit` and a blocker reason only for `blocked`; other actions ignore those known fields. Declared types, consumed values, authority, and exact revisions remain validated. Ignored fields never reach another goal operation or change unrelated state, and call summaries select only values used by the action. `write` and `edit` allow absent or blank justification when no sandbox mode is requested or the effective mode is repeated; actual widening retains its reason and approval requirements, and filesystem observation and denial checks remain active. `subagent` and `list_subagent_models` treat an exact empty `provider`, `model`, or `reasoning_effort` as omitted; an empty subagent `name` remains invalid because its error states the accepted format.
This partially supersedes the unused-field rejection in the [goal-tool decision](../feature/2026-07-19-model-facing-goal-tools.md). Its authority, lifecycle, scheduling, and persistence decisions remain active. The rules apply to every provider and stay inside the owning tool rather than weakening its underlying service.
@@ -22,4 +22,4 @@ This partially supersedes the unused-field rejection in the [goal-tool decision]
## Consequences
The tools accept these calls without extra mutations. Unit tests cover ignored fields for every goal action, consumed-field and authority failures, stale revisions, filter validation, and real search results. A headless recorded-session scenario verifies both file extensions are searched and completion preserves the original objective and round cap. These rules give up detecting conflicting intent expressed only in inactive goal fields; they do not weaken authorization or establish a generic coercion policy.
The tools accept these calls without extra mutations. Unit tests cover ignored fields for every goal action, consumed-field and authority failures, stale revisions, filter validation, and real search results. A headless recorded-session scenario verifies both file extensions are searched and completion preserves the original objective and round cap. An SDK recorded-session scenario verifies that empty route fields start a subagent on its default route. These rules give up detecting conflicting intent expressed only in inactive goal fields; they do not weaken authorization or establish a generic coercion policy.
@@ -10,7 +10,7 @@ Status: implemented
## 决策
`grep` 将值恰好为空字符串的 `include` 视为省略。仅含空白、否定形式和逗号分隔的过滤器仍然无效。`update_goal` 仅在 `edit` 时使用替换字段,仅在 `blocked` 时使用阻塞原因;其他 action 忽略这些已知字段。声明的类型、实际使用的值、权限和精确修订号仍会校验。被忽略的字段不会传入另一种目标操作,也不会改变无关状态;调用摘要仅选择当前 action 使用的值。未请求沙箱模式或重复当前生效模式时,`write` 和 `edit` 允许省略理由或提供空白理由;真正升权仍需理由和审批,文件系统观察与拒绝检查继续生效。
`grep` 将值恰好为空字符串的 `include` 视为省略。仅含空白、否定形式和逗号分隔的过滤器仍然无效。`update_goal` 仅在 `edit` 时使用替换字段,仅在 `blocked` 时使用阻塞原因;其他 action 忽略这些已知字段。声明的类型、实际使用的值、权限和精确修订号仍会校验。被忽略的字段不会传入另一种目标操作,也不会改变无关状态;调用摘要仅选择当前 action 使用的值。未请求沙箱模式或重复当前生效模式时,`write` 和 `edit` 允许省略理由或提供空白理由;真正升权仍需理由和审批,文件系统观察与拒绝检查继续生效。`subagent` 和 `list_subagent_models` 将值恰好为空字符串的 `provider`、`model` 或 `reasoning_effort` 视为省略;空的 subagent `name` 仍然无效,因为其报错会说明可接受的格式。
本决策部分取代[目标工具决策](../feature/2026-07-19-model-facing-goal-tools.zh.md)中对无关字段的拒绝规则。其权限、生命周期、调度和持久化决策继续生效。这些规则适用于所有提供方,并保留在所属工具内,不削弱底层服务的校验。
@@ -22,4 +22,4 @@ Status: implemented
## 后果
工具接受这些调用,且不会产生额外变更。单元测试覆盖每种目标 action 对无关字段的忽略、有效字段与权限失败、陈旧修订号、过滤器校验以及真实搜索结果。headless 会话回放验证两种扩展名的文件都参与搜索,并且完成操作保留原始目标和轮数上限。这些规则放弃检测仅由非当前 action 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。
工具接受这些调用,且不会产生额外变更。单元测试覆盖每种目标 action 对无关字段的忽略、有效字段与权限失败、陈旧修订号、过滤器校验以及真实搜索结果。headless 会话回放验证两种扩展名的文件都参与搜索,并且完成操作保留原始目标和轮数上限。SDK 会话回放验证空路由字段会让 subagent 按默认路由启动。这些规则放弃检测仅由非当前 action 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-13-draft-attachments-across-session-switches.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/bug-fix/2026-11-13-draft-attachments-across-session-switches.md
/agent-note-draft-attachments-across-session-switches:
en: 2a1645c8c80d6dff
zh: 59277c3754231479
/agent-note-draft-attachments-across-session-switches/problem:
en: 3f4030763e1f0105
zh: c8a0bc5641d7bed4
/agent-note-draft-attachments-across-session-switches/decision:
en: 40697e88c2ed6ca8
zh: eeb363374b25c3a2
/agent-note-draft-attachments-across-session-switches/alternatives-considered:
en: 2c43ad479f4a3577
zh: 07743f45870eb0fe
/agent-note-draft-attachments-across-session-switches/consequences:
en: 6ac6defa552ea040
zh: aa64a3c3e54dbebc
@@ -0,0 +1,25 @@
# Agent Note: Draft attachments across Session switches
Status: implemented
English | [中文](2026-11-13-draft-attachments-across-session-switches.zh.md)
## Problem
Switching to another Session and back emptied the composer's attachment rail while its text survived (issue #5070). The Session scope disposer released every attachment the retiring composer held and revoked image previews, and nothing could rebuild them.
## Decision
**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A message the Host accepts leaves that ownership at once, while the registry keeps its attachments until the echo settles them. A retiring composer releases its attachments only when its Session was removed or a message or command was already submitted, because the Client cannot tell whether a submitted command consumed them; an aborted slash-line adjudication keeps them. Otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed.
**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session that still owns draft attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark and no registered attachments shows the "add them again" notice.
## Alternatives considered
**Restoring attachments after a reload from durable browser references and a Host `restore` Remote.** It would bring uploaded files and images back after a page reload, but it needs a Host Remote with its Liveshare and catalog classifications, a persisted browser format, a send gate during restoration, and an image byte payload. Desktop, where most users work, gains little: its Host binds a new port on every launch, so its storage origin, and with it every saved reference, does not survive an application restart.
**Releasing settled attachments on a switch and restoring them from the Host on return.** It would save the memory of pasted images while a Session is not shown, but every return needs a Host round trip, fails on a weak network, and allocates the same bytes again.
## Consequences
Switching never touches the Host, so a weak network cannot lose a draft attachment there. A reload or crash still discards attachments; a crash writes no mark and so shows no notice.
@@ -0,0 +1,25 @@
# Agent Note:草稿附件跨会话切换
Status: implemented
[English](2026-11-13-draft-attachments-across-session-switches.md) | 中文
## 问题
切到另一个会话再切回时,输入框的附件栏被清空,文字却还在(issue #5070)。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。
## 决策
**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。Host 接受消息时,这些附件立即退出会话归属,注册表则保留它们直到回显结算。退役的输入框只在其会话已被删除、或消息与命令已经提交时释放附件,因为客户端无法判断已提交的命令是否用掉了附件;被中止的斜杠行裁决会保留附件。其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。
**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个仍持有草稿附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记且没有已登记附件的输入框,会显示「请重新添加」提示。
## 考虑过的替代方案
**刷新后通过浏览器 durable 引用与 Host `restore` Remote 恢复附件。** 它能在页面刷新后找回已上传的文件和图片,但需要新增一个 Host Remote 及其 Liveshare 与目录分类、一种浏览器持久化格式、恢复期间的发送拦截和图片字节载荷。主要用户所在的桌面端收益很小:桌面端 Host 每次启动都绑定新端口,存储 origin 连同所有已存引用都无法跨应用重启保留。
**切换时释放已结算附件,切回时由 Host 恢复。** 它能在会话不显示期间省下粘贴图片的内存,但每次切回都需要一次 Host 往返,弱网下会失败,并且之后还要再分配同样的字节。
## 影响
切换会话从不访问 Host,因此弱网不会让草稿附件在切换中丢失。刷新或崩溃仍会丢弃附件;崩溃时不会写标记,因此没有提示。
@@ -18,8 +18,8 @@
en: 8b10f08e67ca9323
zh: e57adb520049f407
/agent-note-typed-tool-returns-in-ptc-mode/decision/outer-result-and-output-ledger:
en: e48ef4dbe1ac9a1e
zh: b87b0c0a3f1c2a4e
en: f6fb803d2dc061bb
zh: 05432104d5876f99
/agent-note-typed-tool-returns-in-ptc-mode/decision/typed-handles-and-lifetime:
en: b2b9318c2812e3a4
zh: 73cf34bfd487e2f1
@@ -33,8 +33,8 @@
en: 069a1e170c7d1dfb
zh: 14ce5a56e602595c
/agent-note-typed-tool-returns-in-ptc-mode/consequences:
en: f5726b5e7a2fc73f
zh: 0b9aa884db5d920f
en: 16cb8d972867b62f
zh: d253114975e96fe8
/agent-note-typed-tool-returns-in-ptc-mode/known-limitations-and-deferred-work:
en: 19828c2e5796df2d
zh: 2ef63df81fca7a72
@@ -59,9 +59,9 @@ Ordinary binding arguments and JSON resolutions are revalidated as lossless JSON
Runtime consumers that retain completions receive exact lossless JSON: `undefined` omits the completion and `null` is an explicit result. TypeScript `run_code` requests completion discard and returns captured logs plus optional sandbox facts as its canonical value; selected images enter its rendered content separately.
`NodePtcRuntime` replaces the former independent log and value caps with configurable `maxOutputBytes`, defaulting to `67_108_864` bytes. The worker charges captured logs by their exact JSON-string serialization and preflights the detached completion or program exception against the remaining combined budget before posting a terminal message. A giant thrown string or stack therefore crosses the worker port only as the fixed `output-limit` diagnostic. The host repeats the hostile-peer ledger for forged traffic and native pipe writes the worker cannot observe. Fixed `PtcRunResult` field names, braces, the bounded error-kind tag, and later presentation whitespace are deliberately outside this variable-payload ledger. Neither stage materializes an over-limit serialized completion. A result at or below the cap is exact. A completion that cannot survive lossless JSON snapshotting fails as `invalid-output`; a value, diagnostic, or combined outcome over the cap fails as `output-limit` rather than becoming inspected or truncated text.
`NodePtcRuntime` uses the configurable `maxOutputBytes` combined payload budget, defaulting to `67_108_864` bytes. Required completion values remain lossless JSON: unsupported values fail with `invalid-output`, and values that cannot fit fail with `output-limit`. The [output-truncation decision](../architecture/2026-11-13-ptc-output-truncation.md) owns captured-output retention and diagnostic priority. Fixed `PtcRunResult` field names, braces, bounded metadata and later presentation whitespace remain outside this variable-payload ledger. The host validates untrusted process traffic and native pipe writes independently; neither side serializes oversized completions.
Logs stream eagerly so a terminated run can retain output already admitted. Native stdout and stderr writes that bypass the worker's patched stream slots use independent pipes, so terminal settlement continues bounded capture until worker termination completes before materializing the result. When the cap is crossed, the runtime returns an explicit bounded failure with the fitting captured prefix. That outer result then traverses the ordinary `run_code` rendering and spill policy, which may save the captured text and expose its configured head/tail preview. The spill layer cannot recover bytes the runtime rejected beyond the hard cap.
Logs stream eagerly so a terminated run can retain output already admitted. Native stdout and stderr writes that bypass the worker's patched stream slots use independent pipes, so terminal settlement continues bounded capture until worker termination completes before materializing the result. When the cap is crossed, captured output is truncated to a fitting prefix and marked with `outputTruncated`, while execution continues. Finalization reserves the required completion or diagnostic budget before retaining output; only a required completion that cannot fit causes `output-limit`. That outer result then traverses the ordinary `run_code` rendering and spill policy, which may save the captured text and expose its configured head/tail preview. The spill layer cannot recover bytes the runtime rejected beyond the hard cap.
Compute time, wall time, worker heap, cancellation, and fresh-worker isolation remain independent limits. The outer ledger never charges intermediate bindings, so snapshotting, flat-wire encoding and decoding, structured-clone cost, and available process or worker memory are their practical bounds.
@@ -101,7 +101,7 @@ Keyless real-worker integration tests pin the two handle workflows that prose re
Code programs can compose tools through stable values instead of reverse-engineering Native prose. Native mode retains its existing text and UI presentation, while PTC mode receives output-schema types and exact runtime JSON. Tool authors must treat the canonical value as their programmatic API and put display-only formatting in the renderer.
The worker performs bounded-depth flat-wire transport and lossless validation but does not make intermediate values cheap or durable. Outer overflow is an explicit failed run, and error handling remains intentionally human-guided rather than a versioned code union.
The worker performs bounded-depth flat-wire transport and lossless validation but does not make intermediate values cheap or durable. An oversized required completion is an explicit failed run, and error handling remains intentionally human-guided rather than a versioned code union.
## Known Limitations and Deferred Work
@@ -59,9 +59,9 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
保留完成值的运行时消费方接收精确无损 JSON:`undefined` 省略完成值,`null` 是显式结果。TypeScript `run_code` 请求丢弃完成值,将捕获日志和可选沙箱信息作为规范值返回;所选图片单独进入渲染内容。
`NodePtcRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `PtcRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。
`NodePtcRuntime` 使用可配置的 `maxOutputBytes` 组合负载预算,默认值为 `67_108_864` 字节。必需完成值保持无损 JSON:不支持的值以 `invalid-output` 失败,无法容纳的值以 `output-limit` 失败。[输出截断决策](../architecture/2026-11-13-ptc-output-truncation.zh.md)负责捕获输出保留和诊断优先级。固定的 `PtcRunResult` 字段名、花括号、有界元数据和后续展示空白仍不计入可变负载账本。宿主独立校验不可信进程通信和原生管道写入;两端都不会序列化过大的完成值。
日志会在产生时立即流出,因此运行被终止时仍可保留已经纳入额度的输出。绕过 worker 中已改写流写入入口的原生 stdout 和 stderr 写入会经由彼此独立的管道传输,因此运行时在终态结算期间仍会继续在上限内捕获输出,直至 worker 完全终止,然后才组装结果。超过上限后,运行时会返回一个显式的有界失败,并携带可容纳的已捕获前缀。该外层结果随后通过普通的 `run_code` 渲染与 spill 策略;策略可以保存已捕获的文本,并暴露其配置指定的头尾预览。spill 层无法恢复运行时在硬上限之外拒绝的字节。
日志会在产生时立即流出,因此运行被终止时仍可保留已经纳入额度的输出。绕过 worker 中已改写流写入入口的原生 stdout 和 stderr 写入会经由彼此独立的管道传输,因此运行时在终态结算期间仍会继续在上限内捕获输出,直至 worker 完全终止,然后才组装结果。超过上限后,捕获输出会截断为可容纳的前缀并标记 `outputTruncated`,执行继续。最终结算先为必需完成值或诊断预留预算,再保留输出;只有无法容纳的必需完成值才会导致 `output-limit`。该外层结果随后通过普通的 `run_code` 渲染与 spill 策略;策略可以保存已捕获的文本,并暴露其配置指定的头尾预览。spill 层无法恢复运行时在硬上限之外拒绝的字节。
计算时间、墙钟时间、worker 堆内存、取消和每次运行使用全新 worker 的隔离仍是互相独立的限制。外层账本从不计入中间绑定值,因此生成快照、扁平协议格式的编码与解码、结构化克隆开销,以及进程或 worker 的可用内存构成了这些值的实际边界。
@@ -101,7 +101,7 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
PTC mode 程序可以通过稳定值组合工具,无需逆向解析 Native 自然语言。Native mode 保留现有文本与 UI 展示,PTC mode 则获得输出 schema 类型和精确的运行时 JSON。工具作者必须把规范值视为程序化 API,并将仅用于展示的格式化放入渲染器。
worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。外层输出溢出会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。
worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。必需完成值超限会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。
## 已知限制与暂缓事项
@@ -9,8 +9,8 @@
en: 344bcc7e9825bbc8
zh: c1d0f4b54f5b3786
/agent-note-change-request-panel-and-worktree-sessions/decision:
en: 4695a1e4f8aa7a25
zh: e17be0e36ea3eaa3
en: a2da424833a8aa0a
zh: 9ab23d2e5bde31de
/agent-note-change-request-panel-and-worktree-sessions/deferred:
en: 32ef8af85f4d2f66
zh: b82b67f94346399e
@@ -10,7 +10,7 @@ English | [中文](2026-10-09-forge-panel.zh.md)
## Decision
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) is a two-face package. Its Host half, the `forgePanel` Remote, assembles everything the panel shows for one Session into one streamed state; the forge registry and the binding service keep only their domain operations. Its Client half is a right-sidebar tab, a Session header button that shows or hides it, a New Session option, a creation card above the composer, a toast, and the [Session list icons and hover card section](2026-10-20-forge-session-list.md). Every surface calls a bound item a change request, the forge registry's term, whatever its code host calls it. The [forge bundle](../../../../packages/experimental/forge-bundle/README.md) ships the panel, the forge registry, the GitHub provider, the bindings, the worktree model tool, and an isolated worktree service for the panel as one default-disabled Plugins page entry.
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) is a two-face package. Its Host half, the `forgePanel` Remote, assembles everything the panel shows for one Session into one streamed state; the forge registry and the binding service keep only their domain operations. Its Client half is a Change requests section, checkout and local changes rows, and an attention mark in the [Session panel](2026-11-05-session-panel.md), a changes view, a New Session option, a creation card above the composer, a toast, and the [Session list icons and hover card section](2026-10-20-forge-session-list.md). Every surface calls a bound item a change request, the forge registry's term, whatever its code host calls it. The [forge bundle](../../../../packages/experimental/forge-bundle/README.md) ships the panel, the forge registry, the GitHub provider, the bindings, the worktree model tool, and an isolated worktree service for the panel as one default-disabled Plugins page entry.
Review and worktree controls serve one code-change workflow. One Plugins entry lets users enable that workflow without having to distinguish the underlying package split. Packages and the two worktree services remain independent so each owns its before-Session or in-conversation creation flow.
@@ -10,7 +10,7 @@ Status: implemented
## Decision
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 是一个双端包。宿主端的 `forgePanel` Remote 把面板为一个 Session 展示的全部内容组装成一条流式状态;forge 注册表与绑定服务只保留各自的领域操作。客户端包括一个右侧边栏标签页、一个显示或隐藏它的 Session 标题栏按钮、一个新会话选项、一张位于输入框上方的创建卡片、一个 toast,以及[会话列表中的图标与悬浮卡片部分](2026-10-20-forge-session-list.zh.md)。所有界面都把已绑定的条目称为变更请求(forge 注册表的术语),不随代码托管平台的叫法变化。[forge 套件](../../../../packages/experimental/forge-bundle/README.zh.md)把面板、forge 注册表、GitHub 提供方、绑定服务、工作树模型工具与面板使用的一个隔离 worktree 服务作为插件页中默认禁用的一个条目发布。
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 是一个双端包。宿主端的 `forgePanel` Remote 把面板为一个 Session 展示的全部内容组装成一条流式状态;forge 注册表与绑定服务只保留各自的领域操作。客户端包括[会话面板](2026-11-05-session-panel.zh.md)中的“变更请求”分栏、检出行与本地变更行和提醒标记,以及一个变更视图、一个新会话选项、一张位于输入框上方的创建卡片、一个 toast,以及[会话列表中的图标与悬浮卡片部分](2026-10-20-forge-session-list.zh.md)。所有界面都把已绑定的条目称为变更请求(forge 注册表的术语),不随代码托管平台的叫法变化。[forge 套件](../../../../packages/experimental/forge-bundle/README.zh.md)把面板、forge 注册表、GitHub 提供方、绑定服务、工作树模型工具与面板使用的一个隔离 worktree 服务作为插件页中默认禁用的一个条目发布。
评审与工作树控件服务于同一个代码修改流程。统一插件入口让用户可以一次启用这些能力,无需根据底层包的拆分判断应该开启哪张卡片。包与两套工作树服务仍保持独立,分别负责会话开始前和对话中创建工作树的流程。
@@ -27,8 +27,8 @@
en: 0dcc97d8105fab60
zh: d80d40ae3a0c601d
/agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered:
en: 907e0b8424943d43
zh: f45e583e7cb4eb63
en: 021a4b08ad534b36
zh: e98e1f65e50a568b
/agent-note-direct-deepseek-search-and-fetch-apis/consequences:
en: 7ec21c5b1124e5f8
zh: af769dbdb4face9f
@@ -52,7 +52,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request
**Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider.
**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the shared [`llm-deepseek` credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts); Messages search and the Search/Fetch API transports remain independent.
**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.providerCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent.
**Split Search and Fetch into separate packages.** The guide serves both APIs from one base with one credential; separate packages would duplicate settings that address one deployment. Independent selection does not require separate packages, because each API registers its own provider id. Each operation lives in its own module, so either API can change without the other.
@@ -52,7 +52,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek
**把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。
**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为通过共享的 [`llm-deepseek` 凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)获取;Messages 搜索与 Search/Fetch API 传输层保持独立。
**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.providerCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。
**把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。
@@ -0,0 +1,28 @@
# Bilingual-pair consistency record for 2026-11-05-session-panel.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-05-session-panel.md
/agent-note-session-panel-in-the-chat-view-s-end-gutter:
en: 1dc9957a0c9336e0
zh: 88d41c8490c2710c
/agent-note-session-panel-in-the-chat-view-s-end-gutter/problem:
en: c69d9843bc6f0b87
zh: c31bb1b2b4d9b781
/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision:
en: c2ddf417ea56b626
zh: 44c30091ade7e5bf
/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision/docking-follows-the-transcript-gutter:
en: 8a97ac8ac0b40d0c
zh: d42fe9c23b9dcd79
/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision/sections-are-registrations-the-panel-draws-titles:
en: 783b146c3396bebb
zh: 0f71205fdb744961
/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision/the-turn-rail-sits-at-the-start-edge:
en: 08e720a4ea75d4d6
zh: 5e2e5b8452f67d36
/agent-note-session-panel-in-the-chat-view-s-end-gutter/alternatives-considered:
en: 6adaf7a36da05668
zh: c0ace7297995d764
/agent-note-session-panel-in-the-chat-view-s-end-gutter/consequences:
en: 0b6e547a08c042bc
zh: 154a69e3f54692cd
@@ -0,0 +1,52 @@
# Agent Note: Session panel in the Chat View's end gutter
Status: implemented
English | [中文](2026-11-05-session-panel.zh.md)
## Problem
Facts about the current Session — its project directory, the change requests it opened, and later its outputs — had no common home. Each owner added its own Session header button and, for anything larger than a menu, a right-sidebar tab: the forge change requests are one such tab. A sidebar tab takes width from the transcript while it shows, shows one tab at a time, and leaves the facts one click away from every message. The required surface is a summary the user can keep beside the conversation without covering it, that several plugins fill independently, that hides when there is no room, and that the user can show or hide from the Session header.
## Decision
[`dsh-client-ui-session-panel`](../../../../packages/client/ui-session-panel/README.md) adds a Session header toggle (`conversation.session.header.utilities`, order −10) and a floating panel that occupies `conversation.chat.aside`, a slot that [`ui-chat`](../../../../packages/client/ui-chat/README.md#scroll-ownership) renders in the Chat View beside the turn rail. The aside is a zero-height layer at the top of the Chat frame and, like the turn rail, is sticky inside the shared scrollport: the panel does not scroll with the transcript, inherits the scrollport's composer and viewport heights, and needs no seat in the Conversation shell. Views other than Chat show no panel.
### Docking follows the transcript gutter
The panel docks only while the gutter between the transcript column and the Chat frame's end edge can hold it (348px: 40px clear of the column and its width handle, a 300px minimum width, and an 8px margin). The gutter, not the viewport width, decides because the column width is adaptive and user-draggable and the right sidebar shares the frame: the same viewport can leave 75px or 600px. The Chat View owns the frame and the transcript column, so its aside layer publishes the gutter as the `--dsh-chat-aside-gutter` custom property, and the panel's stylesheet sizes the docked panel from it.
Script still needs the decision, because docked and overlay differ in behavior and not only in size: the toggle reports `aria-expanded` truthfully and knows whether a press flips docking or opens the overlay, the overlay closes on Escape and on outside presses and returns focus, and an open overlay closes once the panel can dock. A CSS-only container query cannot tell an element outside the Chat View, or a listener, any of that. The stylesheet therefore computes the decision as well: each mounted panel renders a zero-height dock probe that is 1px wide from the gutter that holds the panel's minimum width and 0 below it, derived from the same metrics as the docked width, and the plugin observes only that probe. It hears the decision flip; observing the frame and the transcript column would call back on every frame of a streamed reply, because the column's height changes with its content, and on every step of a window resize. A Session has room to dock while any of its probes does, and a Session without a probe shows no Chat View. The toggle and the panel decide the presentation with the same pure function. While no Chat View shows the Session, as in the trajectory View, the toggle is unavailable and its tooltip asks for the Chat view; `ui-conversation` keeps View selection inside its shell, so the toggle does not switch Views itself.
Docking follows one persisted preference shared by every Session and defaults to on. Without room, a press opens a transient overlay for that Session above the transcript; it never changes the preference, and it closes once its gutter can dock the panel or no Chat View shows the Session any longer, so it never reappears on its own. The panel state follows the reported gutter of the open overlay's Session. A panel withdraws its report when it unmounts or its Chat View moves to another Session, in a layout-effect cleanup kept apart from the gutter update, so a changed gutter never reads as an unmount. Hiding automatically and overlaying on request keeps the transcript uncovered without making the facts unreachable on laptop widths.
### Sections are registrations; the panel draws titles
Each section is one list registration with `id`, `order`, and a required `label`. The panel projects the live registrations into titles, draws each title, and renders the section body with `renderSlot(..., { only: id })`; a CSS `:has()` rule hides a section whose body rendered nothing, so a section opts out by rendering nothing and no effect reports visibility to the owner. Trailing title controls are a keyed slot addressed by the section `id`, and a section that several plugins share declares its own row slot, as the built-in Environment section does with `conversation.session.panel.environment.row`. Marks that must stay visible while the panel is hidden go in an indicator list over the toggle.
Rows from every contributor share one look through the panel's stylesheet instead of a shared component: each contributor writes its row's markup and marks the parts, and the panel lays them out, so icon, text, and trailing areas align across packages. A shared row component would receive each contributor's icon, text, and controls as React nodes in props, which the client rules forbid, and a feature package cannot share its own row component with another feature package.
A section's list shows five rows of each group and then a fold control, because a Session with many subagents, shared tasks, or background jobs would otherwise push the later sections out of the panel's height. Each list orders its rows so that the ones it holds back are the least current: running rows first and then the most recent ones, or for shared tasks, which carry no times, the unfinished tasks before the completed ones. The fold control is the one row the panel does offer as a Component Factory, `conversation.session.panel.fold`: it is the same in every section and takes only data and a callback, while each section keeps its fold state and decides which rows show.
### The turn rail sits at the start edge
The turn rail sits at the scrollport's start edge with its marks, focus ring, and preview mirrored, leaving the end gutter to the docked panel; its 900px hiding rule guarantees room beside the start-side width handle.
## Alternatives considered
- **A seat in `conversation.content`.** Rejected: it made `ui-conversation` render the panel beside the width handles and outside the scrollport, have its width controls measure the gutter into a per-Session `ctx.uiConversation.layouts` source, and move the composer and viewport height variables from the scrollport to the content body so the seat could read them. The Conversation shell would carry geometry and variable placement for one feature, while chrome that must not scroll can sit sticky inside the scrollport as the turn rail does, and the Chat View already owns the column it would measure.
- **A right-sidebar tab.** It already exists for change requests, but it narrows the transcript while shown, shows one tab at a time, and the [UI guidance](../../../skills/dsh-client-ui-ux/SKILL.md#reuse-before-adding) reserves the sidebar for content opened on demand rather than a resident summary.
- **The dock kit's floating window.** `FloatLayer` windows are draggable, resizable, and positioned in viewport coordinates; a summary anchored to the transcript gutter needs none of that and would have to fight the window's own placement rules.
- **Viewport-width breakpoints.** The transcript width is adaptive and draggable and the right sidebar takes a variable track, so a viewport breakpoint either covers the transcript or hides the panel with room to spare.
- **CSS-only hiding with a click-time read.** A container query on the gutter can hide the docked panel, and the toggle could read the computed result when pressed, as the background-job trigger does. The toggle would still render without knowing whether the panel shows, so `aria-expanded` and its tooltip would be wrong whenever the preference says dock but the gutter is too narrow.
- **Squeezing the transcript to make room.** Docking on laptop widths by moving the transcript column aside changes the centered column, the composer, and both width handles; it remains a separate layout decision.
- **A Session-scoped standard hook for the gutter.** Adding a hook to every Session-scoped Slot would make every component fixture in the client restate it; the docking decision has two readers, the panel and the toggle, and both read it from the plugin's own state.
## Consequences
- With the default transcript width, which stops at 880px, the body must be 1576px wide to dock, so laptop widths use the overlay; the panel never covers the transcript unless the user opens it.
- Sections from independent plugins share one surface, ordering, and title style without depending on each other, and an occupied section id can be replaced by a higher-priority registration.
- `ui-chat` gained one slot and one custom property on its layer and observes nothing for them. Each mounted panel adds one `ResizeObserver` on its dock probe, which calls back only when the docking decision flips. `ui-conversation` caps the default transcript width at 880px.
- The panel shows only in Chat Views; elsewhere the toggle stays in the header, unavailable. Every Chat View occurrence renders the aside, so a Session shown in the main body and in an embedded Conversation at once shows its overlay in both.
- The turn rail's position changed for every user; its behavior and hiding rule did not.
- Change requests, background jobs, and subagents became sections, replacing the change requests sidebar tab, its start-page entry, and the header controls of jobs and subagents; the header keeps the subagent breadcrumb switcher for child Sessions. A section mounts only while the panel shows, so state that must outlast hiding the panel, such as cleared job rows, lives in a per-Session slot store.
@@ -0,0 +1,52 @@
# Agent Note: 停靠在 Chat 视图末端留白的会话面板
Status: implemented
[English](2026-11-05-session-panel.md) | 中文
## Problem
与当前会话相关的信息(项目目录、它开出的变更请求,以及之后的产物)没有统一的位置。各自的拥有者分别加会话标题栏按钮,内容一多就再开一个右侧栏标签页,forge 的变更请求就是这样一个标签页。侧栏标签页显示时占用正文宽度,一次只显示一个,而且每条消息之外都要多点一次才能看到。需要的界面是:可以放在对话旁边常驻而不遮挡正文;多个插件各自填充;没有空间时自动隐藏;用户可以从会话标题栏显示或隐藏。
## Decision
[`dsh-client-ui-session-panel`](../../../../packages/client/ui-session-panel/README.zh.md) 新增一个会话标题栏开关(`conversation.session.header.utilities`,order −10)和一块悬浮面板,面板占用 `conversation.chat.aside`:这是 [`ui-chat`](../../../../packages/client/ui-chat/README.zh.md#scroll-ownership) 在 Chat 视图中、轮次轨道旁渲染的 slot。侧边层是 Chat 外框顶部的零高度图层,与轮次轨道一样在共享滚动容器内 sticky 定位:面板不随正文滚动,继承滚动容器的输入框区域与视口高度,也不需要 Conversation 外壳提供落位。Chat 以外的视图不显示面板。
### 停靠取决于正文留白
只有正文列到 Chat 外框末端边缘的留白放得下面板时才停靠(348px:与正文列及其宽度拖拽条保持 40px,最小宽度 300px,外加 8px 边距)。判断依据是留白而不是视口宽度,因为正文列宽度可自适应、可由用户拖拽,右侧栏也会占用框架宽度:同一个视口可能只剩 75px,也可能有 600px。Chat 视图持有外框和正文列,因此由它的侧边层把留白发布为自定义属性 `--dsh-chat-aside-gutter`,面板的样式表据此决定停靠宽度。
脚本仍然需要知道这个判断,因为停靠与浮层的差别不只在尺寸,还在行为:开关要如实报告 `aria-expanded`,也要知道按下后是切换停靠还是打开浮层;浮层在按 Esc 或在外部按下时关闭并归还焦点;面板可以停靠后,已打开的浮层要关闭。纯 CSS 的容器查询无法把这些告诉 Chat 视图之外的元素或事件监听器。因此样式表把判断也一并算出:每个已挂载的面板渲染一个零高度的停靠探针,它从放得下面板最小宽度的留白起宽 1px,更窄时宽度为 0,与停靠宽度出自同一组尺寸,插件只观察这个探针。这样插件只在判断翻转时收到通知;如果改为观察外框和正文列,流式回答的每一帧都会回调(正文列的高度随内容变化),窗口缩放的每一步也会回调。会话的任一探针有空间时该会话就可以停靠,没有探针的会话表示没有 Chat 视图在显示它。开关和面板用同一个纯函数决定呈现方式。没有 Chat 视图显示该会话时(例如在轨迹视图中),开关不可用,悬停提示请用户切到「对话」视图;`ui-conversation` 把视图选择留在其外壳内部,因此开关不自行切换视图。
停靠遵循所有会话共用的一个持久化偏好,默认开启。没有空间时,按下开关会为该会话在正文上方打开临时浮层;它从不改变偏好;该会话的留白可以停靠面板,或不再有 Chat 视图显示该会话时,浮层关闭,因此不会自己重新出现。面板状态跟随打开浮层的会话所上报的留白。面板卸载或其 Chat 视图换到另一个会话时撤回上报;撤回放在与留白更新分开的 layout effect 清理中,因此留白变化永远不会被当成卸载。自动隐藏加按需浮层,既保证正文不被遮挡,也让笔记本宽度下的信息依然可达。
### 分栏是注册项;面板绘制标题
每个分栏是一次 list 注册,带 `id`、`order` 和必填的 `label`。面板把实时注册投影成标题并逐个绘制,再用 `renderSlot(..., { only: id })` 渲染分栏正文;CSS `:has()` 规则隐藏正文没有渲染内容的分栏,因此分栏不渲染任何内容即可退出,不需要 effect 向拥有者上报可见性。标题尾部控件是以分栏 `id` 为键的 keyed slot;多个插件共用的分栏声明自己的行 slot,内置「环境」分栏就以 `conversation.session.panel.environment.row` 这样做。面板隐藏时也要可见的标记放进开关上的角标列表。
各贡献方的行通过面板的样式表共享同一外观,而不是共享组件:各贡献方自己写行的标记并标出各个部分,由面板统一排版,使不同包的图标、文字与尾部区域对齐。共享的行组件要把各贡献方的图标、文字和控件作为 React 节点从 props 传入,这是客户端规则禁止的;功能包之间也不能共享各自的行组件。
分栏的列表每个分组只显示五行,然后是一个收起控件;否则子智能体、共享任务或后台任务很多的会话会把后面的分栏挤出面板的高度。每个列表按顺序排列,使被收起的是最不需要看的行:运行中的在前,然后是最近的;共享任务没有时间信息,则未完成的排在已完成的前面。收起控件是面板唯一以 Component Factory 提供的行,即 `conversation.session.panel.fold`:它在每个分栏里都一样,只接收数据和一个回调,而收起状态和显示哪些行由各分栏自己决定。
### 轮次轨道位于起始边
轮次轨道连同刻度、焦点环和预览位于滚动容器的起始边,末端留白留给停靠面板;它的 900px 隐藏规则保证旁边有足够空间容纳起始侧的宽度拖拽条。
## Alternatives considered
- **落位在 `conversation.content`。** 已否决:这种做法让 `ui-conversation` 在宽度拖拽条旁、滚动容器之外渲染面板,由宽度控件把留白测量结果写入按会话划分的 `ctx.uiConversation.layouts` source,并把输入框区域与视口高度变量从滚动容器挪到正文容器上,使落位能读到它们。Conversation 外壳因此要为单个功能承担几何测量和变量位置;而不随滚动的界面元素可以像轮次轨道那样在滚动容器内 sticky 定位,要测量的正文列也本来就归 Chat 视图所有。
- **右侧栏标签页。** 变更请求已有这种实现,但它显示时会压窄正文,一次只显示一个标签页,而且 [UI 指南](../../../skills/dsh-client-ui-ux/SKILL.md#reuse-before-adding)把侧栏留给按需打开的内容,而不是常驻摘要。
- **dock kit 的悬浮窗。** `FloatLayer` 窗口可拖拽、可缩放、按视口坐标定位;锚定在正文留白的摘要用不上这些能力,还要对抗窗口自身的定位规则。
- **按视口宽度断点。** 正文宽度自适应、可拖拽,右侧栏占用可变宽度,视口断点要么遮挡正文,要么在空间充足时也隐藏面板。
- **纯 CSS 隐藏加点击时读取。** 对留白做容器查询可以隐藏停靠面板,开关在按下时读取计算结果,与后台任务按钮的做法相同。但开关渲染时仍不知道面板是否显示,偏好为停靠而留白不足时,`aria-expanded` 与提示文字都会出错。
- **挤压正文腾出空间。** 在笔记本宽度下把正文列移开来停靠,会改变居中的正文列、composer 和两侧宽度拖拽条;这仍是另一项布局决策。
- **会话作用域标准 hook。** 给每个会话作用域 Slot 增加一个留白 hook,会让客户端所有组件测试夹具都要补上它;停靠判断只有两个读取方,即面板和开关,两者都从插件自己的状态读取。
## Consequences
- 默认正文宽度最多 880px,此时对话区要 1576px 宽才能停靠,因此笔记本宽度使用浮层;除非用户主动打开,面板不会遮挡正文。
- 独立插件的分栏共享同一界面、排序和标题样式,彼此不依赖;已占用的分栏 id 可以被更高优先级的注册替换。
- `ui-chat` 多了一个 slot,侧边层多了一个自定义属性,但不为它们观察任何尺寸。每个已挂载的面板在停靠探针上多一个 `ResizeObserver`,只在停靠判断翻转时回调。`ui-conversation` 把默认正文宽度上限定为 880px。
- 面板只出现在 Chat 视图中;其他视图下开关仍在标题栏中,但不可用。每个 Chat 视图实例都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。
- 轮次轨道的位置对所有用户都变了;行为和隐藏规则不变。
- 变更请求、后台任务和子智能体成为分栏,取代变更请求侧边栏标签页、其起始页入口,以及标题栏中的后台任务和子智能体控件;标题栏仍为子会话保留子智能体面包屑切换器。分栏只在面板显示时挂载,因此需要在隐藏面板后保留的状态(例如已清空的任务行)放在按会话划分的 slot store 中。
@@ -21,8 +21,8 @@
en: 8a9578bbc700c0bf
zh: 8ee46e5ef1cf3972
/agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/authorization-loses-required-observation-or-an-accepted-credential-write:
en: c6b0d746185d0d3b
zh: a228633ecdf42800
en: 0532e871788d6ef7
zh: 75131f43216bd05f
/agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/ssh-disables-cleanup-requests-before-dependent-process-cleanup-finishes:
en: 85fb2b564bc40230
zh: 97c3e794124f8044
@@ -36,7 +36,7 @@ A focused in-memory experiment using the actual Cordis and storage-domain implem
### Authorization loses required observation or an accepted credential write
**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts).
**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/account/deepseek-account/src/index.ts).
**Successful write, false failure.** Pause a credential write, dispose the account consumer, then complete the write and emit its update. The observer can auto-unsubscribe alongside the account's drain; Authorization then rejects with `NOT_COMMITTED` despite successful storage. Keep observation owned by the operation until its result settles, or acknowledge successful `session.commit` directly while giving legacy direct-write observation an explicit lifetime. A focused experiment using actual Cordis and Authorization with a deferred in-memory credential provider reproduced `NOT_COMMITTED` after the provider write succeeded; the complete browser sign-in path is source-traced.
@@ -36,7 +36,7 @@ Status: proposed
### Authorization 丢失必需的提交观察或已接受的凭据写入
**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts)。
**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/account/deepseek-account/src/index.ts)。
**写入成功,却报告失败。** 暂停凭据写入,释放账号消费者,再完成写入并发出更新。观察器可以与账号的排空并发自动退订;随后 Authorization 即使存储成功也会以 `NOT_COMMITTED` 拒绝。应让操作拥有观察器直到结果确定,或直接确认成功的 `session.commit`,同时给旧式直接写入观察明确的生命周期。使用实际 Cordis 与 Authorization、配合延迟的内存凭据 provider 的实验,复现了 provider 写入成功后返回 `NOT_COMMITTED`;完整浏览器登录路径由源码追踪确认。
+47 -29
View File
@@ -1,29 +1,36 @@
/**
* Daily stale pull-request reminders for the `Stale pull requests` workflow.
* Daily stale pull-request reminders and closing for the `Stale pull requests` workflow.
*
* A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review
* event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross
* references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow
* comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE`
* and pull requests opened by bots receive no reminders. The workflow never closes pull requests.
* references, do not count, so reminder and closing comments never extend it. After 7 and 14 days without activity the
* workflow comments once per stage and mentions the author. After 21 days without activity, and at least 7 days after
* the 14-day reminder, it comments and closes the pull request; the reminder therefore always gives the author 7 days'
* notice, including for pull requests that were already inactive when the workflow started. Activity, including
* reopening, starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` and pull requests opened by bots are neither
* reminded nor closed.
*
* Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at`
* also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently
* also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` comments, least recently
* updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed
* pull request is reported and skipped.
*/
/** Label that exempts a pull request from reminders. */
/** Label that exempts a pull request from reminders and closing. */
export const EXEMPT_LABEL = 'DO_NOT_CLOSE'
/** Days without activity after which each reminder is posted, in ascending order. */
export const REMINDER_DAYS = [7, 14]
/** Days without activity after which a pull request is closed. */
export const CLOSE_DAYS = 21
const DAY_MS = 24 * 60 * 60 * 1000
// GitHub asks integrations to wait at least one second between content-creating requests.
const COMMENT_INTERVAL_MS = 1000
const MAX_COMMENTS_PER_RUN = 100
const MARKER = /<!-- stale-pr-reminder:(\d+) -->/
// Reminders posted before closing existed use `stale-pr-reminder` and announce no closing, so they are ignored.
const MARKER = /<!-- stale-pr:(\d+) -->/
// Review bots that use ordinary user accounts.
const BOT_LOGINS = new Set(['ds-review-bot'])
@@ -55,39 +62,46 @@ function activityTimes(event) {
}
/**
* Selects the reminder a pull request is due for.
* Selects the reminder or closing a pull request is due for.
* @param {object} options
* @param {string} options.createdAt Pull-request creation time.
* @param {object[]} options.timeline Complete issue timeline of the pull request.
* @param {Date} options.now Evaluation time.
* @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due.
* @returns {{ days: number, comment: boolean } | undefined} Due stage in days, `CLOSE_DAYS` for closing, and whether its
* comment is still unposted; `undefined` when nothing is due. A closing whose comment was posted but whose close failed
* is due again without a comment.
*/
export function dueReminder({ createdAt, timeline, now }) {
export function dueStage({ createdAt, timeline, now }) {
const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite)
const lastActivity = Math.max(...times)
const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1)
if (due === undefined) return undefined
const sent = timeline
.filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity)
.map(event => Number(MARKER.exec(event.body ?? '')?.[1]))
return sent.some(days => days >= due) ? undefined : due
.map(event => ({ days: Number(MARKER.exec(event.body ?? '')?.[1]), at: Date.parse(event.created_at) }))
const finalReminder = REMINDER_DAYS.at(-1)
const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS
if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) {
return { days: CLOSE_DAYS, comment: !sent.some(({ days }) => days === CLOSE_DAYS) }
}
const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1)
if (due === undefined || sent.some(({ days }) => days >= due)) return undefined
return { days: due, comment: true }
}
/**
* Builds the reminder comment.
* Builds the reminder or closing comment.
* @param {string} author Pull-request author login.
* @param {number} days Reminder stage in days.
* @param {number} days Stage in days; `CLOSE_DAYS` builds the closing comment.
* @returns {string} Comment body.
*/
export function reminderBody(author, days) {
return [
`<!-- stale-pr-reminder:${days} -->`,
`@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`,
].join('\n')
export function stageBody(author, days) {
const text = days === CLOSE_DAYS
? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.`
: `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.`
return `<!-- stale-pr:${days} -->\n${text}`
}
/**
* Posts every due reminder on open pull requests of the workflow repository.
* Posts every due reminder and closes every due pull request among the open pull requests of the workflow repository.
* @param {object} options
* @param {object} options.github Authenticated Octokit client from `actions/github-script`.
* @param {object} options.context Workflow context from `actions/github-script`.
@@ -96,7 +110,7 @@ export function reminderBody(author, days) {
* @param {(ms: number) => Promise<void>} [options.sleep] Delay between comments.
* @returns {Promise<void>}
*/
export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) {
export async function processStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) {
const { owner, repo } = context.repo
const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 })
let posted = 0
@@ -107,12 +121,16 @@ export async function remindStalePullRequests({ github, context, core, now = new
if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue
try {
const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 })
const days = dueReminder({ createdAt: pull.created_at, timeline, now })
if (days === undefined) continue
if (posted > 0) await sleep(COMMENT_INTERVAL_MS)
await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) })
posted++
core.info(`#${pull.number}: posted the ${days}-day reminder`)
const stage = dueStage({ createdAt: pull.created_at, timeline, now })
if (stage === undefined) continue
const { days } = stage
if (stage.comment) {
if (posted > 0) await sleep(COMMENT_INTERVAL_MS)
await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) })
posted++
}
if (days === CLOSE_DAYS) await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' })
core.info(days === CLOSE_DAYS ? `#${pull.number}: closed after ${days} days without activity` : `#${pull.number}: posted the ${days}-day reminder`)
} catch (error) {
failed++
core.warning(`#${pull.number}: ${error.message}`)
+60 -28
View File
@@ -1,47 +1,67 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs'
import { dueStage as dueAction, stageBody, processStalePullRequests } from './remind.mjs'
const now = new Date('2026-11-30T00:00:00Z')
const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString()
const human = { login: 'author', type: 'User' }
const bot = { login: 'github-actions[bot]', type: 'Bot' }
const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body })
const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage))
const reminder = (days, stage) => comment(bot, days, stageBody('author', stage))
const dueStage = options => dueAction(options)?.days
test('no reminder is due within 7 days of the last activity', () => {
assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined)
assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined)
})
test('the latest due stage is posted once after the last activity', () => {
assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7)
assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined)
assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(7), timeline: [], now }), 7)
assert.equal(dueStage({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [], now }), 14)
assert.equal(dueStage({ createdAt: daysAgo(17), timeline: [reminder(3, 14)], now }), undefined)
})
test('a pull request closes after 21 days without activity and 7 days after the 14-day reminder', () => {
assert.equal(dueStage({ createdAt: daysAgo(21), timeline: [reminder(14, 7), reminder(7, 14)], now }), 21)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), 21)
// A pull request that was already inactive gets the 14-day reminder first and 7 days' notice.
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(6, 14)], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14)
// A 14-day reminder from before the last activity gives no notice.
assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14)
// Reminders posted before closing existed announce no closing.
const legacy = comment(bot, 10, '<!-- stale-pr-reminder:14 -->\n@author This pull request has had no activity for 14 days.')
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [legacy], now }), 14)
})
test('a closing whose comment was posted retries the close without another comment', () => {
assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14)], now }), { days: 21, comment: true })
assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14), reminder(1, 21)], now }), { days: 21, comment: false })
})
test('human activity restarts the cycle and bot activity does not', () => {
const sentBefore = [reminder(30, 7), reminder(23, 14)]
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined)
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reopened', actor: human, created_at: daysAgo(3) }], now }), undefined)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), 21)
assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), 21)
})
test('mentions, labels and cross references are not activity', () => {
const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) })
// GitHub records a `mentioned` event for the author right after each reminder.
assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14)
assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14)
assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14)
assert.equal(dueStage({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14)
})
test('reminders mention the author and skip exempt and bot-authored pull requests', async () => {
test('reminders and closing mention the author and skip exempt and bot-authored pull requests', async () => {
const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides })
const pulls = [
pull(1),
@@ -51,12 +71,21 @@ test('reminders mention the author and skip exempt and bot-authored pull request
pull(4, { updated_at: daysAgo(1) }),
pull(6),
pull(5),
pull(7, { created_at: daysAgo(30) }),
pull(8, { created_at: daysAgo(30) }),
]
const comments = []
const closed = []
const timelines = []
const github = {
rest: {
pulls: { list: 'pulls' },
pulls: {
list: 'pulls',
update: async params => {
if (params.pull_number === 8) throw new Error('close failed')
closed.push(params)
},
},
issues: {
listEventsForTimeline: 'timeline',
createComment: async params => {
@@ -68,20 +97,23 @@ test('reminders mention the author and skip exempt and bot-authored pull request
paginate: async (method, params) => {
if (method === 'pulls') return pulls
timelines.push(params.issue_number)
return []
return [7, 8].includes(params.issue_number) ? [reminder(9, 14)] : []
},
}
const sleeps = []
const warnings = []
const failures = []
const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) }
await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) })
assert.deepEqual(timelines, [1, 4, 6, 5])
assert.deepEqual(warnings, ['#6: locked'])
await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) })
assert.deepEqual(timelines, [1, 4, 6, 5, 7, 8])
// A failed close after its comment is retried on the next run without another comment.
assert.deepEqual(warnings, ['#6: locked', '#8: close failed'])
assert.equal(failures.length, 1)
assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5])
assert.match(comments[0].body, /^<!-- stale-pr-reminder:14 -->\n@author This pull request has had no activity for 14 days\./)
assert.deepEqual(sleeps, [1000, 1000, 1000])
assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7, 8])
assert.match(comments[0].body, /^<!-- stale-pr:14 -->\n@author This pull request has had no activity for 14 days\./)
assert.match(comments[3].body, /^<!-- stale-pr:21 -->\n@author This pull request has had no activity for 21 days and is now closed\./)
assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }])
assert.deepEqual(sleeps, [1000, 1000, 1000, 1000, 1000])
})
test('a run posts at most 100 reminders', async () => {
@@ -91,6 +123,6 @@ test('a run posts at most 100 reminders', async () => {
rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } },
paginate: async method => method === 'pulls' ? pulls : [],
}
await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} })
await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} })
assert.equal(comments, 100)
})
+5 -5
View File
@@ -1,4 +1,4 @@
# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them.
# Reminds authors of open pull requests after 7 and 14 days without activity and closes them after 21 days.
# Rules: .github/stale-pull-requests/remind.mjs.
name: Stale pull requests
@@ -16,7 +16,7 @@ concurrency:
jobs:
remind:
name: Remind stale pull requests
name: Remind and close stale pull requests
runs-on: ubuntu-latest
permissions:
contents: read
@@ -27,9 +27,9 @@ jobs:
with:
sparse-checkout: .github/stale-pull-requests
persist-credentials: false
- name: Post due reminders
- name: Post due reminders and close stale pull requests
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3
with:
script: |
const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`)
await remindStalePullRequests({ github, context, core })
const { processStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`)
await processStalePullRequests({ github, context, core })
+1
View File
@@ -58,6 +58,7 @@ packages/ @deepseek-ai/dsh-<pkg> workspaces at packages/<group>/<pkg>/
identity/ anonymous identity
settings/ user settings
credentials/ credentials/authorization
account/ DeepSeek
acp/ automation-only ACP
interaction/ human interaction
boot/ application boot
+9 -4
View File
@@ -85,14 +85,18 @@ describe('dsh run with Agent Teams enabled', () => {
expect(files).toHaveLength(4)
const logs = await Promise.all(files.map(file => readFile(join(sessions, file), 'utf8')))
const parsed = logs.map(records)
const workflowTask = [
{ type: 'text', text: 'Agent lead sent a message: ' },
{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' },
]
const workflowChild = parsed.find(log => log.some(record => record.type === 'user/message'
&& JSON.stringify((record.data as { content: unknown }).content) === JSON.stringify([{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }])))
&& JSON.stringify((record.data as { content: unknown }).content) === JSON.stringify(workflowTask)))
expect(workflowChild).toBeDefined()
const workflowDescriptor = workflowChild!.find(record => record.type === 'subagent/descriptor')?.data as Record<string, unknown>
expect(workflowDescriptor).toMatchObject({ mode: 'continuable', provider: 'spawn' })
expect(workflowChild!.filter(record => record.type === 'user/message'
&& (record.data as { source: { kind: string } }).source.kind === 'user').map(record => record.data))
.toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })])
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message').map(record => record.data))
.toEqual([expect.objectContaining({ content: workflowTask })])
const root = parsed.find((log) => {
const header = log[0]
return header?.type === 'session' && typeof header.parentSession !== 'string'
@@ -111,7 +115,8 @@ describe('dsh run with Agent Teams enabled', () => {
expect(eventTypes).not.toContain('team/message/queued')
expect(eventTypes).not.toContain('team/message/delivered')
const peerMessages = parsed.flatMap(log => log.filter(record => record.type === 'user/message'
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message'))
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message'
&& (record.data as { source: { senderSessionId: string } }).source.senderSessionId !== root![0]?.id))
expect(peerMessages).toHaveLength(2)
const taskEvents = root!.filter(record => record.type === 'team/task')
expect(taskEvents.filter((record) => {
+1 -3
View File
@@ -143,9 +143,7 @@ function createProfileLifecycleFixture(): ProfileLifecycleFixture {
writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
const linkTarget = join(profileDir, 'node_modules', 'dsh-lifecycle-bundle')
mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
try {
rmSync(linkTarget, { recursive: true, force: true })
} catch { /* fresh dir */ }
rmSync(linkTarget, { recursive: true, force: true })
// Copy-free: a package.json redirecting via a relative main is enough for require.resolve.
mkdirSync(linkTarget, { recursive: true })
for (const file of ['package.json', 'cordis.patch.yml', 'plugin.mjs']) {
@@ -37,7 +37,7 @@
"boolean",
"null"
],
"description": "Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation."
"description": "Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation."
},
"disabled": {
"anyOf": [
@@ -249,6 +249,28 @@
{
"$ref": "#/$defs/entryMetadata"
},
{
"if": {
"properties": {
"group": {
"const": true
}
},
"required": [
"group"
]
},
"then": {
"properties": {
"config": {
"$ref": "#/$defs/entryList"
}
},
"required": [
"config"
]
}
},
{
"if": {
"properties": {
@@ -31,10 +31,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr
- setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value.
- selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate.
## Simulated mouse
Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot.
## Screenshots
Use an explicit window for screenshots.
- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId.
## Simulated mouse
Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot.
- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration.
- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.
- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press.
- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window.
@@ -48,6 +52,8 @@ Available at app or window level depending on the platform.
- pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string.
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier.
click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
AX read defaults: maxElements=2000, maxDepth=25.
@@ -17,7 +17,7 @@
{
"name": "cua_run_code",
"title": "Computer use program",
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. 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, output overflow, 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.",
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. 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.",
"inputSchema": {
"type": "object",
"properties": {
@@ -9,7 +9,7 @@
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title-llm-request","seq":13,"time":0,"data":{"titleProvider":"session-title-first-prompt-llm","messageSeqs":[8],"route":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"Create a concise title for an AI coding-assistant session from the supplied human messages.\nReturn only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.\nUse the language of the messages.\nAim for about 5 words in non-CJK languages or 10 CJK characters.\nIf the messages give little to name, still return a short best-effort title, such as Greeting, instead of explaining.","messages":[{"content":[{"type":"text","text":"Generate the session title from this JSON array of human messages:\n[{\"seq\":8,\"text\":\"say pong\"}]"}],"source":{"kind":"dsh-session-title-llm"},"role":"user","id":"{{sessionId}}"}],"maxTokens":4096,"reasoningEffort":"off"}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":15,"time":0,"data":{"turn":1,"step":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}}
{"type":"result","sessionId":"{{sessionId}}","output":""}
@@ -2,19 +2,18 @@
{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Delegated write probe","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash","agentReasoningEffort":"low"}}
{"type":"sandbox/mode","data":{"mode":"read-only","source":"delegation"}}
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}
{"type":"turn/start","data":{"turn":1}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
{"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"child-write","name":"write","args":["{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":1,"callId":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}}
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"child-write"},"toolCallId":"child-write","content":[{"type":"text","text":"Error: [sandbox: file access denied under read-only mode]\n[sandbox: escalation available — retry this exact operation once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]"}],"isError":true,"id":"{{sessionId}}"},"error":{"name":"FsError","code":"FS_SANDBOX_DENIED"}},"sourceEventSeqs":[14],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"child-write"},"toolCallId":"child-write","content":[{"type":"text","text":"Error: [sandbox: file access denied under read-only mode]\n[sandbox: escalation available — retry this exact operation once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]"}],"isError":true,"id":"{{sessionId}}"},"error":{"name":"FsError","code":"FS_SANDBOX_DENIED"}},"sourceEventSeqs":[13],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"step/start","data":{"turn":1,"step":2}}
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["CHILD_DENIED [sandbox: file access denied under read-only mode]"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
@@ -2,16 +2,15 @@
{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Return child result","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash"}}
{"type":"sandbox/mode","data":{"mode":"workspace-write","source":"delegation"}}
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}
{"type":"turn/start","data":{"turn":1}}
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
{"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_RESULT"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["CHILD_RESULT"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_RESULT"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
@@ -18,7 +18,7 @@ function latestAssistantCalls(messages) {
function hasNewCoordinationInput(messages) {
const toolIndex = messages.findLastIndex(message => message.role === 'tool')
return messages.some((message, index) => index > toolIndex && message.role === 'user'
return toolIndex >= 0 && messages.some((message, index) => index > toolIndex && message.role === 'user'
&& ['agent-message', 'subagent-settled'].includes(message.source?.kind))
}
@@ -191,13 +191,15 @@ function lead(messages) {
class TeamFixtureAdapter extends LlmAdapter {
async * stream(options) {
const tools = options.tools.map(tool => tool.name)
const initial = options.messages.findLast(message => message.role === 'user' && message.source.kind === 'user')
const workflowChild = initial?.content[0]?.text === 'TEAM_WORKFLOW_CHILD'
const initial = options.messages.find(message => message.role === 'user'
&& ['user', 'agent-message'].includes(message.source.kind))
const taskContent = initial?.source.kind === 'agent-message' ? initial.content.slice(1) : initial?.content
const workflowChild = taskContent?.[0]?.text === 'TEAM_WORKFLOW_CHILD'
const context = options.messages.findLast(message => message.source?.kind === 'runtime-context')
const section = name => context?.source.sections?.find(candidate => candidate.name === name)?.text
const role = section('subagent:identity')
const parentId = role?.match(/You are a subagent delegated by agent "([^"]+)"/u)?.[1]
const task = initial?.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
const task = taskContent?.filter(block => block.type === 'text').map(block => block.text).join('\n')
if (!workflowChild && (!tools.includes('subagent') || !tools.includes('workflow') || !tools.includes('team_task_create'))) {
throw new Error('Team profile is missing delegation, workflow, or task tools')
}
@@ -1116,15 +1116,22 @@ describe('headless stream-json snapshots', () => {
const parent = logs.find(log => typeof log.header.parentSession !== 'string')
if (parent === undefined) throw new Error('Agent Teams snapshot did not persist its Lead')
const rows = parseJsonl(parent.content)
const workflowTask = [
{ type: 'text', text: 'Agent lead sent a message: ' },
{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' },
]
const workflowChild = logs.find(log => parseJsonl(log.content).some(row => row.type === 'user/message'
&& JSON.stringify((row.data as JsonObject).content) === JSON.stringify([{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }])))
&& JSON.stringify((row.data as JsonObject).content) === JSON.stringify(workflowTask)))
if (workflowChild === undefined) throw new Error('Team profile did not persist its workflow child')
const workflowRows = parseJsonl(workflowChild.content)
expect(workflowRows.find(row => row.type === 'subagent/descriptor')?.data)
.toMatchObject({ mode: 'continuable', provider: 'spawn' })
expect(workflowRows.filter(row => row.type === 'user/message'
&& ((row.data as JsonObject).source as JsonObject).kind === 'user').map(row => row.data))
.toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })])
&& ((row.data as JsonObject).source as JsonObject).kind === 'agent-message').map(row => row.data))
.toEqual([expect.objectContaining({
content: workflowTask,
source: { kind: 'agent-message', form: 'relay', senderSessionId: parent.header.id },
})])
const teammates = rows.filter(row => row.type === 'subagent/catalog')
.flatMap(row => typeof (row.data as JsonObject).label === 'string' && ((row.data as JsonObject).label as string).startsWith('Own deterministic ') ? [(row.data as JsonObject).label as string] : [])
const tasks = rows.filter(row => row.type === 'team/task')
@@ -1160,6 +1167,7 @@ describe('headless stream-json snapshots', () => {
const source = (row.data as JsonObject).source
return typeof source === 'object' && source !== null && !Array.isArray(source)
&& (source as JsonObject).kind === 'agent-message'
&& (source as JsonObject).senderSessionId !== parent.header.id
})
const openTurnStart = implementerRows.findLastIndex((row, index) => (
index < steeredMessageIndex && row.type === 'turn/start'
@@ -1176,11 +1184,11 @@ describe('headless stream-json snapshots', () => {
const identities = logs.flatMap((log) => {
if (log === parent || log === workflowChild) return []
const initial = parseJsonl(log.content).find(row => row.type === 'user/message'
&& ((row.data as JsonObject).source as JsonObject).kind === 'user')
&& ((row.data as JsonObject).source as JsonObject).kind === 'agent-message')
if (initial === undefined) throw new Error('Teammate Session has no initial task')
const content = (initial.data as JsonObject).content as JsonObject[]
// The task block is followed by the standard return guidance naming the Lead.
expect(content).toHaveLength(2)
expect(content).toHaveLength(3)
expect(content[0]).toEqual({ type: 'text', text: 'Agent lead sent a message: ' })
const context = parseJsonl(log.content).find(row => row.type === 'user/message'
&& ((row.data as JsonObject).source as JsonObject).kind === 'runtime-context')
const source = (context?.data as JsonObject)?.source as JsonObject
+1 -1
View File
@@ -27,7 +27,7 @@
"path": "../../packages/host/webserver"
},
{
"path": "../../packages/credentials/deepseek-account"
"path": "../../packages/account/deepseek-account"
},
{
"path": "../../packages/boot/plugin-manager"
+2 -2
View File
@@ -15,8 +15,8 @@
en: 127ea90553cb6af7
zh: 7b1c5aec8558c684
/deepseek-harness-desktop/application-overview:
en: 8b2a35655a384403
zh: 8cb7c8138cae59db
en: 7414f87908fbffaf
zh: 8ff4fc1d83879c25
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
+1 -1
View File
@@ -51,7 +51,7 @@ Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/depend
Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar.
Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection.
Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/account/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection.
A server-expired account credential returns to Welcome when no official API key is configured; an available API key keeps the workspace open. Explicit sign-out follows the same rule. Both Welcome and the workspace display the localized expiry notice.
+1 -1
View File
@@ -51,7 +51,7 @@ Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一
Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。
Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。
Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/account/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。
账号凭据被服务端判定失效后,未配置官方 API key 时返回 Welcome;有可用 API key 时保持工作区打开。主动退出登录遵循相同规则。Welcome 和工作区均显示本地化的登录失效提示。
+4 -3
View File
@@ -142,14 +142,15 @@ export function Welcome({ api }: { api: WelcomeApi }) {
if (cancelling || attemptRef.current === null) return
setCancelling(true)
const current = ++revision.current
let state: AccountView | undefined
try {
const state = await api.cancelSignIn(attemptRef.current.id)
if (mounted.current && revision.current === current) showAccount(state)
} catch {
state = await api.cancelSignIn(attemptRef.current.id)
} catch (_cancelFailed) {
// The current attempt remains visible so cancellation can be retried.
} finally {
if (mounted.current) setCancelling(false)
}
if (state !== undefined && mounted.current && revision.current === current) showAccount(state)
}
async function copyLink() {
const current = attemptRef.current
+9 -8
View File
@@ -15,17 +15,18 @@ if (process.isMainFrame && location.origin === allowedOrigin) {
try { listener(value) } catch (error) { console.error('Platform locale listener failed', error) }
}
})
let value: unknown
try {
const value: unknown = ipcRenderer.sendSync(PLATFORM_IPC.bootstrap)
if (typeof value === 'object' && value !== null && 'token' in value && 'origin' in value
&& typeof value.token === 'string' && value.token.length > 0 && value.origin === location.origin
&& 'locale' in value && (value.locale === 'en_US' || value.locale === 'zh_CN')) {
token = value.token
locale = value.locale
}
} catch {
value = ipcRenderer.sendSync(PLATFORM_IPC.bootstrap)
} catch (_bootstrapFailed) {
// Initialization failure retains embedded mode so Platform cannot use browser credentials.
}
if (typeof value === 'object' && value !== null && 'token' in value && 'origin' in value
&& typeof value.token === 'string' && value.token.length > 0 && value.origin === location.origin
&& 'locale' in value && (value.locale === 'en_US' || value.locale === 'zh_CN')) {
token = value.token
locale = value.locale
}
contextBridge.exposeInMainWorld('dsh', {
protocolVersion: 1,
displayMode: 'embedded',
+1 -1
View File
@@ -14,7 +14,7 @@
"path": "../../packages/client/ui-primitives"
},
{
"path": "../../packages/credentials/deepseek-account"
"path": "../../packages/account/deepseek-account"
},
{
"path": "../../packages/client/product-analytics/tsconfig.client.json"
+1 -1
View File
@@ -18,7 +18,7 @@
"path": "../../packages/util/home-paths"
},
{
"path": "../../packages/credentials/deepseek-account"
"path": "../../packages/account/deepseek-account"
},
{
"path": "../../packages/api/gateway/tsconfig.host.json"
+4 -3
View File
@@ -428,9 +428,10 @@ describe('web e2e: agent-preset selection', () => {
await compareOrRefreshGolden(HEADER_EXPECTED, snapshot, MODE)
expect(snapshot).toContain('Minimal mode')
expect(snapshot).toContain('button "1 subagent"')
expect(snapshot.indexOf('Minimal mode')).toBeLessThan(snapshot.indexOf('button "1 subagent"'))
expect(snapshot.indexOf('button "1 subagent"')).toBeLessThan(snapshot.indexOf('button "More actions"'))
// The Session's subagents live in the Session panel, whose toggle follows the preset label.
expect(snapshot).not.toContain('button "1 subagent"')
expect(snapshot.indexOf('Minimal mode')).toBeLessThan(snapshot.indexOf('button "Session panel"'))
expect(snapshot.indexOf('button "Session panel"')).toBeLessThan(snapshot.indexOf('button "More actions"'))
// Static chrome, not a control: the header can only report a composition
// the host would refuse to change.
expect(snapshot).not.toContain('button "Minimal mode"')
+243 -278
View File
@@ -2,7 +2,8 @@
// over the real Host projection frame flow.
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
import type { Browser, Page } from 'playwright'
import { homedir } from 'node:os'
import type { Browser, Locator, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished, vi } from 'vitest'
import type {} from '@deepseek-ai/dsh-agent-team'
@@ -10,16 +11,22 @@ import type { SessionId } from '@deepseek-ai/dsh-session'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { CommandId } from '@deepseek-ai/dsh-commands/types'
import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path'
import {
acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { assertWarningDialogLayout, connectFreshWorkspace, connectFreshWorkspaceZh, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
import {
assertWarningDialogLayout, connectFreshWorkspace, connectFreshWorkspaceZh, dismissSessionPanel, foldControlLayout, newEnglishPage,
saveFailureShot, sessionPanelToggle, showSessionPanel, writeComposerDraft,
} from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/agent-team-panel', import.meta.url))
const PANEL_EXPECTED = join(SNAPSHOT_DIR, 'task.expected.md')
const RESIZE_EXPECTED = join(SNAPSHOT_DIR, 'resize.expected.md')
const MODE = webSnapshotMode()
const SUBAGENTS_SECTION = '[data-session-panel-section="subagents"]'
const SHARED_TASKS_SECTION = '[data-session-panel-section="shared-tasks"]'
const RESEARCHER_DESCRIPTION = 'Researcher: investigate the construction and verify every bound before reporting the result. '.repeat(8).trim()
const RECEIPT_LOCALES = [
{
@@ -40,6 +47,26 @@ const RECEIPT_LOCALES = [
type ReceiptLocale = typeof RECEIPT_LOCALES[number]
/**
* Show the Session panel and return its Subagents section once the panel's
* entrance animation has ended, so geometry reads see its resting position.
* @param page - the page under test.
* @returns the section, hidden while it has nothing to show.
*/
async function showSubagentsSection(page: Page): Promise<Locator> {
return (await showSessionPanel(page)).locator(SUBAGENTS_SECTION)
}
/**
* Show the Session panel and return its Shared tasks section once the panel's
* entrance animation has ended.
* @param page - the page under test.
* @returns the section, hidden while it has nothing to show.
*/
async function showSharedTasksSection(page: Page): Promise<Locator> {
return (await showSessionPanel(page)).locator(SHARED_TASKS_SECTION)
}
async function openTeamSettings(page: Page, chinese = false): Promise<void> {
const trigger = page.getByRole('button', { name: chinese ? /^选择模型/u : /^Select model/u })
await trigger.click()
@@ -252,7 +279,11 @@ describe('web e2e: agent teamwork panel', () => {
it('defaults off and saves a Session selection in the model menu', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-mode'))
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
const assertNoSubagentsSection = async (): Promise<void> => {
expect(await (await showSubagentsSection(page)).locator('[data-subagents-section]').count()).toBe(0)
await dismissSessionPanel(page)
}
await assertNoSubagentsSection()
await openTeamSettings(page)
const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true })
await toggle.waitFor()
@@ -266,7 +297,7 @@ describe('web e2e: agent teamwork panel', () => {
await page.keyboard.press('Space')
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true')
await closeModelMenu(page)
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
await assertNoSubagentsSection()
const agent = scaffold.ctx.agents.list()[0]!
expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false)
expect(agent.session.ownEvents().filter(event => event.type === 'command/run' || event.type === 'command/done')).toEqual([])
@@ -275,8 +306,8 @@ describe('web e2e: agent teamwork panel', () => {
await other.dispose()
const beforeReload = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
await assertNoSubagentsSection()
await openTeamSettings(page)
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
expect(await toggle.getAttribute('aria-checked')).toBe('true')
await closeModelMenu(page)
acknowledgeReloadConnectionLoss(tripwire, beforeReload)
@@ -310,37 +341,32 @@ describe('web e2e: agent teamwork panel', () => {
expect(tripwire.pageErrors).toEqual([])
})
it('shows tasks without children or a divider and hides the entry after the last task is deleted', async () => {
it('shows tasks in their own section without subagents and hides it after the last task is deleted', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-task-only'))
const agent = scaffold.ctx.agents.list()[0]!
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
const section = await showSharedTasksSection(page)
expect(await section.locator('[data-team-panel]').count()).toBe(0)
expect(await section.isVisible()).toBe(false)
const task = await scaffold.ctx.agentTeams.createTask(agent, {
subject: 'Plan before delegation', description: 'Prepare shared work before creating subagents',
})
await page.getByRole('button', { name: '0 subagents', exact: true }).click()
const board = page.locator('[data-team-panel]')
const board = section.locator('[data-team-panel]')
await board.getByText(task.subject, { exact: true }).waitFor()
const panel = page.locator('[data-subagent-panel]')
expect(await panel.getByRole('treeitem').count()).toBe(0)
await panel.getByText('No subagents', { exact: true }).waitFor()
expect(await panel.locator('[data-subagent-section-header]').textContent()).toBe('Subagents')
expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await page.locator(SUBAGENTS_SECTION).isVisible()).toBe(false)
expect(await section.getByRole('heading', { level: 2 }).locator('..').textContent()).toBe('Shared tasks1 pending')
expect(await section.locator('h2 button, h3 button').count()).toBe(0)
expect(await board.locator('[data-team-task-details]').count()).toBe(0)
expect(await board.getByRole('button', { expanded: false }).count()).toBe(1)
expect(await board.evaluate((element) => {
const style = getComputedStyle(element)
return { border: style.borderTopWidth, margin: style.marginTop }
})).toEqual({ border: '0px', margin: '0px' })
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'task-only.expected.md'),
await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd), MODE)
await captureStableAria(page, SHARED_TASKS_SECTION, scaffold.workspaceCwd), MODE)
await scaffold.ctx.agentTeams.updateTask(agent, { taskId: task.id, expectedRevision: task.revision, action: 'delete' })
await page.locator('[data-subagent-action]').waitFor({ state: 'hidden' })
await page.locator('[data-subagent-panel]').waitFor({ state: 'hidden' })
await board.waitFor({ state: 'detached' })
await section.waitFor({ state: 'hidden' })
await dismissSessionPanel(page)
expect(tripwire.pageErrors).toEqual([])
})
it('opens the member tree and live read-only tasks in one panel', async () => {
it('opens the member tree and live read-only tasks in their own sections', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-team-panel'))
const projectionReads = vi.spyOn(scaffold.ctx.sessionController, 'projections')
onTestFinished(() => { projectionReads.mockRestore() })
@@ -350,32 +376,16 @@ describe('web e2e: agent teamwork panel', () => {
version: 2, childId: memberId, childCreatedAt: Date.now(), mode: 'external',
label: RESEARCHER_DESCRIPTION,
})
const countAction = page.locator('[data-subagent-action]')
await countAction.waitFor()
await page.mouse.move(2, 2)
expect(await countAction.evaluate((element) => {
const header = element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!
const preset = header.querySelector('[data-icon="dsw-icon-agent-preset-outline-regular"]')!
const users = element.querySelector('[data-icon="dsw-icon-users-outline-regular"]')!
return {
display: getComputedStyle(header).display, gap: getComputedStyle(header).gap,
presetOpacity: getComputedStyle(preset).opacity,
presetParentOpacity: getComputedStyle(preset.parentElement!).opacity,
sameColor: getComputedStyle(preset).color === getComputedStyle(users).color,
}
})).toEqual({ display: 'flex', gap: '10px', presetOpacity: '1', presetParentOpacity: '1', sameColor: true })
const countTrigger = countAction.getByRole('button', { name: /subagents?$/u })
await countTrigger.click()
await countTrigger.click()
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
expect(await countTrigger.evaluate(element => element === document.activeElement)).toBe(true)
await countTrigger.click()
const action = page.locator('[data-subagent-panel]')
const toggle = sessionPanelToggle(page)
await toggle.click()
await toggle.click()
await page.locator('[data-session-panel]').waitFor({ state: 'detached' })
expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true)
const action = await showSubagentsSection(page)
await action.getByRole('treeitem', { name: /Researcher/u }).waitFor()
expect(await action.locator('[data-team-panel], [data-subagent-section-header]').count()).toBe(0)
expect(await action.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await action.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await page.locator('[data-team-panel]').count()).toBe(0)
expect(await page.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await action.locator('h2 button, h3 button').count()).toBe(0)
expect(await action.getByRole('heading', { name: 'Members', exact: true }).count()).toBe(0)
expect(projectionReads).not.toHaveBeenCalled()
@@ -383,52 +393,32 @@ describe('web e2e: agent teamwork panel', () => {
expect(await action.getByRole('button', { name: /Refresh/u }).count()).toBe(0)
await action.getByRole('treeitem', { name: /Researcher/u }).waitFor()
expect(await page.locator('[data-subagent-panel]').count()).toBe(1)
expect(await page.locator('[data-subagents-section]').count()).toBe(1)
expect(await page.getByRole('button', { name: 'Task board', exact: true }).count()).toBe(0)
const task = await scaffold.ctx.agentTeams.createTask(agent, {
subject: 'Agent task', description: 'Created by the root agent', writeScopes: ['src/web'],
})
const row = action.locator(`[data-team-task="${task.id}"]`)
const tasks = page.locator(SHARED_TASKS_SECTION)
const row = tasks.locator(`[data-team-task="${task.id}"]`)
await row.getByRole('button', { name: 'Pending Agent task', exact: true, expanded: false }).waitFor()
expect(await action.locator('[data-subagent-section-header]').textContent()).toBe('Subagents1 external')
expect(await action.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await action.locator('[data-team-panel]').evaluate((element) => {
const style = getComputedStyle(element)
return { border: style.borderTopWidth, margin: style.marginTop }
})).toEqual({ border: '0px', margin: '4px' })
expect(await action.evaluate((element) => {
const tree = element.querySelector('[role="tree"]')!
const board = element.querySelector('[data-team-panel]')!
return Boolean(tree.compareDocumentPosition(board) & Node.DOCUMENT_POSITION_FOLLOWING)
})).toBe(true)
const head = action.getByRole('heading', { level: 2 }).locator('..')
expect(await head.textContent()).toBe('Subagents1 external')
expect(await action.locator('h2 button, h3 button').count()).toBe(0)
expect(await action.evaluate((element, selector) => Boolean(
element.compareDocumentPosition(document.querySelector(selector)!) & Node.DOCUMENT_POSITION_FOLLOWING,
), SHARED_TASKS_SECTION)).toBe(true)
expect(await row.evaluate(element => ({ tag: element.tagName, parent: element.parentElement?.tagName })))
.toEqual({ tag: 'LI', parent: 'UL' })
expect(await action.locator('[data-team-task-details], article').count()).toBe(0)
expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await action.getByRole('heading', { name: 'Shared tasks 1 pending', exact: true }).waitFor()
expect(await action.evaluate(element => getComputedStyle(element).padding)).toBe('6px')
expect(await action.locator('[data-subagent-section-header]').evaluate((element) => {
const style = getComputedStyle(element)
return { padding: style.padding, gap: style.gap }
})).toEqual({ padding: '4px 7px 8px', gap: '7px' })
expect(await action.locator('[data-team-panel]').getByRole('heading')
.evaluate(element => getComputedStyle(element).columnGap)).toBe('7px')
for (const [title, progress] of [
[action.locator('[data-subagent-section-header]').getByRole('heading'), action.getByText('1 external', { exact: true })],
[action.locator('[data-team-panel]').getByText('Shared tasks', { exact: true }), action.getByText('1 pending', { exact: true })],
] as const) {
expect(await progress.evaluate(element => getComputedStyle(element).marginInlineStart)).toBe('4px')
const titleRight = await title.evaluate(element => element.getBoundingClientRect().right)
const progressLeft = await progress.evaluate(element => element.getBoundingClientRect().left)
expect(Math.abs(progressLeft - titleRight - 11)).toBeLessThanOrEqual(1)
}
expect(await tasks.locator('[data-team-task-details], article').count()).toBe(0)
const tasksHead = tasks.getByRole('heading', { level: 2 }).locator('..')
expect(await tasksHead.textContent()).toBe('Shared tasks1 pending')
expect(await tasks.getByRole('heading', { level: 2 }).evaluate(element => getComputedStyle(element).font))
.toBe(await action.getByRole('heading', { level: 2 }).evaluate(element => getComputedStyle(element).font))
const member = action.getByRole('treeitem', { name: /Researcher/u })
const memberTitle = member.getByText(RESEARCHER_DESCRIPTION, { exact: true })
const taskTitle = row.getByText('Agent task', { exact: true })
const titleLefts = await Promise.all([
memberTitle,
action.locator('[data-subagent-section-header]').getByRole('heading'),
action.locator('[data-team-panel]').getByText('Shared tasks', { exact: true }),
taskTitle,
].map(locator => locator.evaluate(element => element.getBoundingClientRect().left)))
expect(Math.max(...titleLefts) - Math.min(...titleLefts)).toBeLessThanOrEqual(1)
@@ -438,8 +428,8 @@ describe('web e2e: agent teamwork panel', () => {
})))
expect(primaryStyles.map(style => style.fontSize)).toEqual(['13px', '13px'])
expect(primaryStyles[1]).toEqual(primaryStyles[0])
expect(await member.getByText('team-panel-researcher', { exact: true })
.evaluate(element => getComputedStyle(element).fontSize)).toBe('12px')
// The member's name moves from the row to its hover card.
expect(await member.getByText('team-panel-researcher', { exact: true }).count()).toBe(0)
const memberHover = member.locator(':scope > div')
for (const target of [member, memberHover]) {
expect(await target.evaluate((element) => {
@@ -447,27 +437,33 @@ describe('web e2e: agent teamwork panel', () => {
return [style.paddingTop, style.paddingBottom]
})).toEqual(['4px', '4px'])
}
expect(await member.evaluate(element => getComputedStyle(element).minHeight)).toBe('40px')
expect(await member.evaluate(element => getComputedStyle(element).minHeight)).toBe('28px')
expect(await member.evaluate((element) => {
const style = getComputedStyle(element)
return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap }
})).toEqual({ left: '9px', right: '6px', gap: '7px' })
})).toEqual({ left: '6px', right: '6px', gap: '8px' })
expect(await memberHover.evaluate((element) => {
const style = getComputedStyle(element)
return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap, margin: style.margin }
})).toEqual({ left: '6px', right: '6px', gap: '7px', margin: '-4px -6px' })
})).toEqual({ left: '6px', right: '6px', gap: '8px', margin: '-4px -6px' })
const taskHover = row.getByRole('button')
expect(await taskHover.evaluate((element) => {
const style = getComputedStyle(element)
return [style.paddingTop, style.paddingBottom]
})).toEqual(['7px', '7px'])
expect(await taskHover.evaluate(element => element.getBoundingClientRect().height)).toBe(31)
})).toEqual(['4px', '4px'])
expect(await taskHover.evaluate(element => element.getBoundingClientRect().height)).toBe(28)
expect(await taskHover.evaluate((element) => {
const style = getComputedStyle(element)
return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap, margin: style.margin }
})).toEqual({ left: '6px', right: '6px', gap: '7px', margin: '0px -6px' })
expect(await taskHover.evaluate(element => element.getBoundingClientRect().width
- element.parentElement!.getBoundingClientRect().width)).toBe(12)
})).toEqual({ left: '6px', right: '6px', gap: '8px', margin: '0px' })
// Status glyphs and trailing chevrons of both rows share their columns.
const columns = await Promise.all([
member.locator('[data-state]').first(), row.locator('[data-state]').first(),
].map(locator => locator.evaluate((element) => {
const bounds = element.getBoundingClientRect()
return bounds.left + bounds.width / 2
})))
expect(Math.abs(columns[0]! - columns[1]!)).toBeLessThanOrEqual(0.5)
const hoverStyles = []
for (const target of [memberHover, taskHover]) {
await target.hover()
@@ -488,26 +484,28 @@ describe('web e2e: agent teamwork panel', () => {
expect(await row.locator('[data-team-task-details]').evaluate((element) => {
const style = getComputedStyle(element)
return { fontSize: style.fontSize, indent: style.paddingLeft }
})).toEqual({ fontSize: '12px', indent: '21px' })
})).toEqual({ fontSize: '12px', indent: '30px' })
expect(await row.locator('[data-team-task-details] p, [data-team-task-owner]')
.evaluateAll(elements => elements.every(element => getComputedStyle(element).fontSize === '12px'))).toBe(true)
expect(await row.getByRole('button').getAttribute('aria-expanded')).toBe('true')
expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await scaffold.ctx.agentTeams.updateTask(agent, {
taskId: task.id, expectedRevision: task.revision, action: 'claim',
})
await row.getByRole('img', { name: 'In progress', exact: true }).waitFor()
await row.locator('[data-team-task-owner]').filter({ hasText: 'Owner: lead' }).waitFor()
await action.getByRole('heading', { name: 'Shared tasks 1 in progress', exact: true }).waitFor()
expect(await action.getByRole('button', { name: /^(New task|Edit|Complete|Reopen|Delete)$/u }).count()).toBe(0)
expect(await action.locator('input, select, textarea').count()).toBe(0)
await tasks.getByText('1 in progress', { exact: true }).waitFor()
expect(await tasks.getByRole('button', { name: /^(New task|Edit|Complete|Reopen|Delete)$/u }).count()).toBe(0)
expect(await tasks.locator('input, select, textarea').count()).toBe(0)
const snapshot = await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd)
// The working directory row abbreviates the home directory, which holds the scratch workspace on CI.
const snapshot = await captureStableAria(page, '[data-session-panel]', scaffold.workspaceCwd, {
replacements: [[abbreviateHomePath(scaffold.workspaceCwd, homedir()), '{{cwd}}']],
})
await compareOrRefreshGolden(PANEL_EXPECTED, snapshot, MODE)
expect(projectionReads).not.toHaveBeenCalled()
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
await page.keyboard.press('Escape')
await dismissSessionPanel(page)
}, 60_000)
it('hides the board while disabled and restores its tasks when re-enabled', async () => {
@@ -515,94 +513,47 @@ describe('web e2e: agent teamwork panel', () => {
const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true })
await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false')
expect(await page.locator('[data-subagent-action]').count()).toBe(1)
await closeModelMenu(page)
await page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true }).click()
await page.getByRole('treeitem', { name: /Researcher/u }).waitFor()
const section = await showSubagentsSection(page)
await section.getByRole('treeitem', { name: /Researcher/u }).waitFor()
expect(await page.locator('[data-subagents-section]').count()).toBe(1)
expect(await page.locator('[data-team-panel]').count()).toBe(0)
expect(await page.locator('[data-subagent-panel]').evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await page.locator('[data-subagent-section-header]').count()).toBe(0)
await page.keyboard.press('Escape')
await dismissSessionPanel(page)
await openTeamSettings(page)
await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true')
await closeModelMenu(page)
await page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }).click()
await page.locator('[data-subagent-panel]').getByText('Agent task', { exact: true }).waitFor()
await page.keyboard.press('Escape')
await (await showSharedTasksSection(page)).getByText('Agent task', { exact: true }).waitFor()
await dismissSessionPanel(page)
})
it('keeps the narrow Users trigger focused and opens its catalog only on explicit activation', async () => {
it('keeps the toggle focused in a narrow window and opens the catalog only on explicit activation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-narrow-trigger'))
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true })
const panel = page.locator('[data-subagent-panel]')
const count = trigger.locator('[data-subagent-count]')
const trigger = sessionPanelToggle(page)
const panel = page.locator('[data-session-panel]')
const viewport = page.viewportSize()!
expect(await count.isVisible()).toBe(true)
expect(await trigger.locator('[data-icon="dsw-icon-users-outline-regular"]').count()).toBe(1)
expect(await trigger.locator('[data-icon="dsw-icon-users-outline-regular"]').evaluate((element) => {
const bounds = element.getBoundingClientRect()
return { width: bounds.width, height: bounds.height }
})).toEqual({ width: 14, height: 14 })
expect(await trigger.locator('[data-icon="dsw-icon-chevron-down-outline-regular"]').count()).toBe(0)
expect(await trigger.locator('svg').count()).toBe(1)
await trigger.focus()
const original = await trigger.elementHandle()
if (original === null) throw new Error('Subagent trigger is missing')
if (original === null) throw new Error('Session panel toggle is missing')
try {
await page.setViewportSize({ width: 390, height: 700 })
await expect.poll(() => count.evaluate(element => getComputedStyle(element).display)).toBe('none')
expect(await original.evaluate(element => element.isConnected && element === document.activeElement)).toBe(true)
const expandSidebar = page.locator('[data-sidebar-right-expand]')
const compactStyles = await Promise.all([trigger, expandSidebar].map(control => control.evaluate((element) => {
const bounds = element.getBoundingClientRect()
const icon = element.querySelector('svg')!.getBoundingClientRect()
const style = getComputedStyle(element)
return { width: bounds.width, height: bounds.height, padding: style.padding, radius: style.borderRadius,
color: style.color, iconWidth: icon.width, iconHeight: icon.height }
})))
expect(compactStyles[0]).toEqual(compactStyles[1])
expect(compactStyles[0]).toMatchObject({ width: 28, height: 28, padding: '0px', iconWidth: 15, iconHeight: 15 })
expect(await trigger.evaluate(element => getComputedStyle(element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!).gap)).toBe('8px')
await expandSidebar.hover()
const expandHover = await expandSidebar.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})
await page.mouse.move(1, 1)
await page.keyboard.press('Tab')
const countTooltip = page.getByRole('tooltip', { name: '1 subagent', exact: true })
await countTooltip.waitFor({ state: 'hidden' })
await trigger.hover()
expect(await trigger.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})).toEqual(expandHover)
expect(expandHover.background).not.toBe('rgba(0, 0, 0, 0)')
// Observe beyond the wide trigger's 150ms hover-open deadline.
// Hover alone opens nothing, even past the 150ms delay of hover-opened subagent menus.
await page.waitForTimeout(200)
expect(await panel.count()).toBe(0)
await countTooltip.waitFor({ state: 'visible' })
expect(await panel.count()).toBe(0)
await trigger.click()
await panel.waitFor()
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
expect(await trigger.getAttribute('aria-expanded')).toBe('true')
expect(await page.getByRole('tooltip', { name: '1 subagent', exact: true }).count()).toBe(0)
await panel.getByRole('treeitem', { name: /Researcher/u }).waitFor()
const section = panel.locator(SUBAGENTS_SECTION)
await section.getByRole('treeitem', { name: /Researcher/u }).waitFor()
await panel.locator('[data-team-task]').getByRole('button', { expanded: false }).waitFor()
await trigger.click()
await panel.waitFor({ state: 'detached' })
expect(await trigger.getAttribute('aria-expanded')).toBe('false')
await trigger.press('ArrowDown')
await panel.waitFor()
await page.mouse.move(1, 1)
// Keyboard activation stays pinned beyond the 120ms pointer-leave grace.
await page.waitForTimeout(180)
expect(await panel.count()).toBe(1)
await page.keyboard.press('Escape')
await panel.waitFor({ state: 'detached' })
} finally {
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
await original.dispose()
}
@@ -610,56 +561,77 @@ describe('web e2e: agent teamwork panel', () => {
it('keeps the panel inside the viewport and closes on outside click or Escape', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-team-panel-keyboard'))
const panel = page.locator('[data-subagent-panel]')
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u })
const panel = page.locator('[data-session-panel]')
const section = panel.locator(SUBAGENTS_SECTION)
const tasksHeading = panel.locator(SHARED_TASKS_SECTION).getByRole('heading', { name: 'Shared tasks', exact: true })
const trigger = sessionPanelToggle(page)
const viewport = page.viewportSize()!
await trigger.click()
await panel.getByRole('heading', { name: /Shared tasks/u }).waitFor()
try {
for (const size of [{ width: 760, height: 540 }, { width: 600, height: 420 }, { width: 390, height: 700 }]) {
await page.setViewportSize(size)
await showSessionPanel(page)
await tasksHeading.waitFor()
await expect.poll(() => panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
return element.parentElement === document.body
&& rect.left >= 16 && rect.top >= 16
&& rect.right <= window.innerWidth - 16 && rect.bottom <= window.innerHeight - 16
return element.getAttribute('data-session-panel') === 'overlay'
&& rect.left >= 0 && rect.top >= 0
&& rect.right <= window.innerWidth && rect.bottom <= window.innerHeight
&& [[rect.left + 12, rect.top + 12], [rect.right - 12, rect.bottom - 12]]
.every(([x, y]) => element.contains(document.elementFromPoint(x!, y!)))
})).toBe(true)
}
const row = panel.getByRole('treeitem', { name: /Researcher/u })
const row = section.getByRole('treeitem', { name: /Researcher/u })
const primary = row.getByText(RESEARCHER_DESCRIPTION, { exact: true })
const secondary = row.getByText('team-panel-researcher', { exact: true })
expect(await row.getByRole('button').count()).toBe(0)
expect(await primary.evaluate((element) => {
const style = getComputedStyle(element)
return {
tag: element.tagName, clipped: element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight,
whiteSpace: style.whiteSpace, overflowWrap: style.overflowWrap,
}
})).toEqual({ tag: 'SPAN', clipped: false, whiteSpace: 'normal', overflowWrap: 'anywhere' })
const primaryBounds = await primary.boundingBox()
const secondaryBounds = await secondary.boundingBox()
expect(primaryBounds).not.toBeNull()
expect(secondaryBounds).not.toBeNull()
expect(primaryBounds!.y + primaryBounds!.height).toBeLessThanOrEqual(secondaryBounds!.y)
// The row keeps one line at every width: the description clips, and the name shows in its hover card.
expect(await primary.evaluate(element => ({ tag: element.tagName, whiteSpace: getComputedStyle(element).whiteSpace })))
.toEqual({ tag: 'SPAN', whiteSpace: 'nowrap' })
expect(await row.getByText('team-panel-researcher', { exact: true }).count()).toBe(0)
expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await primary.hover()
const card = page.locator('[data-session-panel-details]')
await card.waitFor()
expect(await card.evaluate(element => [...element.children].slice(0, 2).map(child => child.textContent)))
.toEqual([RESEARCHER_DESCRIPTION, 'Owner: team-panel-researcher'])
// The window has room for the card on neither side of the row, and this description fills a card too
// tall to open under or over the row, so the card covers the row; it stays inside the viewport.
expect(await card.evaluate((element) => {
// The details sit inside the fixed card.
let fixed = element
while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement!
const rect = fixed.getBoundingClientRect()
return rect.left >= 0 && rect.top >= 0 && rect.right <= window.innerWidth && rect.bottom <= window.innerHeight
})).toBe(true)
await page.mouse.move(20, 400)
await card.waitFor({ state: 'detached' })
// A card that fits under its row opens there, from the row's start edge and inside the viewport's
// margin, so the row stays clear.
const task = panel.locator('[data-team-task]').getByRole('button')
await task.hover()
await card.waitFor()
const anchor = await task.locator('xpath=..').boundingBox()
if (anchor === null) throw new Error('the task row has no box')
const placed = await card.evaluate((element) => {
let fixed = element
while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement!
const bounds = fixed.getBoundingClientRect()
return { left: bounds.left, top: bounds.top, right: bounds.right, viewport: window.innerWidth }
})
expect({ below: placed.top - (anchor.y + anchor.height), start: placed.left - anchor.x }).toEqual({ below: 8, start: 0 })
expect(placed.right).toBeLessThanOrEqual(placed.viewport - 8)
const beforeClick = page.url()
await primary.click()
expect(page.url()).toBe(beforeClick)
expect(await page.getByRole('tooltip', { name: RESEARCHER_DESCRIPTION, exact: true }).count()).toBe(0)
expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
expect(await secondary.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await secondary.hover()
expect(await page.getByRole('tooltip').count()).toBe(0)
await panel.getByRole('heading', { name: /Shared tasks/u }).click()
await tasksHeading.click()
expect(await panel.count()).toBe(1)
await page.mouse.click(2, 2)
await panel.waitFor({ state: 'detached' })
await page.setViewportSize(viewport)
await trigger.focus()
await page.keyboard.press('Enter')
await panel.getByRole('heading', { name: /Shared tasks/u }).waitFor()
expect(await panel.evaluate(element => element === document.activeElement)).toBe(true)
await tasksHeading.waitFor()
await panel.locator('[data-team-task]').getByRole('button').focus()
await page.keyboard.press('Escape')
await panel.waitFor({ state: 'detached' })
expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true)
@@ -676,24 +648,7 @@ describe('web e2e: agent teamwork panel', () => {
}
})
it('keeps the hovered panel open when the pointer returns directly to its trigger', async () => {
onTestFailed(async () => {
await saveFailureShot(page, 'web-e2e-agent-team-hover')
console.error('Agent Team hover diagnostics', JSON.stringify({ errors: tripwire.pageErrors, warnings: tripwire.warnings }))
})
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u })
const panel = page.locator('[data-subagent-panel]')
await trigger.hover()
await panel.waitFor()
await panel.hover()
await trigger.hover()
// The assertion spans the 120ms dismissal grace while the pointer stays on the trigger.
await page.waitForTimeout(180)
expect(await panel.count()).toBe(1)
await page.keyboard.press('Escape')
})
it('keeps compact tasks ordered, opens one full detail at a time, and scrolls only the fixed-width menu', async () => {
it('keeps compact tasks ordered, opens one full detail at a time, and scrolls only the Session panel', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-compact-details'))
const agent = scaffold.ctx.agents.list()[0]!
const completed = await scaffold.ctx.agentTeams.createTask(agent, {
@@ -714,64 +669,46 @@ describe('web e2e: agent teamwork panel', () => {
subject, description, blockedBy: [blocker.id], writeScopes: ['src/web/components'],
})
const viewport = page.viewportSize()!
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u })
const panel = page.locator('[data-subagent-panel]')
const board = panel.locator('[data-team-panel]')
const panel = page.locator('[data-session-panel]')
const section = panel.locator(SHARED_TASKS_SECTION)
const board = section.locator('[data-team-panel]')
const row = board.locator(`[data-team-task="${task.id}"]`)
const emptyRow = board.locator(`[data-team-task="${completed.id}"]`)
onTestFinished(() => page.setViewportSize(viewport))
// Constrain the menu so closed and expanded task rows both exercise its scrollbar.
await page.setViewportSize({ width: viewport.width, height: 540 })
await trigger.click()
// Constrain the panel so closed and expanded task rows both exercise its scrollbar.
await page.setViewportSize({ width: viewport.width, height: 500 })
await showSharedTasksSection(page)
await row.waitFor()
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await board.locator('[data-team-task-details], article').count()).toBe(0)
expect(await board.getByRole('button', { expanded: false }).count()).toBe(4)
expect(await board.locator('[data-team-task]').evaluateAll(elements => elements.map(element => element.getAttribute('data-status'))))
.toEqual(['in_progress', 'completed', 'pending', 'pending'])
const counts = board.getByText('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending', { exact: true })
.toEqual(['in_progress', 'pending', 'pending', 'completed'])
const counts = section.getByText('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending', { exact: true })
await counts.waitFor()
expect(await counts.textContent()).toBe('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending')
expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await panel.getByRole('button', { name: /^Show (more|less)$/u }).count()).toBe(0)
expect(await section.locator('h2 button, h3 button').count()).toBe(0)
expect(await section.getByRole('button', { name: /^Show (more|less)$/u }).count()).toBe(0)
await row.getByRole('img', { name: 'Blocked by dependencies', exact: true }).waitFor()
// The panel itself scrolls; its client box ends where its scrollbar track begins.
const measureScroll = async () => panel.evaluate((element) => {
const style = getComputedStyle(element)
const bounds = element.getBoundingClientRect()
const scroller = element.querySelector('[role="tree"]')!.parentElement!
const scrollStyle = getComputedStyle(scroller)
const scrollBounds = scroller.getBoundingClientRect()
const taskBounds = element.querySelector('[data-team-task] button')!.getBoundingClientRect()
const scrollbarWidth = Number.parseFloat(getComputedStyle(scroller, '::-webkit-scrollbar').width)
const trackLeft = bounds.left + element.clientLeft + element.clientWidth
return {
innerWidth: bounds.width - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight)
- Number.parseFloat(style.borderLeftWidth) - Number.parseFloat(style.borderRightWidth),
clientWidth: scroller.clientWidth, clientHeight: scroller.clientHeight, scrollHeight: scroller.scrollHeight,
overflowing: scroller.scrollHeight > scroller.clientHeight,
gutter: scrollStyle.scrollbarGutter, marginRight: scrollStyle.marginRight,
trackMargin: scrollStyle.getPropertyValue('--dsh-scrollbar-track-margin').trim(),
overflowing: element.scrollHeight > element.clientHeight,
taskLeft: taskBounds.left, taskRight: taskBounds.right,
trackLeft: scrollBounds.right - scrollbarWidth, trackRight: scrollBounds.right, panelRight: bounds.right,
arrowsBeforeTrack: [...element.querySelectorAll('[data-team-task] button svg')]
.every(arrow => arrow.getBoundingClientRect().right <= scrollBounds.right - scrollbarWidth),
.every(arrow => arrow.getBoundingClientRect().right <= trackLeft),
}
})
const closedScroll = await measureScroll()
expect(closedScroll.overflowing, JSON.stringify(closedScroll)).toBe(true)
expect(Math.abs(closedScroll.clientWidth - closedScroll.innerWidth), JSON.stringify(closedScroll)).toBeLessThanOrEqual(1)
expect(closedScroll.gutter).toBe('stable')
expect(closedScroll.marginRight).toBe('-5px')
expect(closedScroll.trackMargin).toBe('6px')
await row.getByRole('button').click()
const expandedScroll = await measureScroll()
expect(expandedScroll.overflowing).toBe(true)
expect(expandedScroll.clientWidth).toBe(closedScroll.clientWidth)
expect(expandedScroll.taskLeft).toBe(closedScroll.taskLeft)
expect(expandedScroll.taskRight).toBe(closedScroll.taskRight)
expect(expandedScroll.arrowsBeforeTrack).toBe(true)
expect(expandedScroll.trackLeft).toBeGreaterThanOrEqual(expandedScroll.panelRight - 6)
expect(expandedScroll.trackRight).toBeLessThanOrEqual(expandedScroll.panelRight - 1)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
const details = row.locator('[data-team-task-details]')
expect(await details.locator('p:not([data-team-task-owner])').textContent()).toBe(description)
expect(await details.locator('[data-team-task-owner]').textContent()).toBe('Owner: Unowned')
@@ -786,35 +723,32 @@ describe('web e2e: agent teamwork panel', () => {
await page.setViewportSize({ width: 390, height: 700 })
await expect.poll(() => panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
return rect.width === Math.min(360, innerWidth - 32) && rect.left >= 16 && rect.right <= innerWidth - 16
&& rect.top >= 16 && rect.bottom <= innerHeight - 16
return element.getAttribute('data-session-panel') === 'overlay'
&& rect.left >= 0 && rect.right <= innerWidth && rect.top >= 0 && rect.bottom <= innerHeight
&& element.scrollWidth <= element.clientWidth
})).toBe(true)
expect(await panel.locator('*').evaluateAll((elements) => {
const scrollers = elements.filter(element =>
expect(await panel.evaluate((panelElement) => {
const scrollers = [panelElement, ...panelElement.querySelectorAll('*')].filter(element =>
['auto', 'scroll'].includes(getComputedStyle(element).overflowY)
&& element.scrollHeight > element.clientHeight)
return scrollers.map(element => ({
hasHeader: element.querySelector('[data-subagent-section-header]') !== null,
panel: element === panelElement,
hasTree: element.querySelector('[role="tree"]') !== null,
hasBoard: element.querySelector('[data-team-panel]') !== null,
fitsWidth: element.scrollWidth <= element.clientWidth,
}))
})).toEqual([{ hasHeader: true, hasTree: true, hasBoard: true, fitsWidth: true }])
const narrowScroll = await measureScroll()
expect(Math.abs(narrowScroll.clientWidth - narrowScroll.innerWidth), JSON.stringify(narrowScroll)).toBeLessThanOrEqual(1)
expect(narrowScroll.arrowsBeforeTrack).toBe(true)
const scroller = panel.getByRole('tree').locator('..')
await scroller.hover({ position: { x: 20, y: 20 } })
})).toEqual([{ panel: true, hasTree: true, hasBoard: true, fitsWidth: true }])
expect((await measureScroll()).arrowsBeforeTrack).toBe(true)
await panel.hover({ position: { x: 20, y: 20 } })
await Promise.all([
scroller.evaluate(element => new Promise<void>((resolve) => {
panel.evaluate(element => new Promise<void>((resolve) => {
element.addEventListener('scrollend', () => { resolve() }, { once: true })
})),
page.mouse.wheel(0, 180),
])
await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBeGreaterThan(0)
await scroller.evaluate((element) => { element.scrollTo({ top: 0 }) })
await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBe(0)
await expect.poll(() => panel.evaluate(element => element.scrollTop)).toBeGreaterThan(0)
await panel.evaluate((element) => { element.scrollTo({ top: 0 }) })
await expect.poll(() => panel.evaluate(element => element.scrollTop)).toBe(0)
expect(await row.getByText(subject, { exact: true }).evaluate(element =>
element.scrollWidth <= element.clientWidth && getComputedStyle(element).whiteSpace === 'pre-wrap')).toBe(true)
expect(await details.locator('p:not([data-team-task-owner])').evaluate(element => element.scrollHeight === element.clientHeight)).toBe(true)
@@ -828,13 +762,17 @@ describe('web e2e: agent teamwork panel', () => {
expect(await details.locator('[data-team-task-owner], [data-team-task-owner] span')
.evaluateAll(elements => elements.map(element => getComputedStyle(element).color)))
.toEqual([detailColor, detailColor, detailColor])
expect(await counts.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
const titleBounds = await board.getByText('Shared tasks', { exact: true }).boundingBox()
// Long progress clips on the title's line; the title itself keeps its full width.
const title = section.getByRole('heading', { name: 'Shared tasks', exact: true })
expect(await title.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
const titleBounds = await title.boundingBox()
const countBounds = await counts.boundingBox()
const sectionBounds = await section.boundingBox()
expect(titleBounds).not.toBeNull()
expect(countBounds).not.toBeNull()
expect(countBounds!.y).toBeGreaterThanOrEqual(titleBounds!.y + titleBounds!.height)
await compareOrRefreshGolden(RESIZE_EXPECTED, await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd), MODE)
expect(Math.abs((countBounds!.y + countBounds!.height / 2) - (titleBounds!.y + titleBounds!.height / 2))).toBeLessThanOrEqual(1)
expect(countBounds!.x + countBounds!.width).toBeLessThanOrEqual(sectionBounds!.x + sectionBounds!.width)
await compareOrRefreshGolden(RESIZE_EXPECTED, await captureStableAria(page, SHARED_TASKS_SECTION, scaffold.workspaceCwd), MODE)
await emptyRow.getByRole('button').click()
expect(await row.getAttribute('data-expanded')).toBe('false')
expect(await row.locator('[data-team-task-details]').count()).toBe(0)
@@ -846,13 +784,45 @@ describe('web e2e: agent teamwork panel', () => {
await emptyRow.getByRole('button').click()
expect(await board.locator('[data-team-task-details]').count()).toBe(0)
await page.setViewportSize(viewport)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
} finally {
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
}
})
it('holds back the tasks past five behind the fold control and keeps the choice while the panel is hidden', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-task-fold'))
const agent = scaffold.ctx.agents.list()[0]!
const before = scaffold.ctx.agentTeams.listTasks(agent).filter(task => task.status !== 'deleted')
// The tasks so far: one in progress, pending ones, and a completed one. Pending tasks bring the list to eight.
for (let index = before.length; index < 8; index++) {
await scaffold.ctx.agentTeams.createTask(agent, { subject: `Fold task ${String(index)}`, description: 'Fills the list.', writeScopes: [] })
}
const section = await showSharedTasksSection(page)
const tasks = section.locator('[data-team-task]')
const fold = section.locator('[data-session-panel-row="fold"]')
const statuses = (): Promise<(string | null)[]> => tasks.evaluateAll(items => items.map(item => item.getAttribute('data-status')))
// Five tasks show: the one in progress, then pending ones in source order. The completed task is held back.
await expect.poll(statuses, { timeout: 15_000 }).toEqual(['in_progress', 'pending', 'pending', 'pending', 'pending'])
expect(await fold.textContent()).toBe('Show 3 more')
// The control follows the list, at the row height, with its chevron under the state marks and its text under the subjects.
expect(await section.getByRole('list').locator('[data-session-panel-row="fold"]').count()).toBe(0)
expect(await foldControlLayout(fold, tasks.first().getByRole('button'), '[class*="subject"]'))
.toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' })
await section.getByRole('button', { name: 'Show 3 more (shared tasks)', exact: true }).click()
await expect.poll(statuses).toEqual(['in_progress', 'pending', 'pending', 'pending', 'pending', 'pending', 'pending', 'completed'])
const less = section.getByRole('button', { name: 'Show less (shared tasks)', exact: true })
expect([await less.textContent(), await less.getAttribute('aria-expanded')]).toEqual(['Show less', 'true'])
// The choice is the Session's: it holds while the panel is hidden.
await dismissSessionPanel(page)
await showSharedTasksSection(page)
await expect.poll(() => tasks.count()).toBe(8)
await less.click()
await expect.poll(() => tasks.count()).toBe(5)
expect(tripwire.pageErrors).toEqual([])
await dismissSessionPanel(page)
})
it('confirms disabling after a recorded model request and keeps cancellation side-effect free', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-disable-confirmation'))
const agent = scaffold.ctx.agents.list()[0]!
@@ -897,24 +867,21 @@ describe('web e2e: agent teamwork panel', () => {
expect(tripwire.pageErrors).toEqual([])
})
it('removes both section headings and the board divider when the last shared task is deleted', async () => {
it('hides the Shared tasks section when the last shared task is deleted', async () => {
const agent = scaffold.ctx.agents.list()[0]!
await page.getByRole('button', { name: '1 subagent', exact: true }).click()
const panel = page.locator('[data-subagent-panel]')
await panel.locator('[data-team-panel]').waitFor()
const tasks = await showSharedTasksSection(page)
await tasks.locator('[data-team-panel]').waitFor()
for (const task of scaffold.ctx.agentTeams.listTasks(agent).toReversed()) {
if (task.status === 'deleted') continue
await scaffold.ctx.agentTeams.updateTask(agent, {
taskId: task.id, expectedRevision: task.revision, action: 'delete',
})
}
await panel.locator('[data-team-panel]').waitFor({ state: 'detached' })
expect(await panel.locator('[data-subagent-section-header]').count()).toBe(0)
expect(await panel.getByRole('heading').count()).toBe(0)
expect(await panel.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await panel.getByRole('treeitem', { name: /Researcher/u }).count()).toBe(1)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await page.keyboard.press('Escape')
await tasks.locator('[data-team-panel]').waitFor({ state: 'detached' })
await tasks.waitFor({ state: 'hidden' })
expect(await page.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await page.locator(SUBAGENTS_SECTION).getByRole('treeitem', { name: /Researcher/u }).count()).toBe(1)
await dismissSessionPanel(page)
})
it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
@@ -1047,21 +1014,19 @@ it.each(RECEIPT_LOCALES)('renders historical Team failures in $language without
})
})
it('shows the Chinese empty subagent section above compact shared tasks', async () => {
it('shows the Chinese Shared tasks section without subagents', async () => {
await withTeamReceiptPage(RECEIPT_LOCALES[1], async (page, scaffold) => {
const agent = scaffold.ctx.agents.list()[0]!
await scaffold.ctx.agentTeams.setEnabled(agent, true)
await scaffold.ctx.agentTeams.createTask(agent, {
subject: '准备协作', description: '先准备共享任务,再创建子智能体。',
})
await page.getByRole('button', { name: '0 个子智能体', exact: true }).click()
const panel = page.locator('[data-subagent-panel]')
await panel.getByText('暂无子智能体', { exact: true }).waitFor()
expect(await panel.locator('[data-subagent-section-header]').textContent()).toBe('子智能体')
expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await panel.getByRole('heading', { name: '共享任务 1 待处理', exact: true }).waitFor()
expect(await panel.locator('[data-team-task-details]').count()).toBe(0)
const section = await showSharedTasksSection(page)
await section.getByText('准备协作', { exact: true }).waitFor()
expect(await section.getByRole('heading', { level: 2 }).locator('..').textContent()).toBe('共享任务1 待处理')
expect(await section.locator('h2 button, h3 button').count()).toBe(0)
expect(await section.locator('[data-team-task-details]').count()).toBe(0)
expect(await page.locator(SUBAGENTS_SECTION).isVisible()).toBe(false)
})
})
+1 -2
View File
@@ -10,9 +10,8 @@ const PANELS = [
{ file: 'client/ui-schedule/src/client/TaskMenu.module.css', classes: 'list portal scrollable alignEnd', align: 'end' },
{ file: 'client/ui-schedule/src/client/PickerPopover.module.css', classes: 'panel', align: 'start' },
{ file: 'client/ui-schedule/src/client/ScheduleCatalogAction.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-subagent/src/client/SubagentHeaderLineage.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-subagent/src/client/SubagentCatalog.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-approval/src/client/ApprovalPanel.module.css', classes: 'warningPopover', align: 'end' },
{ file: 'client/ui-jobs/src/client/JobListAction.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-conversation/src/client/skeleton/ContextMeter.module.css', classes: 'panel', align: 'start' },
{ file: 'client/ui-chat/src/client/chat/stat-dialog.module.css', classes: 'panel', align: 'start' },
{ file: 'client/ui-sidebar-documentpreview/src/client/office/FontNotice.module.css', classes: 'panel', align: 'start' },
+152 -130
View File
@@ -1,6 +1,6 @@
import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
// Session-header background jobs driven by a real `ctx.jobs` entry. No model
// call is involved.
// The Session panel's background-jobs section driven by a real `ctx.jobs`
// entry. No model call is involved.
import { readFile, writeFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
@@ -16,12 +16,13 @@ import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
import { foldControlLayout, newEnglishPage, saveFailureShot, sessionPanelToggle, showSessionPanel } from './support.ts'
const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url))
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/background-job-list', import.meta.url))
const RUNNING_EXPECTED = join(SNAPSHOT_DIR, 'running.expected.md')
const SETTLED_EXPECTED = join(SNAPSHOT_DIR, 'settled.expected.md')
const SECTION = '[data-session-panel-section="background-jobs"]'
const MODE = webSnapshotMode()
const SEED_ID = 'background-job-list-web-e2e'
// A hold on a barrier file the test owns in the job's cwd: the process never
@@ -82,12 +83,18 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => {
await scaffold?.close()
})
it('shows a running background job in the header without a refresh, then kills it from the two-press stop control', async () => {
it('shows a running background job in the Session panel without a refresh, then kills it from the two-press stop control', async () => {
let phase = 'running'
onTestFailed(() => saveFailureShot(page, `web-e2e-background-job-${phase}`))
// Polling for zero would pass at t=0 before delivery and prove nothing.
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
expect(await trigger.count()).toBe(0)
const toggle = sessionPanelToggle(page)
const section = (await showSessionPanel(page)).locator(SECTION)
const list = section.getByRole('list')
// The mounted section keeps the roster stream open but renders no rows
// yet, so the panel hides it with its title. A one-shot check: polling for
// zero would pass at t=0 before delivery and prove nothing.
expect(await section.count()).toBe(1)
expect(await section.isVisible()).toBe(false)
expect(await list.count()).toBe(0)
const started = await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
@@ -101,31 +108,26 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => {
if (matched === null) throw new Error(`background bash reported no job id: ${reported}`)
const jobId = brandString<JobId>(matched[0])
await trigger.waitFor({ timeout: 15_000 })
expect(await trigger.locator('[data-state="ongoing"]').count()).toBe(1)
expect(await trigger.locator('[data-icon="dsw-icon-chevron-down-outline-regular"]').count()).toBe(0)
await trigger.hover()
const list = page.getByRole('list', { name: 'Background jobs' })
const row = list.getByRole('listitem').first()
await row.waitFor({ timeout: 10_000 })
await row.waitFor({ timeout: 15_000 })
await expect.poll(() => row.textContent()).toContain(COMMAND)
expect(await trigger.getAttribute('aria-expanded')).toBe('true')
await row.hover()
await row.getByRole('button', { name: /Show live output/ }).focus()
await page.mouse.move(2, 2)
// Focusing a menu control pins it beyond the 120ms hover-leave deadline.
await page.waitForTimeout(180)
expect(await list.count()).toBe(1)
await trigger.click()
expect(await section.getByRole('heading', { name: 'Background jobs', level: 2 }).isVisible()).toBe(true)
expect(await row.locator('[data-state="ongoing"]').count()).toBe(1)
expect(await page.locator('[data-jobs-running]').count()).toBe(0)
// Hiding the panel unmounts the section, and a blue dot on the toggle reports the running job.
await toggle.click()
await list.waitFor({ state: 'detached' })
await trigger.click()
await list.waitFor()
await page.mouse.move(2, 2)
await page.waitForTimeout(180)
expect(await list.count()).toBe(1)
expect(await trigger.getAttribute('aria-label')).toBe('1 background job')
const dot = page.locator('[data-jobs-running]')
await dot.waitFor()
await page.getByRole('button', { name: 'Session panel Background jobs running: 1', exact: true }).waitFor()
expect(await dot.evaluate(element => getComputedStyle(element).width)).toBe('6px')
// Showing it again lists the live job, and the dot goes away.
await showSessionPanel(page)
await row.waitFor({ timeout: 10_000 })
expect(await toggle.getAttribute('aria-expanded')).toBe('true')
await dot.waitFor({ state: 'detached' })
const running = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd, { runningJobs: 'keep' })
const running = await captureStableAria(page, SECTION, scaffold.workspaceCwd)
await compareOrRefreshGolden(RUNNING_EXPECTED, running, MODE)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
@@ -133,151 +135,171 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => {
phase = 'settled'
// The whole human path: arm, confirm, job.kill, registry kill, jobs
// frames flipping the row — no registry call from the test.
const stop = page.locator('[data-kill-state]')
const stop = section.locator('[data-kill-state]')
await stop.waitFor({ timeout: 10_000 })
await stop.click()
await expect.poll(() => stop.getAttribute('data-kill-state')).toBe('armed')
await stop.click()
expect(await trigger.getAttribute('aria-label')).toBe('1 background job')
// The unclaimed report's reason lands in the settled row's detail.
await expect.poll(
() => page.getByRole('list', { name: 'Background jobs' }).textContent(),
{ timeout: 15_000 },
).toContain('cancelled by the user')
// The unclaimed report's reason lands in the settled row's detail; presses
// inside the overlay leave it open.
await expect.poll(() => list.textContent(), { timeout: 15_000 }).toContain('cancelled by the user')
expect(await toggle.getAttribute('aria-expanded')).toBe('true')
expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('killed')
const settled = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd)
const settled = await captureStableAria(page, SECTION, scaffold.workspaceCwd)
await compareOrRefreshGolden(SETTLED_EXPECTED, settled, MODE)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 90_000)
it('keeps the open list above the expanded right sidebar and in the header Tab order', async () => {
it('opens the section over the conversation beside the expanded right sidebar and closes it with Escape', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-right-sidebar'))
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click()
const toggle = sessionPanelToggle(page)
await page.getByRole('button', { name: 'Open right sidebar' }).click()
const sidebar = page.locator('[data-rightbar-col]')
// A toggle holds data-animating on the frame until its tracks settle.
await expect.poll(() => sidebar.evaluate(column => column.parentElement?.hasAttribute('data-animating'))).toBe(false)
await trigger.click()
const list = page.getByRole('list', { name: 'Background jobs' })
await list.waitFor({ timeout: 10_000 })
// The list crosses into the sidebar column, so the hit test below covers it.
const [menuBox, sidebarBox] = await Promise.all([list.boundingBox(), sidebar.boundingBox()])
if (menuBox === null || sidebarBox === null) throw new Error('job list geometry is unavailable')
expect(menuBox.x + menuBox.width).toBeGreaterThan(sidebarBox.x)
// Every corner of the list hit-tests to the list itself; the inset clears its rounded corners.
const covered = await list.evaluate((menu) => {
const rect = menu.getBoundingClientRect()
const panel = await showSessionPanel(page)
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
const section = panel.locator(SECTION)
const settledToggle = section.getByRole('button', { name: 'Finished 1', exact: true })
await settledToggle.waitFor({ timeout: 10_000 })
// The overlay stays in the conversation body, clear of the sidebar column.
const [panelBox, sidebarBox] = await Promise.all([panel.boundingBox(), sidebar.boundingBox()])
if (panelBox === null || sidebarBox === null) throw new Error('Session panel geometry is unavailable')
expect(panelBox.x + panelBox.width).toBeLessThanOrEqual(sidebarBox.x)
// Every corner of the panel hit-tests to the panel itself; the inset clears its rounded corners.
const covered = await panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
const inset = 20
const points: Array<[number, number]> = [
[rect.left + inset, rect.top + inset], [rect.right - inset, rect.top + inset],
[rect.left + inset, rect.bottom - inset], [rect.right - inset, rect.bottom - inset],
]
return points.filter(([x, y]) => !menu.contains(document.elementFromPoint(x, y)))
return points.filter(([x, y]) => !element.contains(document.elementFromPoint(x, y)))
})
expect(covered).toEqual([])
// Keyboard order matches the in-place list: the trigger leads into the
// list, and Tab off its last control reaches the control after the trigger.
const after = await trigger.evaluate((node) => {
const all = [...document.querySelectorAll<HTMLElement>('button, a[href], [tabindex]:not([tabindex="-1"])')]
const outside = all.filter(el => el.closest('[aria-label="Background jobs"]') === null && el.tabIndex >= 0)
return outside[outside.indexOf(node as HTMLElement) + 1]?.outerHTML.slice(0, 120)
})
expect(after).toMatch(/^<button/)
await trigger.focus()
await page.keyboard.press('Tab')
expect(await list.evaluate(menu => menu.contains(document.activeElement))).toBe(true)
const controls = await list.evaluate(menu => menu.querySelectorAll('button:not(:disabled)').length)
for (let i = 1; i < controls; i += 1) await page.keyboard.press('Tab')
await page.keyboard.press('Tab')
expect(await page.evaluate(() => document.activeElement?.outerHTML.slice(0, 120))).toBe(after)
await trigger.focus()
await page.keyboard.press('Tab')
// Escape from a control in the section closes the overlay and returns focus to the toggle.
await settledToggle.focus()
await page.keyboard.press('Escape')
await list.waitFor({ state: 'detached', timeout: 10_000 })
expect(await trigger.evaluate(node => node === document.activeElement)).toBe(true)
await panel.waitFor({ state: 'detached', timeout: 10_000 })
expect(await toggle.getAttribute('aria-expanded')).toBe('false')
expect(await toggle.evaluate(node => node === document.activeElement)).toBe(true)
}, 60_000)
it('keeps the compact Layers trigger focused and opens jobs only on click or keyboard', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-compact-trigger'))
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
const list = page.getByRole('list', { name: 'Background jobs' })
const count = trigger.locator('[data-job-count]')
it('fits the section into the narrow overlay and closes it on a press outside', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-narrow-overlay'))
const toggle = sessionPanelToggle(page)
const viewport = page.viewportSize()!
await page.getByRole('button', { name: 'Collapse right sidebar', exact: true }).click()
await expect.poll(() => page.locator('[data-rightbar-col]')
.evaluate(column => column.parentElement?.hasAttribute('data-animating'))).toBe(false)
await page.getByRole('button', { name: 'Open right sidebar', exact: true }).waitFor()
await page.mouse.move(2, 2)
expect(await count.isVisible()).toBe(true)
expect(await trigger.locator('[data-icon="dsw-icon-layers-outline-regular"]').count()).toBe(1)
expect(await trigger.locator('svg').count()).toBe(1)
expect(await trigger.locator('svg').evaluate((element) => {
const bounds = element.getBoundingClientRect()
return [bounds.width, bounds.height]
})).toEqual([14, 14])
await trigger.focus()
const original = await trigger.elementHandle()
if (original === null) throw new Error('Background jobs trigger is missing')
await toggle.focus()
const original = await toggle.elementHandle()
if (original === null) throw new Error('Session panel toggle is missing')
try {
await page.setViewportSize({ width: 390, height: 700 })
await expect.poll(() => count.evaluate(element => getComputedStyle(element).display)).toBe('none')
expect(await original.evaluate(element => element.isConnected && element === document.activeElement)).toBe(true)
const expandSidebar = page.locator('[data-sidebar-right-expand]')
const compactStyles = await Promise.all([trigger, expandSidebar].map(control => control.evaluate((element) => {
const style = getComputedStyle(element)
const bounds = element.getBoundingClientRect()
const icon = element.querySelector('svg')!.getBoundingClientRect()
return { width: bounds.width, height: bounds.height, padding: style.padding, radius: style.borderRadius,
color: style.color, iconWidth: icon.width, iconHeight: icon.height }
})))
expect(compactStyles[0]).toEqual(compactStyles[1])
expect(compactStyles[0]).toMatchObject({ width: 28, height: 28, padding: '0px', iconWidth: 15, iconHeight: 15 })
expect(await trigger.evaluate(element => getComputedStyle(element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!).gap)).toBe('8px')
await expandSidebar.hover()
const expandHover = await expandSidebar.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})
await expect.poll(() => trigger.evaluate((element) => {
const bounds = element.getBoundingClientRect()
return element.contains(document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2))
})).toBe(true)
await trigger.hover()
expect(await trigger.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})).toEqual(expandHover)
expect(expandHover.background).not.toBe('rgba(0, 0, 0, 0)')
// Compact hover stays closed beyond the wide trigger's 150ms open deadline.
await page.waitForTimeout(200)
expect(await list.count()).toBe(0)
await trigger.click()
await list.waitFor()
const panel = await showSessionPanel(page)
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
const list = panel.locator(SECTION).getByRole('list')
await list.getByRole('button', { name: 'Finished 1', exact: true }).waitFor()
await trigger.click()
await list.waitFor({ state: 'detached' })
await trigger.press('ArrowDown')
await list.waitFor()
expect(await list.getByRole('button').first().evaluate(element => element === document.activeElement)).toBe(true)
await page.mouse.move(2, 2)
// Keyboard activation remains pinned after leaving both trigger and menu.
await page.waitForTimeout(180)
expect(await list.count()).toBe(1)
await page.mouse.click(2, 2)
await list.waitFor({ state: 'detached' })
expect(await trigger.getAttribute('aria-expanded')).toBe('false')
// The long command truncates inside its row instead of widening the panel past the viewport.
const fit = await panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
const rows = [...element.querySelectorAll<HTMLElement>('[data-jobs-section] li')]
return {
inViewport: rect.left >= 0 && rect.right <= innerWidth,
panelOverflow: element.scrollWidth > element.clientWidth,
rowOverflow: rows.some(row => row.getBoundingClientRect().right > rect.right),
}
})
expect(fit).toEqual({ inViewport: true, panelOverflow: false, rowOverflow: false })
// The overlay's inline margin is transcript: a press there is outside the panel.
const box = await panel.boundingBox()
if (box === null) throw new Error('Session panel geometry is unavailable')
expect(box.x).toBeGreaterThan(4)
await page.mouse.click(box.x / 2, box.y + box.height / 2)
await panel.waitFor({ state: 'detached' })
expect(await toggle.getAttribute('aria-expanded')).toBe('false')
} finally {
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
await original.dispose()
}
})
it('marks a job that finished with a nonzero exit code with the warning dot', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-nonzero-exit'))
await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
callId: brandString<ToolCallId>('background-job-list-nonzero-e2e'),
name: 'bash',
arguments: { command: 'exit 3', description: 'Exit with a failure', run_in_background: true },
agent: scaffold.ctx.agents.list()[0]!,
})
const panel = await showSessionPanel(page)
const row = panel.locator(SECTION).getByRole('listitem').filter({ hasText: 'exit 3' })
await row.getByText('bash · exit code: 3', { exact: true }).waitFor({ timeout: 15_000 })
expect(await row.locator('[data-state]').getAttribute('data-state')).toBe('warning')
})
it('holds back the rows past five in each group behind its fold control and keeps the choice while the panel is hidden', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-folds'))
// Seven jobs on the suite's barrier file: they run until this case, or `afterAll`, releases it.
for (let index = 0; index < 7; index++) {
await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
callId: brandString<ToolCallId>(`background-job-list-fold-${String(index)}`),
name: 'bash',
arguments: { command: `: fold-${String(index)}; ${COMMAND}`, description: 'Hold a slot for the fold', run_in_background: true },
agent,
})
}
const section = (await showSessionPanel(page)).locator(SECTION)
const rows = section.locator('[data-job-row]')
const liveRows = section.locator('[data-job-row]:has([data-state="ongoing"])')
const folds = section.locator('[data-session-panel-row="fold"]')
const names = async (): Promise<(string | undefined)[]> => (await liveRows.allTextContents()).map(text => /fold-\d/.exec(text)?.[0])
// The five jobs started last show, the most recent first, and the group's fold control follows them.
await expect.poll(names, { timeout: 20_000 }).toEqual(['fold-6', 'fold-5', 'fold-4', 'fold-3', 'fold-2'])
expect(await folds.allTextContents()).toEqual(['Show 2 more running'])
expect(await section.locator('li:has([data-session-panel-row="fold"])').count()).toBe(1)
// The control is one more row: the row height, its chevron under the state marks, its text under the commands.
expect(await foldControlLayout(folds.first(), liveRows.first(), '[data-job-label]'))
.toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' })
const more = section.getByRole('button', { name: 'Show 2 more running (running background jobs)', exact: true })
await more.click()
await expect.poll(names).toEqual(['fold-6', 'fold-5', 'fold-4', 'fold-3', 'fold-2', 'fold-1', 'fold-0'])
const less = section.getByRole('button', { name: 'Show less (running background jobs)', exact: true })
expect([await less.textContent(), await less.getAttribute('aria-expanded')]).toEqual(['Show less', 'true'])
// The same button stays under the pointer's focus across the change.
expect(await less.evaluate(element => element === document.activeElement)).toBe(true)
// The choice is the Session's: hiding the panel unmounts the section, and showing it again lists every live row.
await sessionPanelToggle(page).click()
await section.getByRole('list').waitFor({ state: 'detached' })
await showSessionPanel(page)
await expect.poll(() => liveRows.count(), { timeout: 10_000 }).toBe(7)
// Released, the jobs settle. With nothing live the settled group opens, with its five latest rows and its own control.
await writeFile(join(scaffold.workspaceCwd, RELEASE), '')
await expect.poll(() => liveRows.count(), { timeout: 30_000 }).toBe(0)
const header = section.getByRole('button', { name: /^Finished \d+$/ })
await expect.poll(async () => Number(/\d+/.exec(await header.textContent() ?? '')?.[0]), { timeout: 15_000 }).toBeGreaterThanOrEqual(7)
const settled = Number(/\d+/.exec(await header.textContent() ?? '')?.[0])
expect(await header.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => rows.count()).toBe(5)
expect(await folds.allTextContents()).toEqual([`Show ${String(settled - 5)} more finished`])
expect(await foldControlLayout(folds.first(), rows.first(), '[data-job-label]'))
.toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' })
await folds.first().getByRole('button').click()
await expect.poll(() => rows.count()).toBe(settled)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 120_000)
it('keeps its snapshot inventory closed', async () => {
await assertFixtureInventory(SNAPSHOT_DIR, ['running.expected.md', 'settled.expected.md'])
})
+48 -3
View File
@@ -271,7 +271,20 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
const opened = await context.newPage()
tripwires.push(watchConsole(opened))
await opened.addInitScript(() => {
Object.defineProperty(globalThis, 'dshDesktop', { value: { protocolVersion: 1 } })
// The update carrier stays idle until a scenario publishes a status for the account row.
let update: { phase: string; version?: string } = { phase: 'idle' }
const updateListeners = new Set<(state: typeof update) => void>()
Object.defineProperty(globalThis, '__bonusPublishUpdate', {
value: (state: typeof update) => { update = state; for (const listener of updateListeners) listener(state) },
})
Object.defineProperty(globalThis, 'dshDesktop', { value: { protocolVersion: 1, updates: {
status: () => Promise.resolve(update),
open: () => Promise.resolve(),
subscribe: (listener: (state: typeof update) => void) => {
updateListeners.add(listener)
return () => { updateListeners.delete(listener) }
},
} } })
// The embedded Platform view is a native child window owned by the Desktop shell.
// The double answers immediately and records the calls, so the scenario observes
// which page was opened and that returning destroyed the view.
@@ -667,6 +680,30 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
})
expect(transition).toBe('0.25s ease-out')
observations.push(`stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=${transition}`)
// A Desktop update status shares the account row and leaves the card row at full width.
const publishUpdate = (state: { phase: string; version?: string }) => stackPage.evaluate((value) => {
(globalThis as typeof globalThis & { __bonusPublishUpdate: (next: typeof value) => void }).__bonusPublishUpdate(value)
}, state)
await publishUpdate({ phase: 'installing', version: '0.1.5' })
const updateTag = stackPage.getByText('正在准备重启…', { exact: true })
await updateTag.waitFor()
const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
await mkdir(artifactDir, { recursive: true })
await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-update-tag.png'), clip: { x: 0, y: 560, width: 420, height: 400 } })
const taggedBox = await cards.first().boundingBox()
const tagBox = await updateTag.boundingBox()
const accountBox = await stackPage.getByRole('button', { name: '账号菜单', exact: true }).boundingBox()
expect(taggedBox!.x).toBeCloseTo(10, 0)
expect(taggedBox!.width).toBeCloseTo(260, 0)
expect(taggedBox!.y + taggedBox!.height).toBeLessThanOrEqual(accountBox!.y)
expect(tagBox!.y).toBeGreaterThanOrEqual(accountBox!.y)
expect(tagBox!.y + tagBox!.height).toBeLessThanOrEqual(accountBox!.y + accountBox!.height)
// The card floats over the session list: the list still reaches down to the card's bottom edge.
const listBottom = await stackPage.locator('[class*="scrollRegion"]').first().evaluate(element => element.getBoundingClientRect().bottom)
expect(listBottom).toBeGreaterThanOrEqual(taggedBox!.y + taggedBox!.height - 1)
observations.push('stack.update-tag card=260 left-inset=10 card-above-account-row=true tag-in-account-row=true floats-over-list=true')
await publishUpdate({ phase: 'idle' })
await updateTag.waitFor({ state: 'detached' })
for (const [delta, width, edge] of [[80, 280, 360], [-80, 260, 280]] as const) {
const handle = await stackPage.locator('[data-side="sidebar"]').boundingBox()
const x = handle!.x + handle!.width / 2
@@ -700,8 +737,6 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
expect(platform.acks.length).toBe(beforeCollapseAcks)
expect(platform.dismissals.length).toBe(beforeCollapseDismissals)
observations.push('stack.expanded cards=3 duplicate-acks=0 dismissed=0')
const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
await mkdir(artifactDir, { recursive: true })
await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-stack-light.png') })
await stackPage.emulateMedia({ colorScheme: 'dark' })
await expect.poll(() => stackPage.locator('body').getAttribute('data-ds-dark-theme')).not.toBeNull()
@@ -736,6 +771,16 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
await expect.poll(() => platform.acks.length).toBe(ackStart + 2)
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222'])
observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true')
// In a short window the long card scrolls its copy instead of pushing the account row out of view.
await stackPage.setViewportSize({ width: 1440, height: 390 })
const shortAccount = await stackPage.getByRole('button', { name: '账号菜单', exact: true }).boundingBox()
const shortCard = await second.boundingBox()
const copyScrolls = await second.getByRole('status').evaluate(element => element.scrollHeight > element.clientHeight)
expect(shortAccount!.y + shortAccount!.height).toBeLessThanOrEqual(390)
expect(shortCard!.y + shortCard!.height).toBeLessThanOrEqual(shortAccount!.y)
expect(copyScrolls).toBe(true)
observations.push('stack.short-window account-row-visible=true card-above-account-row=true copy-scrolls=true')
await stackPage.setViewportSize({ width: 1440, height: 960 })
await second.getByRole('button', { name: '关闭', exact: true }).click()
await expect.poll(() => platform.acks.length).toBe(ackStart + 3)
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222', 'a3333333-3333-4333-8333-333333333333'])
+3 -3
View File
@@ -264,8 +264,8 @@ async function withScrollWorld(
runFailure = error
try {
await saveFailureShot(world.page, options.failureShot)
} catch {
// Best-effort evidence must never prevent cleanup of the owned world.
} catch (_failureShotFailed) {
// A missing screenshot loses evidence only; cleanup of the owned world and the rethrown run failure still follow.
}
}
let cleanupFailure: unknown
@@ -1305,7 +1305,7 @@ describe('web e2e: long Chat scroll contract', () => {
const top = viewport.top + element.clientTop
return Math.max(
Math.abs((railBox.top + railBox.bottom) / 2 - (top + composerBox.top) / 2),
Math.abs(viewport.left + element.clientLeft + element.clientWidth - railBox.right - 12),
Math.abs(railBox.left - viewport.left - element.clientLeft - 12),
Math.abs(composerBox.top - buttonBox.bottom - 16),
)
}), { timeout: 10_000 }).toBeLessThanOrEqual(GEOMETRY_TOLERANCE)
+2 -3
View File
@@ -10,7 +10,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-subagent'
import { launchWebScaffold, selectedSessionFixture, webSnapshotMode, type WebScaffold } from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, openSettings, saveFailureShot } from './support.ts'
import { connectFreshWorkspace, newEnglishPage, openSettings, saveFailureShot, showSessionPanel } from './support.ts'
const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url))
const LABEL = 'event-sourcing researcher'
@@ -104,8 +104,7 @@ describe('web e2e: composer paste routing', () => {
parent,
})
await waitForAgentToSettle(scaffold, started.childId)
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
await page.getByRole('treeitem', { name: new RegExp(LABEL) })
await (await showSessionPanel(page)).getByRole('treeitem', { name: new RegExp(LABEL) })
.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click()
await page.locator('[data-sidebar-chat] [data-composer-card]').waitFor({ timeout: 15_000 })
})
+6 -2
View File
@@ -142,8 +142,12 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr
const account = scaffold.ctx.get('deepseekAccount')
if (account === undefined) throw new Error('Shipped native Account service is absent')
// Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real.
const auth = vi.spyOn(account, 'resolveToken').mockImplementation(async (url: string) =>
new URL(url).origin === origin ? 'paid-browser-fixture-token' : undefined)
const credential = {
headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token',
revoked: new AbortController().signal, reject: () => Promise.resolve(),
}
const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) =>
new URL(url).origin === origin ? credential : undefined)
resources.restoreAuth = () => { auth.mockRestore() }
scaffold.ctx.emit('llm/adapters-updated')
const owner = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'llm-deepseek-account')
@@ -0,0 +1,99 @@
// Web e2e scenario: a composer draft's pasted image survives a sidebar session
// switch. The reported defect spans the whole chain — sidebar row click, Session
// scope retirement, the input shell's teardown, and the rail's rebuild — so only
// the real composition can pin it. Units cover each link separately (hub/shell/
// service specs); this covers the assembled path and the rail the user sees.
//
// Zero model calls: a seeded session is non-blank (so the sidebar can create a
// second one instead of reusing it) and the scenario never submits.
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import type { Browser, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import {
launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
const MODE = webSnapshotMode()
const SEED_ID = 'draft-attachment-switch-a'
const PEER_ID = 'draft-attachment-switch-b'
const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url))
const PNG = fileURLToPath(new URL('../../../snapshots/session/read-image/workspace/red.png', import.meta.url))
const DRAFT_TEXT = 'draft text that survives the switch'
/** The composer's pending-attachment rail, present only while it holds items. */
const RAIL = '[role="group"][aria-label="Pending attachments"]'
/**
* Paste one real PNG into the composer through a genuine clipboard event, the
* same intake a user's screenshot paste performs.
* @param page - page holding the composer.
* @param bytes - PNG bytes.
*/
async function pasteImage(page: Page, bytes: Uint8Array): Promise<void> {
await page.locator('[data-composer-input]').first().evaluate((surface, data) => {
const transfer = new DataTransfer()
transfer.items.add(new File([new Uint8Array(data)], 'draft.png', { type: 'image/png' }))
surface.dispatchEvent(new ClipboardEvent('paste', {
clipboardData: transfer, bubbles: true, cancelable: true,
}))
}, [...bytes])
}
describe.skipIf(MODE === 'record')('web e2e: draft attachment across a session switch', () => {
let scaffold: WebScaffold
let browser: Browser
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
scaffold = await launchWebScaffold({})
const log = await readFile(FIXTURE, 'utf8')
await seedSession(scaffold, log, SEED_ID)
await seedSession(scaffold, log, PEER_ID)
browser = await chromium.launch()
page = await newEnglishPage(browser)
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
// Expand the workspace group and open the seeded session.
const groupRow = page.locator('[role="treeitem"]').first()
await groupRow.waitFor({ timeout: 15_000 })
await groupRow.click()
const sessionRow = page.locator(`[data-row-key="session:${SEED_ID}"]`)
await sessionRow.waitFor({ timeout: 15_000 })
await sessionRow.click()
await page.locator('[data-composer-input]').first().waitFor({ timeout: 15_000 })
})
afterAll(async () => {
await browser?.close()
await scaffold?.close()
})
it('keeps the pasted image and the typed draft when the sidebar leaves and returns', async () => {
onTestFailed(() => saveFailureShot(page, 'draft-attachment-session-switch'))
// (a) paste an image, then type text into the seeded session's composer.
await pasteImage(page, await readFile(PNG))
await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1)
await page.locator('[data-composer-input]').first().click()
await page.keyboard.type(DRAFT_TEXT, { delay: 5 })
await expect.poll(() => page.locator(RAIL).locator('img').count(), { timeout: 10_000 }).toBe(1)
// (b) leave through the sidebar: switching to another session retires this
// one's Session scope.
await page.locator(`[data-row-key="session:${PEER_ID}"]`).click()
await expect.poll(() => page.locator(RAIL).count(), { timeout: 15_000 }).toBe(0)
// (c) return: the rebuilt composer must show the image AND the text.
await page.locator(`[data-row-key="session:${SEED_ID}"]`).click()
await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1)
await expect.poll(
() => page.locator('[data-composer-input]').first().innerText(),
{ timeout: 10_000 },
).toContain(DRAFT_TEXT)
expect(tripwire.pageErrors).toEqual([])
})
})
@@ -1,5 +1,5 @@
- navigation "Session hierarchy": Seeded turn
- text: Minimal mode
- button "1 subagent"
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
@@ -36,11 +36,13 @@ en.get locale=en_US query=
web.notice=赠金已到账 / 已赠送您 4.00 元 DSH 体验赠金。 acks=1
stack.hidden cards=3 acks=0
stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=0.25s ease-out
stack.update-tag card=260 left-inset=10 card-above-account-row=true tag-in-account-row=true floats-over-list=true
stack.resized sidebar=360 card=280 left-inset=10
stack.resized sidebar=280 card=260 left-inset=10
stack.rail cards=3 visible=false dismissed=0
stack.expanded cards=3 duplicate-acks=0 dismissed=0
stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true
stack.short-window account-row-visible=true card-above-account-row=true copy-scrolls=true
stack.dismissed cards=0 acks=stack-first,stack-second,stack-third
refresh.retained cards=3 acks=refresh-first same-node=true
refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Clickable links gallery
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Use only Cordis tools. First
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,4 +1,3 @@
- button "本地变更"
- text: HEAD → origin/main
- button "查看本会话的变更:1 个文件,新增 1 行,删除 0 行": +1 −0 1 个文件
- button "创建变更请求"
- button "本地变更 · 1 个文件,新增 1 行,删除 0 行": 本地变更 · 1 个文件
- text: +1 −0
- button "本地变更操作"
@@ -1,21 +1,22 @@
- text: feat 项目目录
- button "复制项目目录路径"
- button "本地变更"
- text: HEAD → origin/main
- button "查看本会话的变更:4 个文件,新增 4 行,删除 1 行": +4 −1 4 个文件
- heading "本会话的变更请求 · 1" [level=3]
- button "刷新状态"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "在浏览器中打开"
- button "复制变更请求链接"
- 'button "从本会话移除 #7"'
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
- complementary "会话面板":
- region "环境":
- heading "环境" [level=2]
- text: workspace {{cwd}} feat 项目目录
- button "本地变更 · 4 个文件,新增 4 行,删除 1 行": 本地变更 · 4 个文件
- text: +4 −1
- button "本地变更操作"
- region "变更请求":
- heading "变更请求" [level=2]
- text: "1"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "#7 的操作"
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
@@ -1,4 +1,3 @@
- button "Local changes"
- text: HEAD → origin/main
- 'button "View the changes of this Session: 60 files, 60 lines added, 0 lines deleted"': +60 −0 60 files
- button "Create change request"
- button "Local changes · 60 files, 60 lines added, 0 lines deleted": Local changes · 60 files
- text: +60 −0
- button "Local changes actions"
@@ -1,18 +1,19 @@
- text: dsh-{{worktree}} 工作树 · 基于 release
- button "复制工作树路径"
- heading "本会话的变更请求 · 1" [level=3]
- button "刷新状态"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "在浏览器中打开"
- button "复制变更请求链接"
- 'button "从本会话移除 #7"'
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
- complementary "会话面板":
- region "环境":
- heading "环境" [level=2]
- text: dsh-{{worktree}} {{cwd}}/workspace/.agents/worktrees dsh-{{worktree}} 工作树 · 基于 release
- region "变更请求":
- heading "变更请求" [level=2]
- text: "1"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "#7 的操作"
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
@@ -3,9 +3,7 @@
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "在浏览器中打开"
- button "复制变更请求链接"
- 'button "从本会话移除 #7"'
- button "#7 的操作"
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
@@ -1 +0,0 @@
- button "代码审查和变更 查看代码变更与本会话的变更请求"
@@ -11,6 +11,7 @@
- banner:
- navigation "Session hierarchy": Review deepseek-ai/deepseek-harness#314
- text: Standard mode
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -11,6 +11,7 @@
- banner:
- navigation "Session hierarchy": Review deepseek-ai/deepseek-harness#314
- text: Standard mode
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,6 +1,7 @@
- banner:
- navigation "Session hierarchy": workspace
- text: Standard mode
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,35 +0,0 @@
# Background jobs above the Browser dock
```json
{
"collapsed": {
"dockMode": "push",
"bodyMounted": true,
"fixed": true,
"anchored": true,
"viewportBounded": true,
"overlapsBrowser": true,
"aboveBrowser": true
},
"expanded": {
"dockMode": "push",
"bodyMounted": true,
"fixed": true,
"anchored": true,
"viewportBounded": true,
"overlapsBrowser": true,
"aboveBrowser": true
},
"resized": {
"dockMode": "push",
"bodyMounted": true,
"fixed": true,
"anchored": true,
"viewportBounded": true,
"overlapsBrowser": true,
"aboveBrowser": true
},
"escapeRestoresFocus": true,
"outsideDismisses": true
}
```
@@ -0,0 +1,38 @@
# Background jobs beside the Browser dock
```json
{
"collapsed": {
"dockMode": "push",
"presentation": "overlay",
"insideBody": true,
"clearOfBrowser": true,
"clearOfComposer": true,
"viewportBounded": true,
"sectionShown": true,
"onTop": true
},
"expanded": {
"dockMode": "push",
"presentation": "overlay",
"insideBody": true,
"clearOfBrowser": true,
"clearOfComposer": true,
"viewportBounded": true,
"sectionShown": true,
"onTop": true
},
"resized": {
"dockMode": "push",
"presentation": "overlay",
"insideBody": true,
"clearOfBrowser": true,
"clearOfComposer": true,
"viewportBounded": true,
"sectionShown": true,
"onTop": true
},
"escapeRestoresFocus": true,
"outsideDismisses": true
}
```
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": CJK strong emphasis
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Markdown image policy
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Inline code links
- button "Session panel"
- button "More actions"
- tablist:
- tab "Chat" [selected]
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Math rendering
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -43,7 +43,7 @@
- code: "@deepseek-ai/dsh-experimental-forge-session"
- text: 已关闭
- listitem:
- text: 变更请求面板 在侧栏标签页中显示会话的变更请求,并让新会话可以在工作树中开始。
- text: 变更请求面板 在会话面板中显示会话的变更请求,并让新会话可以在工作树中开始。
- code: forge-panel
- code: "@deepseek-ai/dsh-experimental-client-ui-forge"
- text: 已关闭
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Reference order target
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -3,6 +3,8 @@
- list:
- listitem:
- button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00
- listitem:
- button "Weekly review": Weekly review Your work in the workspace this week, with loose ends and what to do first next week. Fridays at {{clock}}
- listitem:
- button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}}
- listitem:
@@ -3,6 +3,8 @@
- list:
- listitem:
- button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00
- listitem:
- button "每周回顾": 每周回顾 回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。 周五 {{clock}}
- listitem:
- button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}}
- listitem:
@@ -1,7 +1,6 @@
- banner:
- navigation "Session hierarchy": Delegate a background job.
- button "1 subagent"
- button "1 background job"
- 'button "Session panel Subagents running: 1 Background jobs running: 1"'
- button "More actions"
- button "Open right sidebar"
- tablist:
Loaded 100 of 1185 files, more files were not shown because too many files have changed in this diff. Show more