diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index f29cf535f2..7f34aedf3f 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -18,23 +18,23 @@ en: 5f5daec51b20db77 zh: e4d6f78fc1b4b835 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps: - en: 0a4240d88cca240a - zh: 8f5f1527caf571cd + en: 04b9f0138b5d2288 + zh: 2a749db57f6e7a10 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/the-loading-flow-end-to-end: en: 1f7db6ecfc0b0831 zh: f6bf37dc921a7d40 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/live-graph-reconciliation: - en: ab9577214d7b2f2b - zh: fc8f10fd8c90b34b + en: d7777566a2594654 + zh: 509cad4a363184ae /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/hot-reload-one-driver-plugin-self-watched-bundles: - en: e6a0bee3d31cd2c6 - zh: 7f7384c5d1a74751 + en: d31506b6ccca554e + zh: 91f4eb62927ebabe /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/package-ownership: en: 94ca0d09e6fd1e3a zh: d5949a2bdec795ba /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/consequences: - en: 624efdd136029771 - zh: 7d60207147e631fe + en: cfeb5dc97753e46f + zh: 92da07a598f7cfb0 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/alternatives-considered: en: b8f036f50cff7cd8 zh: 6d623c4a1f4314b1 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index bc24420a59..6de1fd1ab8 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -46,7 +46,7 @@ A `require.async("./client..js")` call requests the exact revisioned `/plu The shared tsdown preset emits a map for every plugin entry and chunk and rewrites first-party source paths into the browser-resolvable repository form `/packages///src/...`. The production Client pass consumes `lib/types`; the preset supplies each tsc map to Rolldown and fills `sourcesContent` from the original files, so the final map reaches TypeScript/TSX instead of stopping at emitted JavaScript. Other workspace sources inlined into a bundle likewise resolve to their `packages/` owner, while dependency paths remain unchanged. Combo generation strips each local debug directive, records its generated-line offset, resolves every authored source against the original per-plugin map URL, and emits an Indexed Source Map v3. An authored map supplies its section; otherwise an identity section embeds the generated bundle and uses the packer's `sourceURL` as its source name when present. The absolute combo map URL mirrors the script resource list by changing every `client.js` suffix to `client.js.map`, so `/plugins/??/client.js,/client.js&rev=` points to `/plugins/??/client.js.map,/client.js.map&rev=`. A chunk script likewise points to its own map URL. Source-map files are read and combined only when those map URLs receive `GET`; `HEAD` materializes neither script nor map bodies. The Vite shell also emits source maps, letting shell code and externally loaded plugins map stacks and performance profiles back to TypeScript/TSX. -The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial publication and `rebuilt(id)` use the same hash of entry mtime, ctime, and size; artifact contents never enter the hash. Ctime distinguishes rewrites that preserve mtime and size. A Host restart over unchanged artifacts therefore retains every row revision, so the reconnecting SSE snapshot does not trigger browser plugin replacement. The shared preset stamps the entry after every package output is written; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id. +The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial publication and `rebuilt(id)` use the same hash of entry mtime, ctime, and size; artifact contents never enter the hash. Ctime distinguishes rewrites that preserve mtime and size. A Host restart over unchanged artifacts therefore retains every row revision, so the reconnecting stream baseline does not trigger browser plugin replacement. The shared preset stamps the entry after every package output is written; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id. ### The loading flow, end to end @@ -76,13 +76,13 @@ Stylesheet metadata and renderer ownership follow the [module metadata decision] The modules controller owns exactly the Loader entries created from the boot manifest. Full Host snapshots update its module descriptors and reconcile those entries; other Loader contributors retain ownership. New modules arrive through single-resource URLs because replaying a startup batch could register an existing factory twice. Removal uses Loader deletion, then drains the captured fiber before removing unused module records. Declared and observed transitive requests keep shared modules alive. Factory revision tracking is independent of entry activation because a download or materialization can finish without creating an entry. Graph updates invalidate stale factories and failed arrival targets without managed entries, notifying resource consumers before any consumer imports its dependencies; rebuilt frames also reconcile entries missing after import failures. -The Host SSE adapter forwards existing graph-change notifications and sends the current full graph on connection. The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism. +The Host `pluginEvents/follow` Remote stream forwards existing graph-change notifications and opens every generation with the current full graph; graph rows also carry each plugin's synced configuration ([browser plugin configuration sync](2026-11-15-client-config-sync.md)). The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism. ### Hot reload: one driver plugin, self-watched bundles -Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the SSE channel, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row. +Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the authenticated plugin-events Remote stream, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row. -How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids redundant reads when installing the watcher and avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance retries publication even when mtime and size match the baseline. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime, ctime, or size delta, or a dirty row, `rebuilt(id)` derives the revision from those three metadata values. It reads the new bundle snapshot only if the revision changes. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol. +How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids redundant reads when installing the watcher and avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance retries publication even when mtime and size match the baseline. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime, ctime, or size delta, or a dirty row, `rebuilt(id)` derives the revision from those three metadata values. It reads the new bundle snapshot only if the revision changes. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half publishes a `rebuilt` frame on the authenticated `pluginEvents/follow` Remote stream, which opens every generation with the full graph and then sends `graph` and `rebuilt` increments; it is presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol. On the browser side, the transport delegates code replacement to the same modules controller that owns graph reconciliation: @@ -96,7 +96,7 @@ On the browser side, the transport delegates code replacement to the same module Bootstrap replacement is rejected before invalidation or teardown: the module system retains its initial exports, so remounting its old code would reset consumers without applying the requested revision. The page reports the required reload and preserves the bootstrap fiber. Every non-bootstrap plugin shares the replacement semantics; an `immediately` row reloads exactly like a lazy one. Dependency cascade costs zero client code: a fiber's activation epoch strings its service providers' uids, so replacing a foundational provider such as connection re-loads every dependent through cordis itself — correct, if heavy. -Reload creates a fresh fiber and component state; it does not preserve React state inside the replaced plugin. Static assembly libraries and the shell require a rebuilt page; when the Host itself serves another release, the page holds plugin replacement and asks whether to reload ([Host release change prompt](../feature/2026-10-14-host-release-change-refresh-prompt.md)). Failed imports or activation remain diagnosable and retryable without rolling back unrelated plugins. Self-reload closes the old SSE channel and opens a new one; its full snapshot repairs missed graph changes. Boot, graph updates and rebuilt frames share the same queue, so a code replacement cannot overlap initial module arrival. +Reload creates a fresh fiber and component state; it does not preserve React state inside the replaced plugin. Static assembly libraries and the shell require a rebuilt page; when the Host itself serves another release, the page holds plugin replacement and asks whether to reload ([Host release change prompt](../feature/2026-10-14-host-release-change-refresh-prompt.md)). Failed imports or activation remain diagnosable and retryable without rolling back unrelated plugins. Self-reload closes the old stream and opens a new one; its full snapshot repairs missed graph changes. Boot, graph updates and rebuilt frames share the same queue, so a code replacement cannot overlap initial module arrival. ## Package ownership @@ -108,7 +108,7 @@ One governance implementation runs on both sides of the wire; the browser-specif Costs accepted: the vendored Loader carries idle machinery in the browser (EntryTree persistence is a no-op, groups/isolation unused); every plugin edit in dev pays a bundle rebuild plus fiber remount; graph `inject` rows guide factory arrival but service availability remains the activation authority, so a mismatch appears at the boot audit; the static UI libraries keep direct value exports; every bundle gains a source-map artifact; and external-script failures provide only coarse URL diagnostics instead of the HTTP status available to an explicit fetch. The Host retains bundle snapshots and lazy response plans for the current graph and one prior startup generation. Script and map bodies are cached after their first `GET`, so memory grows with bundle snapshots and requested response bodies. Each materialized response stays fixed at its URL; a prior-generation map first requested after a rebuild reads the current map file. -Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordis.patch.yml`); `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer lives in the `dsh-client-modules` node half, while the parser-preloaded client face bootstraps the browser module table. The webserver remains a plain route-registration plugin; `/api/*` binding, browser authentication, RPC envelopes, and exact Fetch routes belong to the Connection node half, while Remote dispatch belongs to API Gateway and the dev bundle watch plus SSE channel belongs to the hmr node half. +Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordis.patch.yml`); `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer lives in the `dsh-client-modules` node half, while the parser-preloaded client face bootstraps the browser module table. The webserver remains a plain route-registration plugin; `/api/*` binding, browser authentication, RPC envelopes, and exact Fetch routes belong to the Connection node half, while Remote dispatch belongs to API Gateway and the dev bundle watch plus the plugin-events Remote stream belongs to the hmr node half. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md index bebd131c85..7e1e7d1d40 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md @@ -46,7 +46,7 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的 共享 tsdown 预设为每个插件入口与 chunk 产出 map,并把第一方源码路径重写成浏览器可识别的仓库形式 `/packages///src/...`。生产 Client 构建会消费 `lib/types`;预设把每份 tsc map 交给 Rolldown,并从原文件补齐 `sourcesContent`,使最终 map 回到 TypeScript/TSX,而不是停在编译后的 JavaScript。内联进 bundle 的其他 workspace 源码同样回到其 `packages/` 归属,依赖包路径保持原样。Combo 生成会移除每个局部调试指令、记录其生成行偏移、以原插件 map URL 解析每个自带 source,再产出 Indexed Source Map v3。插件有自带 map 时直接用于对应 section;没有时则生成 identity section,内嵌构建后 bundle,并在存在时把 packer 写入的 `sourceURL` 用作 source 名。绝对 combo map URL 会平行改写脚本资源列表中的每个 `client.js` 后缀,因此 `/plugins/??/client.js,/client.js&rev=` 指向 `/plugins/??/client.js.map,/client.js.map&rev=`。chunk 脚本同样指向自己的 map URL。只有在这些 map URL 收到 `GET` 后,source map 文件才会被读取和组合;`HEAD` 不会物化脚本或 map body。Vite 壳同样产出 sourcemap,使壳代码与经外部加载的插件都能从 stack 和性能 profile 回到 TypeScript/TSX。 -图为 HMR 保留每个 row 带 revision 的单资源 combo URL,并为每个启动 combo 请求增加带 revision 的描述;多条描述可以使用同一调度阶段。首次发布与 `rebuilt(id)` 使用相同的入口 mtime、ctime 和大小哈希;产物内容不参与求哈希。ctime 用于区分保留 mtime 和大小的重写。Host 重启时若产物未变,每个 row 的 revision 都保持不变,因此重连后的 SSE 快照不会触发浏览器插件替换。共享预设会在每个包输出写完后标记入口;因此只重建 chunk 也会推进 owner revision,无需 Host 扫描 sibling。启动 combo revision 从有序 row revision 派生。脚本 body 在首次 `GET` 时组合;source map 文件在首次 map `GET` 时单独读取并组合。`HEAD` 不会物化任一 body。版本化脚本与 map 使用 immutable 缓存,无关图重组会保留相同 revision 下已经物化的 chunk 响应。Host 只提供精确生成的 URL;陈旧 revision 与未发布资源列表返回 404,不会别名到其他字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。 +图为 HMR 保留每个 row 带 revision 的单资源 combo URL,并为每个启动 combo 请求增加带 revision 的描述;多条描述可以使用同一调度阶段。首次发布与 `rebuilt(id)` 使用相同的入口 mtime、ctime 和大小哈希;产物内容不参与求哈希。ctime 用于区分保留 mtime 和大小的重写。Host 重启时若产物未变,每个 row 的 revision 都保持不变,因此重连后的流 baseline不会触发浏览器插件替换。共享预设会在每个包输出写完后标记入口;因此只重建 chunk 也会推进 owner revision,无需 Host 扫描 sibling。启动 combo revision 从有序 row revision 派生。脚本 body 在首次 `GET` 时组合;source map 文件在首次 map `GET` 时单独读取并组合。`HEAD` 不会物化任一 body。版本化脚本与 map 使用 immutable 缓存,无关图重组会保留相同 revision 下已经物化的 chunk 响应。Host 只提供精确生成的 URL;陈旧 revision 与未发布资源列表返回 404,不会别名到其他字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。 ### 装载流程,端到端 @@ -76,13 +76,13 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的 modules 控制器只持有从启动清单创建的 Loader 条目。Host 的完整快照更新模块描述并对账这些条目;其他 Loader 贡献方保留自身所有权。新增模块通过单资源 URL 到达,因为重放启动 batch 可能重复注册现有 factory。移除使用 Loader 删除语义,随后等待已捕获 fiber 清理完毕,再移除未使用的模块记录。已声明及已观察到的传递依赖使共享模块保持存活。Factory revision 的跟踪独立于条目激活,因为下载或物化完成后仍可能没有创建条目。图更新会在任何消费者导入依赖前,使未归属受管条目的陈旧 factory 和失败的到达目标失效,并通知资源消费者;重建帧也会对账因导入失败而缺失的条目。 -Host SSE 适配器转发现有图变化通知,并在连接时发送当前完整图。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。 +Host 的 `pluginEvents/follow` Remote 流转发现有图变化通知,每一代流先发送当前完整图;图行还携带各插件的同步配置([前端插件配置同步](2026-11-15-client-config-sync.zh.md))。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。 ### 热重载:一个驱动插件,自行监视的 bundle -热重载是一项组合决策:web 组合包无条件挂载 `client-hmr` 行(一个常规的插件包),其 node 半带来 bundle 监视与 SSE(Server-Sent Events)通道;没有重建 watcher 改写客户端 bundle 时链路保持空闲。不应暴露它的组合可以禁用该行。 +热重载是一项组合决策:web 组合包无条件挂载 `client-hmr` 行(一个常规的插件包),其 node 半带来 bundle 监视与经过鉴权的插件事件 Remote 流;没有重建 watcher 改写客户端 bundle 时链路保持空闲。不应暴露它的组合可以禁用该行。 -重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。模块 host 在读取每份启动快照前捕获入口 stat 基线,并通过 `ctx.clientModules.artifactBaseline(id)` 暴露它。HMR 自持的单个定时器把当前图的每个 row 与这份基线比较:未变化的 row 直接开始监视,不读取内容也不求哈希;基线捕获后的写入已经形成 stat 差异,只有该 row 会进入 `rebuilt(id)`。这既避免安装 watcher 时重复读取,也避开 `fs.watchFile` 以异步首次 stat 建立基线、可能静默吸收构造期重建的问题。监视集合的成员随 `onGraphChanged` 更新;消失的 row 撤下监视,轮询时缺失的入口则让对应 row 保持标脏状态,文件重现时即使 mtime 和大小与基线相同也重试发布。共享 tsdown 预设会在每个 sibling 输出写完后标记 `client.js`;入口 mtime、ctime 或大小变化、或 row 处于标脏状态时,`rebuilt(id)` 从这三个元数据值派生 revision。只有 revision 变化时,它才读取新的 bundle 快照。只修改 chunk 因此也会更换 revision;部分写入之后的完成标记还会提供一次更晚的 stat 变化以完成自愈。`rev` 变化时,node 半在 `GET /plugins/events` 上广播 `rebuilt` 帧——这是一条系统级 SSE 通道,连接即发全量图,变更时发 `rebuilt` 帧,仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;每个 row 每个间隔只需一次入口 stat,轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物的进程必须使用共享 Client tsdown 预设;`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现,构建器与 host 之间没有通知协议。 +重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。模块 host 在读取每份启动快照前捕获入口 stat 基线,并通过 `ctx.clientModules.artifactBaseline(id)` 暴露它。HMR 自持的单个定时器把当前图的每个 row 与这份基线比较:未变化的 row 直接开始监视,不读取内容也不求哈希;基线捕获后的写入已经形成 stat 差异,只有该 row 会进入 `rebuilt(id)`。这既避免安装 watcher 时重复读取,也避开 `fs.watchFile` 以异步首次 stat 建立基线、可能静默吸收构造期重建的问题。监视集合的成员随 `onGraphChanged` 更新;消失的 row 撤下监视,轮询时缺失的入口则让对应 row 保持标脏状态,文件重现时即使 mtime 和大小与基线相同也重试发布。共享 tsdown 预设会在每个 sibling 输出写完后标记 `client.js`;入口 mtime、ctime 或大小变化、或 row 处于标脏状态时,`rebuilt(id)` 从这三个元数据值派生 revision。只有 revision 变化时,它才读取新的 bundle 快照。只修改 chunk 因此也会更换 revision;部分写入之后的完成标记还会提供一次更晚的 stat 变化以完成自愈。`rev` 变化时,node 半在经过鉴权的 `pluginEvents/follow` Remote 流上发布 `rebuilt` 帧;该流每一代先发全量图,之后发送 `graph` 与 `rebuilt` 增量,是仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;每个 row 每个间隔只需一次入口 stat,轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物的进程必须使用共享 Client tsdown 预设;`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现,构建器与 host 之间没有通知协议。 浏览器侧的传输把代码替换交给负责图对账的同一个 modules 控制器: @@ -96,7 +96,7 @@ Host SSE 适配器转发现有图变化通知,并在连接时发送当前完 Bootstrap 替换会在失效或卸载前被拒绝:模块系统保留其初始导出,重新挂载旧代码会重置消费者,却无法应用请求的 revision。页面会报告需要刷新,并保留 bootstrap fiber。所有非 bootstrap 插件都共享同一套替换语义;`immediately` 行的重载与 lazy 行分毫不差。依赖级联不花一行 client 代码:fiber 的激活纪元串接着它各服务提供方的 uid,因此替换 connection 等基础 provider 的 fiber 时,每个依赖方都会经 cordis 本身重新装载——行为正确,但代价较高。 -重载会创建新的 fiber 和组件状态,不保留被替换插件内部的 React 状态。静态组装库与应用壳需要重建后的页面;Host 本身换成另一个 release 时,页面会暂停插件替换并询问是否刷新([Host release 变化提示](../feature/2026-10-14-host-release-change-refresh-prompt.zh.md))。导入或激活失败仍可诊断和重试,不会回滚无关插件。自重载关闭旧 SSE 通道并打开新通道;其完整快照补齐遗漏的图变更。启动、图更新和重建帧共用同一队列,因此代码替换不会与初始模块到达重叠。 +重载会创建新的 fiber 和组件状态,不保留被替换插件内部的 React 状态。静态组装库与应用壳需要重建后的页面;Host 本身换成另一个 release 时,页面会暂停插件替换并询问是否刷新([Host release 变化提示](../feature/2026-10-14-host-release-change-refresh-prompt.zh.md))。导入或激活失败仍可诊断和重试,不会回滚无关插件。自重载关闭旧流并打开新流;其完整快照补齐遗漏的图变更。启动、图更新和重建帧共用同一队列,因此代码替换不会与初始模块到达重叠。 ## 包归属 @@ -108,7 +108,7 @@ Wire 两侧运行同一份治理实现;浏览器特有层只包含一套模块 接受的代价:vendored Loader 在浏览器里背着闲置机件(EntryTree 持久化是 no-op,分组/隔离未用);开发期每次修改插件都要付一次 bundle 重建加 fiber 重挂;graph `inject` row 指导 factory 到达,但服务可用性仍是激活权威,因此不匹配会在启动审计时浮出;静态 UI 库保留直接实体导出;每个 bundle 多出一份 sourcemap 产物,外部 script 失败也只能给出粗粒度 URL 诊断,不能像显式 fetch 那样报告 HTTP 状态。Host 为当前图及上一代启动图保留 bundle 快照与惰性响应计划。脚本和 map body 在首次 `GET` 后缓存,因此内存随 bundle 快照和已请求的响应 body 增长。每份已物化响应在其 URL 下保持固定;若上一代 map 在重建后才首次被请求,则会读取当前 map 文件。 -名册位于 web 组合包的配置树(`packages/bundle/web-app/cordis.patch.yml`);`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于替换 yml/overlay。Graph 组合器位于 `dsh-client-modules` node 半,由 parser 预载的 Client face 则自举浏览器模块表。Webserver 继续作为朴素路由注册插件;`/api/*` 绑定、浏览器认证、RPC envelope 与精确 Fetch 路由属于 Connection node 半,Remote 分发属于 API Gateway,开发期 bundle 监视与 SSE 通道属于 HMR node 半。 +名册位于 web 组合包的配置树(`packages/bundle/web-app/cordis.patch.yml`);`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于替换 yml/overlay。Graph 组合器位于 `dsh-client-modules` node 半,由 parser 预载的 Client face 则自举浏览器模块表。Webserver 继续作为朴素路由注册插件;`/api/*` 绑定、浏览器认证、RPC envelope 与精确 Fetch 路由属于 Connection node 半,Remote 分发属于 API Gateway,开发期 bundle 监视与插件事件 Remote 流属于 HMR node 半。 ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml index bbbf53a526..0be791a222 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml @@ -9,8 +9,8 @@ en: 6228c81e4965b688 zh: 04b702be0cfbf195 /agent-note-credential-boundaries-whole-snapshot-requests-and-atomic-route-registration/decision: - en: 052787311a4e6edc - zh: 963eed632ea198de + en: 3ecf963f99b8e9ae + zh: 84fa0bed2316ce94 /agent-note-credential-boundaries-whole-snapshot-requests-and-atomic-route-registration/alternatives-considered: en: 90c5883b247f7301 zh: 6d2a660d8653f805 diff --git a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md index 03ea573307..f153f3afd4 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md +++ b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md @@ -18,7 +18,7 @@ Two request-path defects sat beside them. DeepSeek resolved connection and crede **The stored credential has no boundary against the model, and the READMEs say so.** `0600` under a `0700` directory stops other OS users; the model's bash and filesystem tools run as that same user, and the shipped default confines nothing. What the harness does hold to is narrower and stated as exactly that: no surface hoists the document into `process.env`, and the model is never handed a resolved path to it, so reaching the value takes a deliberate read of a path it was not given. An OS-keychain provider — a store the model's processes cannot read at all — is recorded as the real answer rather than implied by a partial one. -**One request, one generation.** DeepSeek's resolved snapshot carries the credential reference beside the endpoint, and `resolveApiKey` receives that snapshot instead of re-reading configuration. A rejected generation now contributes nothing at all. pi-ai defers to provider-native discovery only for a profile naming no credential; a configured reference that misses fails with `MISSING_CREDENTIAL` naming the route and the reference. The boot-time credential probe is deleted: it could run before the credentials service mounted and reported every failure as a missing key, while the first request already gives the accurate error. +**One request, one generation.** DeepSeek's resolved snapshot carries the credential reference beside the endpoint, and the API-key route's `resolveAuth` hands that snapshot's endpoint and reference to `ctx.deepseekAuth` instead of re-reading configuration. A rejected generation now contributes nothing at all. pi-ai defers to provider-native discovery only for a profile naming no credential; a configured reference that misses fails with `MISSING_CREDENTIAL` naming the route and the reference. The boot-time credential probe is deleted: it could run before the credentials service mounted and reported every failure as a missing key, while the first request already gives the accurate error. **Route replacement is a registry operation, not a caller sequence.** `registerAdapter` returns a handle carrying `replace(providers)`: the candidate set is validated in full first (conflicts, names, provider metadata), then swapped in one synchronous section. A refused replacement leaves the previous routes registered and serving, and the caller's facts cache only advances after the registry actually holds the new set, so reverting to a working configuration re-applies. pi-ai's registration facts are sorted by provider, so a settings document that merely reorders its keys is no longer a route change. diff --git a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md index 9f822b8bee..52a592660d 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md @@ -22,7 +22,7 @@ Status: implemented **存下的凭据对模型没有边界,而 README 就是这么写的。**`0700` 目录下的 `0600` 挡得住其他 OS 用户;模型的 bash 与文件系统工具正是以同一用户身份运行,而已交付的默认配置不提供任何约束。harness 真正守住的边界更窄,文档也严格按这一范围表述:没有任何一个面会把该文档提升进 `process.env`,模型也从不会拿到它的解析后路径,因此要拿到这个值,需要刻意去读一条并未交给它的路径。OS 钥匙串(keychain)提供方——一个模型的进程根本读不到的存储——被记录为真正的答案,而不是靠一个残缺的方案去暗示它。 -**一次请求,一代设置。**DeepSeek 解析出的快照在端点旁一并携带凭据引用,`resolveApiKey` 接收这份快照,而不再重新读取配置。被拒绝的那一代如今完全不再贡献任何东西。只有当一个 profile 完全没有点名凭据时,pi-ai 才交给提供方原生的发现流程;配置了引用却解析不到,就以 `MISSING_CREDENTIAL` 失败,并点名该路由与该引用。启动时的凭据探测被删除:它可能在凭据服务挂载之前就运行,并把每一种失败都报成密钥缺失,而第一次请求本就会给出准确的错误。 +**一次请求,一代设置。**DeepSeek 解析出的快照在端点旁一并携带凭据引用,API 密钥路由的 `resolveAuth` 把这份快照的端点和引用交给 `ctx.deepseekAuth`,而不再重新读取配置。被拒绝的那一代如今完全不再贡献任何东西。只有当一个 profile 完全没有点名凭据时,pi-ai 才交给提供方原生的发现流程;配置了引用却解析不到,就以 `MISSING_CREDENTIAL` 失败,并点名该路由与该引用。启动时的凭据探测被删除:它可能在凭据服务挂载之前就运行,并把每一种失败都报成密钥缺失,而第一次请求本就会给出准确的错误。 **路由替换是注册表的操作,不是调用方的一串步骤。**`registerAdapter` 返回一个携带 `replace(providers)` 的句柄:候选集合先被完整校验(冲突、名称、提供方元数据),再在一个同步区段内完成替换。被拒绝的替换会让先前的路由保持注册并继续服务,而调用方的事实缓存只有在注册表确实持有新集合之后才会推进,因此改回可用配置时会重新生效。pi-ai 的注册事实按提供方排序,因此仅仅调换键顺序的设置文档不再算作路由变更。 diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml index 8d8498f8bb..6f1e439bdf 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml @@ -9,8 +9,8 @@ en: 44615a7a0939054e zh: b8efa721321ba0d7 /agent-note-creator-mode-installs-persistent-plugin-bundles/decision: - en: 38ecabc170c418c7 - zh: d380f53fa508328e + en: 013a2088d8f8c435 + zh: 5491ff817716696b /agent-note-creator-mode-installs-persistent-plugin-bundles/alternatives-considered: en: af527d8aabdfd59c zh: 34388da992d2ab56 diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md index 8fa2b574f6..f831e40520 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md @@ -14,7 +14,7 @@ Creator mode enables the existing `plugin_manager` tool. Agents author packages The default Standard mode enables the same tool under the same profile condition and approval gate. Without it, Standard sessions did not install plugins directly and spent extra turns and tokens working around the missing tool; the change also moves Standard and Creator toward one capability set. A full-access Standard session can therefore install Host code without a separate prompt, as its shell already can. PTC and Minimal keep the tool disabled. -The model sees two read-only Cordis inspection tools. Generated-code define/run/stop/undefine and dynamic self-inspection tool APIs are absent. Existing runtime and Client consumers retain their services; historical session cards remain readable. This supersedes only the model-facing mutation workflow in the [self-referential toolset reference](../../../../packages/extensions/cordis-host-runner/README.md); its runtime ownership and sandbox rationale remain independently relevant. The [profile transaction decision](2026-09-14-current-profile-plugin-management.md) continues to govern locking, package installation, and partial failures. +Standard and Creator expose one read-only Cordis inspection tool, `cordis_inspect`. Omitting `query` discovers providers; supplying `query` reads one declared method. The shared entry keeps runtime discovery available in the default mode without duplicating tool descriptions. Generated-code define/run/stop/undefine and dynamic self-inspection tool APIs are absent. Existing runtime and Client consumers retain their services; historical session cards remain readable. This supersedes only the model-facing mutation workflow in the [self-referential toolset reference](../../../../packages/extensions/cordis-host-runner/README.md); its runtime ownership and sandbox rationale remain independently relevant. The [profile transaction decision](2026-09-14-current-profile-plugin-management.md) continues to govern locking, package installation, and partial failures. Visual creation requests default to an installed Client plugin rendered in the current Web page unless the user names another destination. The development skill supplies a minimal package and effect-owned Client registration. Discovery ends when the required APIs are known; a working first version is installed before optional visual refinement. Verification uses the connected page where available. Browser authentication or operating-system setup is not a prerequisite for plugin installation, and a mock preview cannot establish an in-app result. diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md index b5c0ad0cb2..b3b686385f 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md @@ -14,7 +14,7 @@ agent 需要安装能力并在同一段对话中使用。生成代码工具在 默认的标准模式以相同的 profile 条件和审批门槛启用同一工具。缺少该工具时,标准模式会话不会直接安装插件,而要额外花费轮次和 token 绕过;此改动也让标准模式和创造模式朝同一能力集收敛。因此,完整权限的标准模式会话无需单独审批即可安装 Host 代码,与其 shell 已有的能力一致。PTC 和 Minimal 仍禁用该工具。 -模型可见两个只读 Cordis 检查工具,不再提供生成代码的 define/run/stop/undefine 和动态自省工具 API。现有运行时和 Client 消费者保留其服务;历史会话卡片仍然可读。这仅取代[自引用工具集参考](../../../../packages/extensions/cordis-host-runner/README.zh.md)中的模型侧变更流程;其运行时所有权和沙箱依据仍有独立价值。[profile 事务决策](2026-09-14-current-profile-plugin-management.zh.md)继续规定锁、包安装和部分失败行为。 +标准模式和创造模式提供一个只读 Cordis 检查工具 `cordis_inspect`。省略 `query` 以发现 provider;提供 `query` 以读取一个已声明的方法。共用此入口使默认模式能够进行运行时发现,同时避免重复的工具描述。不再提供生成代码的 define/run/stop/undefine 和动态自省工具 API。现有运行时和 Client 消费者保留其服务;历史会话卡片仍然可读。这仅取代[自引用工具集参考](../../../../packages/extensions/cordis-host-runner/README.zh.md)中的模型侧变更流程;其运行时所有权和沙箱依据仍有独立价值。[profile 事务决策](2026-09-14-current-profile-plugin-management.zh.md)继续规定锁、包安装和部分失败行为。 除非用户指定其他目标,视觉创建请求默认通过已安装的 Client 插件显示在当前 Web 页面。开发 skill 提供最小包和由 effect 管理的 Client 注册示例。已知所需 API 后结束探查,在可选视觉优化之前先安装能工作的初版。有条件时使用已连接页面验证。浏览器认证或操作系统设置不是安装插件的前提,mock 预览不能证明应用内结果。 diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml index 883bb12bc0..e877a2ccc2 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml @@ -9,11 +9,11 @@ en: 8d4d00e33af763b2 zh: 61977c82d66ae9bf /agent-note-account-provider-and-active-request-cancellation/decision: - en: d5eb12a1644c6226 - zh: 513d4f22ab74e039 + en: 383ef40d2ec7b6f1 + zh: 2e9482475015b1ff /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 diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md index 6b8ef842c5..bb2f639601 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md @@ -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 [DeepSeek request authentication decision](2026-11-10-deepseek-request-authentication.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 diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md index 588dd38bf9..1cfd3c435b 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md @@ -14,11 +14,11 @@ Status: implemented 账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。 -本地退登成功后发布账号事件。Platform 账号提供方安装账号模块的监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。账号控制器的退登确认复用同一判断函数。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。 +本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由 [DeepSeek 请求鉴权决策](2026-11-10-deepseek-request-authentication.zh.md)负责。 ## Alternatives considered -历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。登录级取消信号重复现有 Agent 与 HTTP 取消链路。 +历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的撤回信号只是对它的补充。 ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml index ee3f5d9048..e1b5d0b632 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml @@ -9,8 +9,8 @@ en: e42db40b879fdbf4 zh: 6017da9c4da17835 /agent-note-node-ptc-execution-modes-and-in-memory-state/decision: - en: 411054071757d5fe - zh: e683ef7d80f33fc6 + en: 13a72b9728d25394 + zh: 1f44510fe93836dc /agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered: en: 396157a9fc293198 zh: a061f05b4423e26f diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md index c311f397dc..1998b28e64 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md index f91dfff11b..c9fe0a24a5 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md @@ -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)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml index badb03541e..6bcaf5bb56 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml @@ -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: 9bf594047ad5c864 + zh: 366263d56f8a4fbf /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered: en: 6da221f6b821ea44 zh: b15774011abed7ed diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md index 2399e3f1fc..cbf8b2a4d9 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md @@ -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, in a conversation on the account route, whether `ctx.deepseekAuth` has the account sign-in 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, the account sign-in configured for the endpoint under that route's origin 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); `ctx.deepseekAuth` performs these checks, a key's through the reference helpers of `dsh-credentials`. 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. diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md index 61f8acb6f8..29e5b96e2e 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md @@ -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.deepseekAuth` 是否已为其 Messages 端点配置账号登录凭据,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,为该路由 origin 之下的端点配置的账号登录凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `ctx.deepseekAuth` 执行,其中密钥的检查经由 `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 能力不看路由,恰在其自身密钥已配置时就绪。 diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml index 68269e8997..93432e3ee9 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml @@ -15,8 +15,8 @@ en: 7f33895364a9f5cc zh: f1c79ea15f5c151e /agent-note-initial-draft-content-and-structured-reference-restoration/decision/classes-and-methods: - en: e57394545d9d93ff - zh: 5ab142e661750b82 + en: 9039c6bf700da3cf + zh: 2808757aed8615b3 /agent-note-initial-draft-content-and-structured-reference-restoration/decision/data-flow: en: dd57e639e9328f1d zh: 5e16cb2e3a73597c diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md index cbb15cc56a..24355ccf35 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md @@ -37,7 +37,7 @@ The existing `dsh.conversation.` key remains. Readers accept both leg | `SessionInputShell.refreshLexiconSubscription()` / `DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` owns the Session-scope `inject` callback that connects the lexicon after caching the shell, reconnects when the service arrives or is replaced, and unsubscribes on disposal. Both connection and catalog updates rescan the current editor without writing old text back; `setDraft` does not establish the subscription | | `ConversationStoreState` / `createConversationStore` | Support structured input and legacy strings in draft storage, keeping View state and the original key | | `DefaultConversationViews` | Remove restoration and prefill effects, retaining persistence binding and unbinding. Initial saving reads the owner's current snapshot, never text captured during render | -| The existing `selectWorkspace` callback in `apply.ts` | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references | +| The cross-Workspace draft move (`moveDraft` in `apply.ts`) | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references | There is no new draft service, storage key, general task framework, or Session creation entry point. SlotRenderer, Host Session logs, command execution, and file-discovery RPCs are unchanged. `InputActions` remains the shared input-action entry; components receive no separate content-initialization callback. diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md index 12d4e4731a..8a3a964e95 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md @@ -37,7 +37,7 @@ Status: implemented | `SessionInputShell.refreshLexiconSubscription()`/`DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` 拥有 Session scope 的 `inject` 回调,在缓存输入对象后连接词典,服务到达或替换时重接,销毁时退订。连接和词典更新都会重扫当前 editor,不覆盖旧文本;`setDraft` 不负责建立订阅 | | `ConversationStoreState`/`createConversationStore` | draft 支持兼容旧字符串的结构化输入,View 状态及原 key 保持 | | `DefaultConversationViews` | 删除恢复/预填 effect;保留持久化回调的绑定和解绑。初始保存只能读取 owner 的当前快照,不能把 render 时的旧文字写回 | -| `apply.ts` 中现有 `selectWorkspace` 回调 | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 | +| 跨工作区的草稿移动(`apply.ts` 中的 `moveDraft`) | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 | 不新增草稿服务、存储 key、通用任务框架或另一套 Session 创建入口;不改 SlotRenderer、Host Session 日志、命令执行和文件发现 RPC。`InputActions` 保留统一输入操作入口,组件不单独注入另一条内容初始化回调。 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml index fdbd7de7cb..86b1b861c4 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml @@ -24,8 +24,8 @@ en: 428699f74f19e998 zh: 2e8fcdbc9616f70b /agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/watching-and-client-plugin-delivery: - en: f3e6ba098433a70a - zh: 345b93f451d2768c + en: 814c344e891f7f91 + zh: a024d5e30607968b /agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/alternatives-considered: en: 99ee505e82fa9c7c zh: 448bc0e160424cbf diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md index b4c4c539ee..90f71ebcdf 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md @@ -61,7 +61,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_ ### Watching and Client plugin delivery - Worker `fs.watch` and `fs.watchFile` listeners run in the async context where the watcher was created, as Node delivers watch events from the watch handle, not in the context of the code whose write produced the event. HMR's configuration watcher therefore runs outside the writer's HMR transaction, and a configuration write made inside a transaction does not make the follow-up reload fail as a nested transaction. -- The browser half of `@deepseek-ai/dsh-client-hmr` reads `/plugins/events` through the page's `__DSH_TRANSPORT__.fetch` when a shell provides one (the Worker preview tunnel), otherwise through `EventSource`. The Client plugins of a bundle enabled in the Preview therefore mount without a page reload. +- The browser half of `@deepseek-ai/dsh-client-hmr` follows the `pluginEvents/follow` Remote stream over the Remote carrier the page's Connection provides, including the Worker preview tunnel. The Client plugins of a bundle enabled in the Preview therefore mount without a page reload. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md index a5344f8b01..4b46aceeee 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md @@ -61,7 +61,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错 ### 文件监听与 Client 插件下发 - Worker 的 `fs.watch` 和 `fs.watchFile` 监听器在创建 watcher 时的异步上下文里运行,与 Node 从 watch 句柄派发事件一致,而不是在写入方的上下文里运行。因此 HMR 的配置 watcher 在写入方的 HMR 事务之外运行,事务内的配置写入不会让随后的重载因嵌套事务而失败。 -- `@deepseek-ai/dsh-client-hmr` 的浏览器部分在 shell 提供 `__DSH_TRANSPORT__.fetch` 时(Worker preview 隧道)经它读取 `/plugins/events`,否则经 `EventSource` 读取。因此在 Preview 里启用 bundle 后,其 Client 插件无需刷新页面即可挂载。 +- `@deepseek-ai/dsh-client-hmr` 的浏览器部分经页面 Connection 提供的 Remote 载体(包括 Worker preview 隧道)跟随 `pluginEvents/follow` Remote 流。因此在 Preview 里启用 bundle 后,其 Client 插件无需刷新页面即可挂载。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.i18n.yaml new file mode 100644 index 0000000000..8cc646b188 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-27-plugin-cli-absolute-paths.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.md +/agent-note-plugin-clis-by-absolute-path-in-runtime-context: + en: cf842dd82c5a905a + zh: 1cb7923bbc0e3583 +/agent-note-plugin-clis-by-absolute-path-in-runtime-context/problem: + en: 623b3e7c6bbb038d + zh: 0c3725119fb9c41e +/agent-note-plugin-clis-by-absolute-path-in-runtime-context/decision: + en: 3911a3ee37139116 + zh: 648b896c5c71b16d +/agent-note-plugin-clis-by-absolute-path-in-runtime-context/alternatives-considered: + en: 7c2f56152247cadf + zh: a77e41a020ec6835 +/agent-note-plugin-clis-by-absolute-path-in-runtime-context/consequences: + en: c80b941f81db6daf + zh: 964ff6d38b3903d1 diff --git a/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.md b/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.md new file mode 100644 index 0000000000..fb74ba6e93 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.md @@ -0,0 +1,35 @@ +# Agent Note: Plugin CLIs by absolute path in runtime context + +Status: implemented + +English | [中文](2026-10-27-plugin-cli-absolute-paths.zh.md) + +## Problem + +CLI app plugins such as Feishu, WeCom, DingTalk, and Tencent Meeting install a vendor CLI outside PATH. The upstream guides, the CLIs' own messages, and the DingTalk and WeCom skill scripts call it by name. The model must run the plugin's installation, not another installation or none, and the harness should not change how model commands run to make that happen. + +## Decision + +Each app plugin registers its CLI's absolute path with `ctx.cliAccounts`, the Service of [`@deepseek-ai/dsh-cli-account`](../../../../packages/connector/cli-account/README.md). The Service registers required runtime context at the `PLUGIN_CLIS` context order, without interpolation, that tells the model to run the CLI by that path. For a skill whose scripts call the CLI by name, which applies to DingTalk and WeCom, the context also tells the model to prefix only the commands that run those scripts with `PATH=":$PATH"`, and never to export PATH or run the CLI by name. On Windows, where the shipped compositions mount `tool-pwsh` instead of `tool-bash`, the text uses PowerShell syntax: the call operator, `& ''`, and the prefix `$env:PATH = ';' + $env:PATH`. Skills tell the model to use the path from the current runtime context. The plugin's own sign-in, status, and sign-out commands spawn the same path through the Service's command runner. + +The harness changes no command environment: Bash, PowerShell, the sandbox, persistent terminals, and hooks run as they do without these plugins. Tencent Meeting registers its platform executable, `dist/tmeet-`. The DingTalk context contributes nothing until dws and its skills are installed. No load-time check requires commands to run on the Host; when a composition runs commands over SSH, a command fails when it reaches the missing path. + +## Alternatives considered + +**A private PATH.** Shell executors and the plugin backend put each plugin's bin directory first on PATH, and a system-prompt section listed the plugin CLIs. This needed a path prefix in every shell request, a prepared environment for backend commands, a Host-runtime check, and a `tmeet` symlink for Tencent Meeting. Persistent terminals and hooks did not get the prefix, and it hid a CLI of the same name that the user installed. + +**Paths in skill text.** The model sees a skill's text only after loading it, compaction can reduce that text to a summary, and history keeps the old path after an upgrade. Static skill files would also have to be generated at run time. + +**One shared registry and one combined entry.** Rewriting shell-env or adding a package for it states the rule once, but adds a service and its documentation for four callers. Other runtime contexts, such as the working directory and the sandbox policy, are registered by the package that owns the fact; a separate entry per plugin only repeats one sentence. + +**A Host check.** Shipped profiles always run commands on the Host. The check would only move an SSH composition's failure from first use to load, at the cost of a `runsOnHost` member on the subprocess and shell services. + +**A hint after a failed bare-name command.** Appending the path to the tool result when a command cannot find a registered name would correct the model after the failure, but no evidence yet shows that the context text alone is insufficient. + +## Consequences + +The model, not PATH, maps each name to its path. Counted on 2026-10-23, the upstream guides call the CLIs by name on 3,004 lines for DingTalk, 2,542 for Feishu, 321 for WeCom, and 248 for Tencent Meeting, and 33 DingTalk scripts call `dws` by name. A command that still uses the bare name runs the installation that PATH resolves, or fails because none is found; nothing rewrites it. The script sentence forbids exporting PATH and running the CLI by name because, in real-model runs, a sentence that only asked for the prefix on script commands led the model to export PATH and then run the CLI by name. Approval details, tool cards, and job lists show the full path. + +A CLI that the user installed under the same name is no longer hidden, and persistent terminals and hooks need no PATH handling. Runtime context stays out of the cached system prompt and is admitted again after compaction; installing, enabling, or disabling a plugin appends one runtime-context snapshot. The text's dialect follows the Host platform with the same test the compositions use to choose the shell tool, so a composition that mounts the other shell on a platform gets the wrong syntax. + +Unit tests in the kit pin the text, required status, literal paths, readiness, and removal on disposal; each plugin's recorded Session snapshot pins its rendered context. diff --git a/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.zh.md b/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.zh.md new file mode 100644 index 0000000000..3faa6fbcf8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 插件 CLI 通过运行时上下文给出绝对路径 + +Status: implemented + +[English](2026-10-27-plugin-cli-absolute-paths.md) | 中文 + +## Problem + +飞书、企业微信、钉钉、腾讯会议等 CLI 应用插件把厂商 CLI 装在 PATH 之外。上游指南、CLI 自己的提示信息,以及钉钉和企业微信 skill 里的脚本,都按名称调用 CLI。模型必须运行插件安装的那一份,而不是别的安装或者找不到,同时 harness 不应为此改变模型命令的运行方式。 + +## Decision + +每个应用插件把 CLI 的绝对路径注册到 [`@deepseek-ai/dsh-cli-account`](../../../../packages/connector/cli-account/README.zh.md) 的 Service `ctx.cliAccounts`。这个 Service 在 `PLUGIN_CLIS` 上下文顺序处注册一条必需、不做变量插值的运行时上下文,让模型按这个路径运行 CLI。skill 里的脚本按名称调用 CLI 时(钉钉和企业微信属于这种情况),这条上下文还让模型只在运行这些脚本的命令前加上 `PATH="<目录>:$PATH"`,并且不要导出 PATH,也不要按名称运行 CLI。在 Windows 上,内置组合挂载 `tool-pwsh` 而不是 `tool-bash`,文本改用 PowerShell 语法:调用运算符 `& '<路径>'`,以及前缀 `$env:PATH = '<目录>;' + $env:PATH`。skill 让模型使用当前运行时上下文给出的路径。插件自己的登录、状态和登出命令通过这个 Service 的命令执行器启动同一路径。 + +harness 不改变任何命令的环境:Bash、PowerShell、沙箱、持久终端和 hook 的运行方式与没有这些插件时相同。腾讯会议直接注册各平台的可执行文件 `dist/tmeet-<平台>`。钉钉的上下文在 dws 和钉钉 skill 安装完成前不贡献任何内容。加载时不检查命令是否在 Host 上运行;组合把命令放到 SSH 远端运行时,命令在访问不存在的路径时失败。 + +## Alternatives considered + +**私有 PATH。** Shell 执行器和插件后端把各插件的 bin 目录放到 PATH 最前面,再由一段系统提示词列出插件 CLI。这需要在每个 shell 请求里加路径前缀、为后端命令准备环境、检查 runtime 是否在 Host 上,并为腾讯会议建一个 `tmeet` 符号链接。持久终端和 hook 拿不到这个前缀,而且它会遮住用户自己安装的同名 CLI。 + +**把路径写进 skill 正文。** 模型要加载 skill 之后才看得到正文,压缩可能把正文缩成摘要,升级之后历史里留的还是旧路径。静态的 skill 文件也要改成运行时生成。 + +**一个共享注册表、合成一条上下文。** 改造 shell-env 或为此新建一个包,可以只写一次规则,但要为四个调用方增加一个服务及其文档。工作目录、沙箱策略等其他运行时上下文都由掌握该事实的包自己注册;每个插件各一条,只是重复一句话。 + +**检查是否在 Host 上。** 发布的 profile 总在 Host 上运行命令。这个检查只会把 SSH 组合的失败从首次使用提前到加载,代价是 subprocess 和 shell 服务上多一个 `runsOnHost` 成员。 + +**按名称调用失败后追加提示。** 命令找不到已注册的名称时在工具结果里追加路径,可以在失败后纠正模型,但目前没有证据表明仅靠上下文文字不够。 + +## Consequences + +把名称换成路径的是模型,不再是 PATH。按 2026-10-23 的统计,上游指南按名称调用 CLI 的行数为:钉钉 3,004 行、飞书 2,542 行、企业微信 321 行、腾讯会议 248 行;钉钉还有 33 个脚本按名称调用 `dws`。仍用名称的命令会运行 PATH 解析到的那份安装,或者因为找不到而失败;没有任何机制改写它。脚本那句话之所以禁止导出 PATH 和按名称运行 CLI,是因为在真实模型的运行中,只要求给脚本命令加前缀的写法会让模型先导出 PATH、再按名称运行 CLI。审批详情、工具卡和任务列表显示完整路径。 + +用户自己安装的同名 CLI 不再被遮住,持久终端和 hook 也不需要处理 PATH。运行时上下文不进入缓存的系统提示词,压缩后会重新提交;安装、启用或停用插件时追加一份运行时上下文快照。文字的写法按 Host 平台选择,判断条件与组合选择 shell 工具的条件相同;因此某个平台上的组合如果挂载了另一种 shell,得到的写法就不对。 + +kit 的单元测试固定了文字、必需状态、路径原样保留、就绪条件和释放时移除;每个插件的录制会话快照固定了它渲染出的上下文。 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml index 9ad135dbed..5c0fef0e12 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml @@ -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: dca56d7ced4e5294 + zh: e984a7fddac3228f /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections: en: 5fcd3319fbceed1d zh: 20771646b9c36fa6 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md index 82bfa34cfb..9c903db910 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md @@ -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 connects to `ctx.deepseekAuth`, 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 of the mounted `deepseek-official` route, read under that route's `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 mounted DeepSeek routes, which includes either DeepSeek route id while its plugin is not mounted, 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 mounted `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. +`ctx.deepseekAuth` orders and releases these credentials ([DeepSeek request authentication](2026-11-10-deepseek-request-authentication.md)): each DeepSeek model route connects the deployment its settings name, the API-key route with its key reference under `apiKeyEnv`, and the account sign-in is the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs ask that service instead of reading provider configuration, and it reads route keys, `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 authorization 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 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md index f995d39d19..ae7f79c9cb 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md @@ -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.deepseekAuth` 登记的基础地址的 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 路由之外的路由上(包括这两个路由 id 之一而其插件未挂载的情况)或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在已挂载的 `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 密钥路径就能工作。 +这些凭据由 `ctx.deepseekAuth` 排序并释放([DeepSeek 请求鉴权](2026-11-10-deepseek-request-authentication.zh.md)):每条 DeepSeek 模型路由登记其设置所指的部署,API 密钥路由同时登记其 `apiKeyEnv` 下的密钥引用,账号登录凭据则是 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 向该服务索取凭据而不读取提供方配置,该服务通过 `dsh-credentials` 的引用函数读取路由密钥、`DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 ### 默认值与已保存的选择 diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml new file mode 100644 index 0000000000..121a9d669b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md new file mode 100644 index 0000000000..93138b065e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md new file mode 100644 index 0000000000..e2c7a56b41 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md @@ -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 与桌面端组合都会加载注册表。启动调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.i18n.yaml index 4fefcfd5c3..b5aa2ca4af 100644 --- a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md index d2d688ed61..7b79c31002 100644 --- a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md @@ -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 | diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.zh.md b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.zh.md index 15919e55f7..0595cb9f85 100644 --- a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.zh.md @@ -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 | diff --git a/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.i18n.yaml new file mode 100644 index 0000000000..81a31b6f26 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-08-mcp-connector-accounts.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-08-mcp-connector-accounts.md +/agent-note-mcp-connector-accounts-in-the-connector-account-registry: + en: de9535f7ca161ae3 + zh: 50be52d2946e2058 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/problem: + en: 3fcafe54fc134ff3 + zh: bbef331a0d9eccd5 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/decision: + en: b6d50660986dad38 + zh: 4903122d0efd6e68 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/alternatives-considered: + en: 0b7871c3d4aa7c52 + zh: c26061baed87bee4 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/consequences: + en: c90b9de7c3b4e662 + zh: 7e126b5ac0f3e59e diff --git a/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md new file mode 100644 index 0000000000..6c1a800e5a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md @@ -0,0 +1,35 @@ +# Agent Note: MCP connector accounts in the connector account registry + +Status: implemented + +English | [中文](2026-11-08-mcp-connector-accounts.zh.md) + +## Problem + +Connector plugins such as Linear, Notion, and Tencent Docs register an OAuth MCP server with the MCP manager on the Host and show its account on the Plugins page. The manager already owns the authorization attempt, the grant, and the server status, and every connector shares the same states, buttons, and 23 strings. The [connector account registry](2026-11-06-connector-account-registry.md) shows each account from a Host source and presenter, so MCP needs one adapter that turns the manager's view of a server into that source and presenter. + +## Decision + +[`@deepseek-ai/dsh-mcp-account`](../../../../packages/mcp/mcp-account/README.md) provides `ctx.mcpAccounts`. A connector's Host row registers its server name, its bundle package, and the copy that names its service; the service registers the account with `ctx.connectorAccounts` under the key `mcp:`. + +| Part | Choice | +|---|---| +| Source | Reads the manager's `list()` entry for the server and observes `mcp-manager/status`; `refresh` does nothing, because the manager publishes every change | +| Operation | A running authorization attempt is the operation and its identity is the operation's, so the browser that started it follows the manager's own attempt; a finished attempt is the result | +| Page operations | `connect` starts authorization, also while connected, so the user changes the account or workspace without deleting the grant first; `sign-out` and `retry` sign out and restart through the manager and report their own result once they finish | +| Phases | Waiting for the browser and authorizing are connecting; a server that needs authorization again is disconnected, with the reason in its detail; a closed, waiting, disabled, or failed server is unavailable, with Retry only where a restart recovers it | +| Copy | The 23 strings every connector shares are Host dictionaries in eight languages; each connector supplies only the strings that name its service | + +The manager's `startAuthorization`, `cancelAuthorization`, and `signOut` are Host methods without a Remote, so no browser names a server to authorize. + +## Alternatives considered + +**Keep the manager's authorization operations on its Remote.** Rejected: the page would pass a server name the Host already holds, and two paths would start the same attempt. + +**Track an adapter-owned operation for each authorization.** Rejected: the manager already tracks the attempt's identity, phases, and authorization page, so a second tracker would restate it. The registry lets a source answer `start` once the manager has created the attempt. + +**Key each connector's account by its package.** Rejected: the server name is unique among MCP accounts, so the key also refuses a second account for one server, and a server configured in Settings, which no bundle owns, uses the same form. + +## Consequences + +A connector ships no browser code and no page rules; the shared page renders its account. An account that needs reconnection shows as disconnected without a separate warning color, and its status and detail name the reason. Each browser follows the one registry stream, and the Host follows the manager through its status event. diff --git a/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.zh.md b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.zh.md new file mode 100644 index 0000000000..953d1e5b8c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.zh.md @@ -0,0 +1,35 @@ +# Agent Note:MCP 连接器账号接入连接器账号注册表 + +Status: implemented + +[English](2026-11-08-mcp-connector-accounts.md) | 中文 + +## 问题 + +Linear、Notion、腾讯文档等连接器插件在 Host 上向 MCP 管理器注册 OAuth MCP 服务器,并在插件页显示其账号。管理器已经持有授权尝试、grant 和服务器状态,各连接器的状态、按钮和 23 条文案都相同。[连接器账号注册表](2026-11-06-connector-account-registry.zh.md)根据 Host 上的来源和展示函数显示每个账号,因此 MCP 需要一个适配,把管理器对服务器的视图转换为这样的来源和展示函数。 + +## 决定 + +[`@deepseek-ai/dsh-mcp-account`](../../../../packages/mcp/mcp-account/README.zh.md) 提供 `ctx.mcpAccounts`。连接器的 Host 行注册其服务器名、插件包以及点出服务名称的文案;该服务以 `mcp:` 为键,把账号注册到 `ctx.connectorAccounts`。 + +| 部分 | 选择 | +|---|---| +| 来源 | 读取管理器 `list()` 中该服务器的条目,并观察 `mcp-manager/status`;`refresh` 什么也不做,因为管理器会发布每次变化 | +| 操作 | 进行中的授权尝试就是操作,其 id 就是操作的 id,因此发起它的浏览器跟随的是管理器自己的尝试;结束的尝试就是结果 | +| 页面操作 | `connect` 发起授权,已连接时也可用,用户不必先删除授权就能更换账号或工作区;`sign-out` 和 `retry` 通过管理器退出登录、重启服务器,结束后报告各自的结果 | +| 阶段 | 等待浏览器和授权中属于连接中;需要重新授权的服务器属于未连接,原因写在说明里;已关闭、等待凭据、已停用或失败的服务器属于不可用,只有重启能恢复时才提供“重试” | +| 文案 | 各连接器共用的 23 条文案是 Host 上 8 种语言的字典;每个连接器只提供点出其服务名称的文案 | + +管理器的 `startAuthorization`、`cancelAuthorization` 和 `signOut` 是不带 Remote 的 Host 方法,因此浏览器不会指定要授权的服务器。 + +## 考虑过的替代方案 + +**管理器的授权操作继续走它的 Remote。** 否决:页面要传入 Host 已经知道的服务器名,而且会有两条路径发起同一次尝试。 + +**为每次授权维护适配自己的操作。** 否决:管理器已经记录尝试的 id、阶段和授权页,第二套记录只会重复它。注册表允许来源在管理器创建尝试后再回答 `start`。 + +**以插件包作为连接器账号的键。** 否决:服务器名在 MCP 账号中唯一,因此这个键也会拒绝同一服务器的第二个账号;没有插件包的、在 Settings 中配置的服务器也使用同样的键。 + +## 影响 + +连接器不提供任何浏览器代码和页面规则,由共用的页面渲染其账号。需要重新连接的账号显示为未连接,不再单独使用警示色,其状态和说明会点出原因。每个浏览器跟随同一条注册表流,Host 通过管理器的状态事件跟随管理器。 diff --git a/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.i18n.yaml new file mode 100644 index 0000000000..c0667c2eef --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-10-deepseek-request-authentication.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-deepseek-request-authentication.md +/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer: + en: 0ede9c11789e5fd7 + zh: c3e552dfe6216df0 +/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/problem: + en: 1470ef8f922d447a + zh: ccd66a1b897c88e2 +/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/decision: + en: 316f5dc600e50f33 + zh: f52cacf521e94159 +/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/alternatives-considered: + en: 3a4f69542b4a91b2 + zh: 1eb4edce81a858d6 +/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/consequences: + en: 88174cd0c4fca1ee + zh: ae56350b8198a0b0 diff --git a/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md new file mode 100644 index 0000000000..38eec99134 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md @@ -0,0 +1,73 @@ +# Agent Note: DeepSeek request authentication - one service releases the API key or the account sign-in to every DeepSeek consumer + +Status: implemented + +English | [中文](2026-11-10-deepseek-request-authentication.zh.md) + +## Problem + +DeepSeek APIs accept two kinds of credential, an API key and the account sign-in, and each API accepts one or both: the Messages, Files, and model-listing requests of each model route carry one kind, Search and Fetch accept both, and DeepSeek adds account authentication to its other APIs one at a time. No package owned the choice between the two kinds. `@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, ordered the two credentials by their billing setting, and rendered the request headers; Messages search hard-coded the account route id and applied an order of its own. Both web packages therefore depended on `llm-deepseek`, on both route plugins, and on the Loader, and a consumer of another DeepSeek API would have repeated the selection, the deployment binding, the header rendering, and the invalidation. 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-deepseek-auth`, in the `packages/account/` group, provides `ctx.deepseekAuth`. The package holds the Service Definition and the Service Provider of DeepSeek request authentication, and every plugin that calls a DeepSeek API is a Consumer. A consumer describes one request: the credential kinds its API `accepts`, the `billing` its settings choose, the model `route` of the conversation, and a `destination`, either a path under the chosen kind's deployment or one absolute URL. `candidates(request)` returns the kinds in billing order, each bound to the endpoint its credential is sent to, and reads no credential. `authorize(request, signal)` releases the first kind that has a credential as a `DeepSeekAuthorization`: the `kind`, the `endpoint`, the request `headers`, the key `reference` for diagnostics, and for the account sign-in a `reject()` for HTTP 401 and a `revoked` signal that aborts when the account signs out. An authorization carries no bare credential value: a consumer names the headers an API key is sent in through `apiKeyHeaders`, and the account service chooses the header of the sign-in. + +The service owns the billing order. `api-key` and `account` billing try that kind only. `auto` follows the conversation: on the route a plugin connected for the account sign-in, the sign-in and then the API key; on the route a plugin connected for the API key, the API key; on any other route, or outside a conversation, the API key and then the sign-in. The service names no route id: each model route plugin passes the provider route it registers when it connects, and `routeKind(route)` answers the kind connected under that id. A conversation recorded on `deepseek-account` or `deepseek-official` whose plugin is not mounted is ordered as any other route. A kind outside `accepts` is never a candidate. + +Each kind has one deployment at a time. A model route plugin connects its provider route and the deployment its settings name with `connect(kind, route, connection)` inside `ctx.effect()`, and the service calls `connection` for each request. Without a connection the API key is `DEEPSEEK_API_KEY` at `https://api.deepseek.com`, and the sign-in goes to the origin `DEEPSEEK_BASE_URL` names, the official API by default. A credential is released only for a destination under the origin of its kind's deployment that embeds no credentials. A request can carry its own connection of a kind in `connections`, which replaces the connected or default one: a model route passes the configuration generation it captured for one model request, and a consumer with its own endpoint and key passes those. A kind whose connection does not resolve stays among the candidates as an unresolved entry, and `authorize()` stops there with `UNRESOLVED_CONNECTION` and does not try a later kind. + +The API key is read through `resolveCredentialRef` and `credentialRefConfigured` of `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one. `dsh-credentials` also owns `normalizeApiKey`, the Host definition of a key that an HTTP header can carry, which answers the trimmed key or the reason a key cannot be used and words no diagnostic. The service words the diagnostic of an unusable key and reports it as `DeepSeekAuthError` with code `INVALID_CREDENTIAL`, `llm-pi-ai` words its own and reports it as `LlmError`, and `@deepseek-ai/dsh-llm` holds neither a credential interface nor a key check. The account sign-in is what `ctx.deepseekAccount.resolveRequestCredential(endpoint)` releases; it is absent in a composition without the account service. + +`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the request headers, an optional `revoked` signal, and an optional failure callback, or `undefined`; `missingCredential(connection, provider)` names the failure of a request without a credential, `MISSING_CREDENTIAL` by default. The transport runs each model request and its file operations under the `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 are consumers that also connect their deployment, and both require the service. `llm-deepseek-api-key` connects, under its route id, its base URL, its `apiKeyEnv` reference, and its settings namespace as the owner that key diagnostics name; it asks for the key in `x-api-key` with `accepts: ['api-key']` and reports an unusable key as its own `INVALID_CREDENTIAL`. `llm-deepseek-account` connects its base URL under its route id, asks with `accepts: ['account']`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, 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 authorization'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 to the authentication service. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the account service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The account service inspects no Agents and depends on neither `dsh-agent`, `dsh-llm`, nor the authentication service. The package lives in the `packages/account/` group under its unchanged name. + +The web providers declare what their APIs accept. `web-deepseek-api` asks for candidates with `accepts: ['account', 'api-key']`, the capability's billing, the conversation's route, and the path `/v1/tools/search` or `/v1/tools/fetch`; a capability with its own `*BaseURL` or `*ApiKeyEnv` asks with `accepts: ['api-key']` and its own connection, so only that key goes to that endpoint. `web-search-deepseek` passes its search endpoint as an absolute destination and its referenced key as its own connection. In a conversation on the connected account route it asks with `auto` billing, so the sign-in comes first when the search endpoint is under the origin of the account deployment; every other search asks with `api-key` billing. A literal `apiKey` is the provider's own credential: beside it the provider asks only for the sign-in, and sends the literal key when the service releases none. `web-deepseek-api` words its missing-credential and unresolved-settings failures from the candidates. Both web consumers contain a failed `reject()` so the HTTP rejection stays the reported error, run their request under the authorization's `revoked` signal, and report a request that signal 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, the Loader, or the account service, and neither reads a credential through `dsh-llm`: `web-search-deepseek` does not depend on it, and `web-deepseek-api` imports only the message text helper `extractTextContent` from it. + +## Alternatives considered + +**Publishing each route's credential through the model service.** `LlmAdapter.providerCredential(provider)` on `dsh-llm` would answer a route's credential kind, its base URL, and a grant for one endpoint, and consumers would read `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`. A lookup keyed by model route leaves every consumer to order the two credentials by billing, to render its own headers from a bare value, and to fall back by itself when a route is not mounted. An API outside the model protocol, such as the speech and document APIs under `/v1/tools/`, has no route to ask and no place to declare the kinds it accepts. The model service would carry a credential interface with one publisher, the DeepSeek adapter, and two web consumers. + +**A shared library over that publication instead of a service.** The model routes authenticate through the same operation as every other consumer, and a library that reads what the routes publish cannot serve the routes themselves. + +**Checking keys through `dsh-llm`, through a copy in the service, or through a validator each consumer passes.** A service shared by every DeepSeek consumer must not depend on the model service, which is one consumer's dependency. A second Host copy of the rule would be kept in step with the first and with the browser's copy by comments only. A validator parameter would make each consumer that accepts a key pass one, and the web packages would keep their `dsh-llm` dependency for it. The check lives in `dsh-credentials`, the layer that reads the key, and each caller words its own failure for the reason the check returns. + +**The diagnostic text of an unusable key in `dsh-credentials`.** One function there would give the service and `llm-pi-ai` the same words. The text tells the user to set the reference on the Models page, so the package that stores credentials would name a page of its consumers. Each of the two callers words the text, and the credential store names no consumer. + +**`dsh-llm` importing the key check from `dsh-credentials`.** Nothing in the model service reads a key. Its only caller of the check was `llm-pi-ai`, which already depends on `dsh-credentials`, so the model service exports no key check and gains no dependency. + +**A `deepseek-api-key` package beside `deepseek-account`.** `deepseek-account` is the account product feature: browser sign-in, the stored grant, profile, balance, notifications, and the Platform session, of which releasing a request credential is a small part. The API key has no such feature. It is a named string in the generic credential store, and its DeepSeek-specific logic is the key source inside the service. A package becomes worthwhile when DeepSeek-specific key behavior appears, such as a balance per key, server-side validation, or several keys. + +**Merging the two model route plugins, or their route ids.** They are two model providers with different settings and catalog sources, the `ACCOUNT_*` failure mapping, and the sign-out policy over running tasks. The route id is the durable record of how a conversation is billed: Session logs carry it, and sign-out cancellation and `auto` billing read it. + +**A fixed table of the two DeepSeek route ids in the service.** `routeKind()` would answer for `deepseek-account` and `deepseek-official` whichever plugins are mounted, and a conversation recorded on the account route would try only the API key while the account route plugin is not mounted. The table would put the route ids of two consumers into the service those consumers depend on. Each route plugin passes its own id when it connects, and a route id whose plugin is not mounted is ordered as any other route. + +**Route plugins that work without the service.** An optional service would leave compositions and tests that mount a route by hand unchanged, but each route would keep a credential path that bypasses the service. + +**One billing order for every consumer.** Messages search outside an account conversation never tries the sign-in. Giving it the general order would change which credential existing conversations send, so the rule stays. + +**A credential fingerprint in the authorization.** Consumers only send requests, so they need headers; 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 sign-in without a connected account route.** Routing that default 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 + +A consumer of another DeepSeek API declares the kinds that API accepts; it reads no credential, renders no header, and holds no fallback. When an API gains a kind, its consumer widens `accepts`. A new credential kind is a source in the service and a member of `DeepSeekAuthKind`. The transport, the model service, the web providers, and the account service do not depend on one another for credentials, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. The `llm-deepseek` credential helpers and the route plugins' config exports do not exist; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.md) lists the replacements. + +Every composition that mounts a DeepSeek model route or a DeepSeek web provider mounts the service; without it those plugins wait and register nothing. The `base` and `sdk-minimal` bundles carry its row, and the SDK server mounts it with its fallback route when the composition has none. One deployment per kind means a second `connect()` of a kind throws `DUPLICATE_CONNECTION`. `auto` billing recognizes a route only while the plugin that registers it is connected: a conversation recorded on `deepseek-account` or `deepseek-official` whose plugin is not mounted, and a DeepSeek model reached through another provider plugin, are ordered as any other route, so their Search and Fetch operations send the API key and, without a key, the account sign-in. A route's configuration failure reaches consumers as an unresolved candidate: the Search and Fetch APIs report it as `WEB_PROVIDER_MISCONFIGURED`, Messages search as `WEB_PROVIDER_ERROR`, and neither tries a later credential. An unusable key reaches a web tool's result under the error name `DeepSeekAuthError`. + +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. diff --git a/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.zh.md b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.zh.md new file mode 100644 index 0000000000..4f50ab93de --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.zh.md @@ -0,0 +1,73 @@ +# Agent Note: DeepSeek request authentication - one service releases the API key or the account sign-in to every DeepSeek consumer + +Status: implemented + +[English](2026-11-10-deepseek-request-authentication.md) | 中文 + +## 问题 + +DeepSeek 的 API 接受两种凭据:API 密钥和账号登录。每个 API 接受其中一种或两种:每条模型路由的 Messages、Files 和模型列表请求只带一种,Search 与 Fetch 两种都接受,DeepSeek 还在逐个为其他 API 增加账号鉴权。在两种凭据之间做选择这件事没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,按自己的计费设置排定两种凭据的顺序,并自己组装请求头;Messages 搜索则硬编码账号路由 id,并使用自己的一套顺序。因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader,而其他 DeepSeek API 的消费方还得把选择凭据、绑定部署、组装请求头和作废凭据再做一遍。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。 + +## 决策 + +位于 `packages/account/` 组的 `@deepseek-ai/dsh-deepseek-auth` 提供 `ctx.deepseekAuth`。该包同时承担 DeepSeek 请求鉴权的 Service Definition 和 Service Provider,每个调用 DeepSeek API 的插件都是 Consumer。消费方描述一次请求:它的 API 接受的凭据种类 `accepts`、其设置选择的计费方式 `billing`、会话的模型路由 `route`,以及目的地 `destination`,即所选种类的部署之下的一个路径,或一个绝对 URL。`candidates(request)` 按计费顺序返回各个种类,每个种类都绑定到其凭据发往的端点,且不读取任何凭据。`authorize(request, signal)` 把第一个持有凭据的种类释放为 `DeepSeekAuthorization`:`kind`、`endpoint`、请求 `headers`、供诊断使用的密钥 `reference`,账号登录还带有用于 HTTP 401 的 `reject()` 和在账号退登时中止的 `revoked` 信号。授权不携带裸的凭据值:消费方通过 `apiKeyHeaders` 指定 API 密钥放进哪些请求头,账号登录的请求头由账号服务决定。 + +计费顺序由该服务拥有。`api-key` 与 `account` 计费只尝试对应的那一种。`auto` 跟随会话:在某个插件为账号登录登记的路由上先尝试账号登录、再尝试 API 密钥;在某个插件为 API 密钥登记的路由上只尝试 API 密钥;在其他路由上或不在会话中时,先尝试 API 密钥、再尝试账号登录。该服务自身不写任何路由 id:每个模型路由插件在登记时传入它注册的提供方路由,`routeKind(route)` 回答在该 id 下登记的种类。记录在 `deepseek-account` 或 `deepseek-official` 上的会话,在对应插件未挂载时按其他路由处理。不在 `accepts` 中的种类永远不会成为候选。 + +每个种类同一时间只有一个部署。模型路由插件在 `ctx.effect()` 内用 `connect(kind, route, connection)` 登记自己的提供方路由及其设置所指的部署,服务为每个请求调用 `connection`。没有登记时,API 密钥是发往 `https://api.deepseek.com` 的 `DEEPSEEK_API_KEY`,账号登录发往 `DEEPSEEK_BASE_URL` 所指的 origin,默认为官方 API。凭据只释放给其种类的部署 origin 之下且不内嵌凭据的目的地。请求可以在 `connections` 里携带某一种类自己的连接,它取代已登记的或默认的连接:模型路由传入它为一次模型请求捕获的那一代配置,拥有自己端点和密钥的消费方传入这两项。连接无法解析的种类作为未解析条目留在候选中,`authorize()` 在此以 `UNRESOLVED_CONNECTION` 停止,不再尝试后面的种类。 + +API 密钥通过 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境。`dsh-credentials` 还拥有 `normalizeApiKey`,即 Host 端对“能放进 HTTP 请求头的密钥”的定义:它回答去掉首尾空白后的密钥,或密钥不可用的原因,不生成任何诊断文案。该服务为不可用的密钥写出诊断文案,并将其报告为代码 `INVALID_CREDENTIAL` 的 `DeepSeekAuthError`,`llm-pi-ai` 写出自己的文案并报告为 `LlmError`,`@deepseek-ai/dsh-llm` 既不带凭据接口也不带密钥检查。账号登录就是 `ctx.deepseekAccount.resolveRequestCredential(endpoint)` 释放的凭据;组合中没有账号服务时不存在这种凭据。 + +`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回请求头、可选的 `revoked` 信号和可选的失败回调,或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。传输层让每次模型请求及其文件操作受 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。 + +路由插件是同时登记自身部署的消费方,二者都要求该服务已挂载。`llm-deepseek-api-key` 在自己的路由 id 下登记其基础地址、`apiKeyEnv` 引用,以及作为密钥诊断所指属主的设置命名空间;它以 `accepts: ['api-key']` 索取放在 `x-api-key` 里的密钥,并把不可用的密钥报告为自己的 `INVALID_CREDENTIAL`。`llm-deepseek-account` 在自己的路由 id 下登记其基础地址,以 `accepts: ['account']` 索取凭据,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。 + +`@deepseek-ai/dsh-deepseek-account` 向鉴权服务释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、`reject()` 和 `revoked` 信号;`reject()` 仅在已存储的授权记录仍一致时删除它并隔离存储失败,`revoked` 由账号服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。账号服务不检查任何 Agent,也不依赖 `dsh-agent`、`dsh-llm` 或鉴权服务。包以不变的名字位于 `packages/account/` 组。 + +Web 提供方声明各自的 API 接受什么。`web-deepseek-api` 以 `accepts: ['account', 'api-key']`、该能力的计费设置、会话的路由,以及路径 `/v1/tools/search` 或 `/v1/tools/fetch` 索取候选;设置了自己的 `*BaseURL` 或 `*ApiKeyEnv` 的能力以 `accepts: ['api-key']` 和自己的连接索取,因此发往该端点的只有那把密钥。`web-search-deepseek` 把搜索端点作为绝对目的地传入,把它引用的密钥作为自己的连接传入。在已登记的账号路由上的会话里,它以 `auto` 计费索取,因此当搜索端点位于账号部署的 origin 之下时先尝试账号登录;其他搜索都以 `api-key` 计费索取。字面 `apiKey` 是该提供方自己的凭据:有它时提供方只索取账号登录,服务不释放任何凭据时发送字面密钥。`web-deepseek-api` 依据候选来措辞凭据缺失和设置无法解析的失败。两个 Web 消费方都隔离失败的 `reject()` 以保证报告的是 HTTP 拒绝,都让请求受授权的 `revoked` 信号约束,并把被该信号结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不依赖 `llm-deepseek`、路由插件、Loader 或账号服务,也都不经 `dsh-llm` 读取凭据:`web-search-deepseek` 不依赖它,`web-deepseek-api` 只从它导入消息文本辅助函数 `extractTextContent`。 + +## 考虑过的替代方案 + +**通过模型服务发布每条路由的凭据。** `dsh-llm` 上的 `LlmAdapter.providerCredential(provider)` 回答一条路由的凭据种类、基础地址和面向某个端点的授权,消费方读取 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')`。按模型路由查询意味着每个消费方都要自己按计费排定两种凭据的顺序、自己用裸值组装请求头,并在路由未挂载时自己回退。模型协议之外的 API,例如 `/v1/tools/` 下的语音和文档 API,既没有可以询问的路由,也没有地方声明它接受哪些种类。模型服务还要带上一个凭据接口,而它只有 DeepSeek 适配器一个发布方和两个 Web 消费方。 + +**在上述发布之上用公共库代替服务。** 模型路由与其他消费方通过同一个操作鉴权,而读取路由所发布内容的库无法反过来为路由本身服务。 + +**通过 `dsh-llm` 检查密钥、在服务里保留一份副本,或由每个消费方传入校验函数。** 所有 DeepSeek 消费方共用的服务不能依赖模型服务,后者只是其中一类消费方的依赖。Host 端的第二份规则只能靠注释与第一份以及浏览器端的那份保持一致。校验函数参数会让每个接受密钥的消费方都传一个,两个 Web 包也要为此继续依赖 `dsh-llm`。检查放在读取密钥的那一层 `dsh-credentials`,每个调用方依据检查返回的原因写出自己的失败。 + +**把不可用密钥的诊断文案放在 `dsh-credentials`。** 那里的一个函数能让该服务和 `llm-pi-ai` 使用同样的措辞。但文案要告诉用户在 Models 页面设置该引用,存储凭据的包就会写出其消费方的页面。两个调用方各自写出文案,凭据存储不写任何消费方的名字。 + +**让 `dsh-llm` 从 `dsh-credentials` 导入密钥检查。** 模型服务里没有任何代码读取密钥。该检查在其中唯一的调用方是 `llm-pi-ai`,而它已经依赖 `dsh-credentials`,因此模型服务不导出密钥检查,也不新增依赖。 + +**在 `deepseek-account` 旁边设一个 `deepseek-api-key` 包。** `deepseek-account` 是账号这项产品功能:浏览器登录、已存储的授权、资料、余额、通知和 Platform 会话,释放请求凭据只占其中一小部分。API 密钥没有这样的功能。它是通用凭据库里一个有名字的字符串,它的 DeepSeek 专属逻辑就是服务内部的密钥来源。等到出现 DeepSeek 专属的密钥行为,例如按密钥查余额、向服务端校验或多把密钥,才值得拆出一个包。 + +**合并两个模型路由插件,或合并它们的路由 id。** 它们是两个模型提供方,设置和目录来源不同,还各有 `ACCOUNT_*` 失败映射和针对运行中任务的退登策略。路由 id 是一段会话如何计费的持久记录:会话日志携带它,退登取消和 `auto` 计费读取它。 + +**在服务里放一张含两个 DeepSeek 路由 id 的固定表。** 无论挂载了哪些插件,`routeKind()` 都会为 `deepseek-account` 和 `deepseek-official` 作答,记录在账号路由上的会话在账号路由插件未挂载时只尝试 API 密钥。这张表会把两个消费方的路由 id 写进它们所依赖的服务。每个路由插件在登记时传入自己的 id,插件未挂载的路由 id 按其他路由处理。 + +**让路由插件在没有该服务时也能工作。** 把服务做成可选依赖可以让手工挂载路由的组合和测试保持不变,但每条路由都要保留一条绕过该服务的取凭据路径。 + +**让所有消费方使用同一套计费顺序。** Messages 搜索在账号会话之外从不尝试账号登录。让它采用通用顺序会改变现有会话发送的凭据,因此这条规则保留。 + +**在授权中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。 + +**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。 + +**没有登记账号路由时,账号登录使用账号服务的推理 origin。** 让该默认值经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。 + +**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。 + +**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。 + +**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。 + +**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。 + +**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。 + +## 后果 + +其他 DeepSeek API 的消费方只声明该 API 接受的种类;它不读取凭据、不组装请求头,也不保留回退逻辑。某个 API 新增一种凭据时,它的消费方扩充 `accepts`。新增凭据种类意味着在服务里加一个来源,并为 `DeepSeekAuthKind` 加一个成员。传输层、模型服务、Web 提供方和账号服务在凭据上互不依赖,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。`llm-deepseek` 的凭据辅助函数和路由插件的配置导出不复存在;[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.zh.md)列出了替代方案。 + +凡是挂载 DeepSeek 模型路由或 DeepSeek Web 提供方的组合都要挂载该服务;没有它时这些插件一直等待,不注册任何东西。`base` 和 `sdk-minimal` 两个组合包带有它的条目,SDK 服务端在组合里没有它时随后备路由一起挂载它。每个种类一个部署意味着对同一种类第二次 `connect()` 会抛出 `DUPLICATE_CONNECTION`。`auto` 计费只在注册某条路由的插件已登记时才认它:记录在 `deepseek-account` 或 `deepseek-official` 上而对应插件未挂载的会话,以及经由其他提供方插件访问的 DeepSeek 模型,都按其他路由处理,因此它们的 Search 与 Fetch 操作发送 API 密钥,没有密钥时发送账号登录。路由的配置失败以未解析候选的形式到达消费方:Search 与 Fetch API 将其报告为 `WEB_PROVIDER_MISCONFIGURED`,Messages 搜索报告为 `WEB_PROVIDER_ERROR`,二者都不再尝试后面的凭据。不可用的密钥在 Web 工具的结果里以错误名 `DeepSeekAuthError` 出现。 + +退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。 diff --git a/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.i18n.yaml new file mode 100644 index 0000000000..5a5d96d0a1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md new file mode 100644 index 0000000000..cb9f11e50f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.zh.md b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.zh.md new file mode 100644 index 0000000000..f38b8d0bfb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.zh.md @@ -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 数据的要求。只有捕获输出和诊断文本可以缩短。 + +## 后果 + +成功但输出截断的执行仍是成功工具结果。调用方读取当前状态以获取遗漏信息,不重放已完成动作。输出抑制不限制参数求值或原生代码中的分配,这仍由现有资源控制负责。测试覆盖后续动作、保留变量、初始化、有序图片、字节上限以及后续异常、截止到期和取消。 diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml new file mode 100644 index 0000000000..aad42e312a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml @@ -0,0 +1,46 @@ +# Bilingual-pair consistency record for 2026-11-15-client-config-sync.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-15-client-config-sync.md +/agent-note-browser-plugin-configuration-sync: + en: 92fb1b35ccd50f2b + zh: 732f665dd12d0feb +/agent-note-browser-plugin-configuration-sync/problem: + en: bad5854f1a21feb2 + zh: df9f2c62aa7f1c8c +/agent-note-browser-plugin-configuration-sync/decision: + en: a15c7c13f167e5ac + zh: a15c7c13f167e5ac +/agent-note-browser-plugin-configuration-sync/decision/design-principles: + en: 1678ec9cbc83e49e + zh: 1548e5e08774de78 +/agent-note-browser-plugin-configuration-sync/decision/plugin-authoring: + en: 201c029071cc3812 + zh: 03a7245772a95b54 +/agent-note-browser-plugin-configuration-sync/decision/ownership: + en: cb3e66c7d61b706b + zh: a255f85e9c411db9 +/agent-note-browser-plugin-configuration-sync/decision/ordering: + en: 5de9319764101262 + zh: 4a5c5c417cf36d8e +/agent-note-browser-plugin-configuration-sync/decision/push-order: + en: 5714f023a439e068 + zh: 5d5ec5d5847fb2d4 +/agent-note-browser-plugin-configuration-sync/decision/delivery: + en: 9b8e644702108ef6 + zh: 0d4f551c6007e989 +/agent-note-browser-plugin-configuration-sync/decision/push-channel: + en: 5596a32a26042882 + zh: fbeae944656b39ac +/agent-note-browser-plugin-configuration-sync/decision/scope-existing-uses-the-mechanism-can-absorb: + en: 79b8c68583897e07 + zh: 15a0f33fa494ec9a +/agent-note-browser-plugin-configuration-sync/verification: + en: b7ab56a86ef63b85 + zh: b5fc8aae610659fc +/agent-note-browser-plugin-configuration-sync/alternatives-considered: + en: 15ae5cd610d7208c + zh: 5f25271e318dbfe1 +/agent-note-browser-plugin-configuration-sync/consequences: + en: f85e3339246a9f84 + zh: 11cbff9deeb78f88 diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md new file mode 100644 index 0000000000..5282c80450 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md @@ -0,0 +1,215 @@ +# Agent Note: Browser plugin configuration sync + +Status: implemented + +English | [中文](2026-11-15-client-config-sync.zh.md) + +## Problem + +Host plugin configuration updates live: when only volatile fields change, the Loader commits the references in place and emits `loader/volatile-update` without remounting the plugin. The browser has no matching path: + +| Symptom | Cause | +|---|---| +| A browser plugin's `apply(ctx, config)` always receives an empty config | The page Loader creates entries with `name` only ([entries.ts](../../../../packages/client/modules/src/client/entries.ts)), so the row's `config` in cordis.yml never reaches the browser | +| Packages that need Host configuration each work around it | Some write a page global through `webserver/index-inject`, which takes effect only at page load; others read runtime values through the `configForms` settings mirror | +| The plugin-graph push channel does not meet the rules | `/plugins/events` is an `auth: 'anonymous'` route; the browser has two readers, `EventSource` and `__DSH_TRANSPORT__.fetch`, the latter never reconnects; the frame sequence has no one-complete-snapshot-per-generation rule | + +## Decision + +### Design principles + +| Principle | Content | +|---|---| +| One Config | A plugin has one configuration type, in the package's `src/types.ts`, shared by the Host and Client faces; the schema lives only on the Host face. The browser exports no `Config` and validates no configuration | +| Volatile only | The browser receives only the fields the Host schema declares volatile | +| Secrets removed | `role('secret')` positions inside volatile fields, including inside volatile objects, arrays, and dictionaries, are removed on the Host and never sent. The Host face of `client/modules` implements this itself, without depending on `@deepseek-ai/dsh-settings` | +| Plugins support live updates | A synced configuration change never remounts a browser plugin; the plugin reads references at operation time, or hands them to components as observable sources | +| Equal values do nothing | Every layer compares with deep equality; equal values push, write, and notify nothing, and a reconnect snapshot equal to the current values causes no refresh | +| What is not synced | Host-only ordinary fields, secrets, and per-browser preferences stay out of this path; values the page HTML pre-injects to avoid a first-paint flash, such as the theme, stay as they are | + +### Plugin authoring + +```ts ignore-check +// src/types.ts — shared by both faces; types only +import type { Volatile } from '@deepseek-ai/cordis' + +/** Plugin configuration shared by the Host and Client faces. */ +export interface Config { + /** Host-only ordinary field; never synced. */ + cacheDir: string + /** Synced to the browser. */ + interactiveByDefault: Volatile + /** Synced as one value. */ + office: Volatile<{ maxBytes: number }> + /** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */ + apiKey?: Volatile +} +``` + +```ts ignore-check +// src/index.ts — Host face; the only schema +export const Config: z = z.object({ + cacheDir: z.string().default('.cache'), + interactiveByDefault: z.boolean().default(false).volatile(), + office: z.object({ maxBytes: z.natural().default(8 << 20) }).volatile(), + apiKey: z.string().role('secret').volatile(), +}) +``` + +```ts ignore-check +// src/client/index.ts — Client face; no Config export +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { Config } from '../types.ts' + +export function apply(ctx: Context, config: SyncedConfig): void { + // Every synced field may read undefined; the plugin decides what an absent value means. + const tooLarge = (bytes: number) => bytes > (config.office.get()?.maxBytes ?? Number.POSITIVE_INFINITY) + ctx.slots.register({ + name: 'demo.body', + inject: (): DemoBodyInjected => ({ hooks: { interactiveByDefault: config.interactiveByDefault }, tooLarge }), + }, DemoBody) +} +``` + +```tsx ignore-check +// src/client/DemoBody.tsx — the renderer binds the injected source as useInteractiveByDefault +export function DemoBody({ useInteractiveByDefault, tooLarge }: InjectFace) { + const interactive = useInteractiveByDefault(value => value) + // ... +} +``` + +Types exported by the types-only package `@deepseek-ai/dsh-client-config/types`, which plugins depend on instead of the bootstrap Client Modules package; Client Modules implements them: + +```ts ignore-check +/** One synced field: Host-aligned `get()`, and directly an observable source for an injected hook. */ +export interface SyncedConfigRef extends Volatile, ObservableSnapshot> {} + +/** The Volatile fields of the shared Config type. */ +export type SyncedConfig = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : never +} +``` + +`get` and `getSnapshot` return the same frozen snapshot: `get` matches how the Host reads a volatile reference, and `getSnapshot` with `subscribe` satisfy `ObservableSnapshot`, so the reference itself goes into `hooks` without renderer adaptation. The interface has no write operation; the implementing class stays private to Client Modules. + +Components follow the [client rules](../../../../packages/client/AGENTS.md): the plugin injects field-level sources in a slot inject's `hooks` compartment, and the component reads them only through the renderer-bound `use`, never touching the source. + +### Ownership + +Runtime ownership stays in `client/modules`; the only new package is the types-only `@deepseek-ai/dsh-client-config` (empty `apply` on both faces). `client/modules` already follows Loader entries, composes the plugin graph, and creates entries in the browser; synced configuration is an input of an entry, so it owns this too: + +| Face | Responsibility | +|---|---| +| Host (inside the `clientModules` service) | Listens to `loader/volatile-update` on each graph row's own plugin `ctx`; recomputes after the plugin fiber becomes ACTIVE (`internal/status`) or after entry reconciliation; reads the schema's top-level volatile field values from `fiber.effectiveConfig`, removes `role('secret')` positions by the schema, and compares the row's values with the last ones by deep equality, writing them into the graph row's `config` and republishing the graph only when they differ. A change of synced values alone rebuilds no combo artifact | +| Client (inside the entry controller) | Keeps the latest synced values of every package that has appeared in the graph; each plugin activation receives a new configuration object (an empty object while the row has no values), as each Host fiber activation resolves new references; on each graph it compares fields as JSON and writes the changes into the current activation's object | +| Client (`ctx.config` service) | Read-only: `resolveConfigByPackage(packageName)` returns the object a package's current activation received, for reading another plugin's configuration; the object changes when the plugin is replaced, and the result is `undefined` while no activation runs | + +Client constraints: + +| Constraint | Content | +|---|---| +| Lazy creation | A field reference is created on first access and cached | +| Instance identity | One object per activation, living as long as that activation; code replacement and a re-added row each produce a new object holding the latest values | +| No `entry.update` | Synced configuration never takes the Loader update path, so it never triggers a remount, and the browser emits no `loader/volatile-update`; changes notify only through the field references' `subscribe` | +| Atomic publication | One graph update sets every changed field before notifying their subscribers, as the Host commits every reference before emitting its event | +| No value validation | The authoritative Host schema has already validated the values; the browser checks only that a row's `config` is an object when it parses the graph | +| Delivery | The entry controller registers a prepended `internal/config` listener on the page Loader that returns the synced object for managed entries that export no schema; the Loader's interpolation runs inside it and cannot copy the object. A Client face that exports its own `Config` schema keeps Cordis's ordinary configuration, and fails to activate if its row also carries synced values | + +### Ordering + +Host consistency comes from two facts: the schema and the code belong to one module, and activation resolves the raw configuration with that schema; code reloads and configuration reloads run serially through Host hot reload, and only an ACTIVE instance receives volatile changes in place. The Client aligns with the second: + +| Situation | Host | Client | +|---|---|---| +| Configuration changes while the instance runs | Commits every reference in place, then notifies | Writes into the current activation's object in place, notifying after every field is written | +| Configuration changes while a replacement is queued and teardown has not begun | The instance is still ACTIVE and updates in place | Same | +| Configuration changes after teardown begins | A non-ACTIVE instance no longer updates in place; the new instance resolves the latest configuration | Teardown releases the old activation, whose object receives no further writes; the new activation starts with the latest values | +| The row is removed | The instance is destroyed and receives no configuration | Removal releases the activation; nothing is written while the row is absent from the graph | +| The Host-side plugin instance is not ACTIVE | Not applicable | Values follow the Host's configuration as the Host plugin's own effective Config does, including when activation fails; an instance that has not activated yet publishes the values its own schema resolves from its raw configuration | + +A plugin instance that has not activated yet (a new install, an upgrade, a code reload) publishes the values its own schema resolves from its raw configuration, so the graph frame that announces new browser code already carries values of the matching Host schema. Only an incompatible schema change during development (a renamed or removed field) can briefly give old browser code values it does not expect, until the rebuilt bundle arrives. + +### Push order + +When a Host plugin updates its configuration and then pushes other data to the browser, the browser should receive the configuration first. The order is ensured only at the mechanism level, through the steps below; it is not guaranteed in practice. Each stream's source takes its own number of asynchronous steps between a Host event and the item reaching the Gateway write queue, so a stream with fewer steps can be written first even when no plugin adds a wait of its own. Plugins must not rely on this order: + +| Step | Approach | +|---|---| +| Host enqueue | `clientModules` registers its `loader/volatile-update` listener on the plugin ctx with prepend, so it puts the new graph into every follower queue synchronously before the plugin's own listeners run | +| pluginEvents stream | `follow` yields increments from its own generator, with no delegated generator adding a step | +| Gateway write | Each connection has one write queue; each stream's items enter it when the source produces them and are written in queue order, without waiting for the previous write to complete; when the queued bytes exceed `streamOutboxBytes`, the whole connection pauses reading every source | +| Browser handling | WebSocket messages are handled in arrival order, and configuration writes complete synchronously while a graph frame is handled | + +### Delivery + +First-render values travel in the `__DSH_BOOT__` graph rows; later values travel in the plugin-events stream's `baseline` and `graph` frames, with no separate configuration frame. `@deepseek-ai/dsh-client-modules/types` exports the plugin graph's wire types. Only the owner receives configured values; every other Peer, such as a LiveShare viewer, receives in the boot graph and in every plugin-events frame the values each plugin's schema resolves from an empty Config, so the Host schema remains the only source of defaults and the owner's configured values stay on the Host; a row whose schema rejects an empty Config carries no values there. Remote access policies decide only whether a Peer may follow the graph. + +### Push channel + +`/plugins/events` becomes the authenticated Typert Remote stream `pluginEvents/follow`, which the browser consumes with `RemoteSnapshotStream`: + +| Frame | Content | Browser handling | +|---|---|---| +| `baseline` | The complete plugin graph, including each row's synced configuration | Entry reconciliation | +| `graph` | The complete plugin graph after a structural or synced-configuration change | Entry reconciliation | +| `rebuilt` | `{ id, rev }`, one package's code rebuild | Entry code replacement | + +| Item | Content | +|---|---| +| Authentication | Ordinary Remote gateway authentication and authorization; the anonymous `/plugins/events` route is removed, and the browser face opens the stream while Remote access allows `pluginEvents/follow` | +| Transport | Both the `EventSource` and the `__DSH_TRANSPORT__.fetch` readers are removed; shells such as liveshare and webworker connect through the Remote carrier Connection already provides | +| Reconnection | `RemoteStream` owns it; every generation starts with `baseline`, and the new snapshot covers anything missed while disconnected | +| Desktop | Shares the same Remote stream with Web | +| Ownership | The `client/hmr` Host face owns the `pluginEvents` Remote service, in the same package as the bundle stat poll, and declares no `ctx` type merge; `client/modules` is a zero-dependency bootstrap package and takes no typert or gateway dependency | +| Browser dependencies | The browser face `$mount`s its own generated `pluginEvents` namespace rather than through the `api-remotes` assembly, so `api-remotes` can be hot-replaced independently; the required dependencies are `modules`, `remote` (the gateway Client face, over Connection), and `remoteAccess` | + +### Scope: existing uses the mechanism can absorb + +This Note migrates no existing use; the [migration Note](../../proposed/architecture/2026-11-15-client-config-sync-migration.md) owns the inventory and order. The mechanism can absorb page globals that deliver Host configuration through `webserver/index-inject`, plugins that read runtime values through `configForms`, and `Config` schemas declared only on a Client face that nothing can configure. + +## Verification + +The following hold and are covered by tests: + +- A browser plugin's `apply` `config` holds the Host's current volatile values on first render; after a volatile field in `cordis.patch.yml` changes, the browser reference updates and subscribed components re-render, with neither the browser nor the Host plugin fiber remounted. +- `role('secret')` values in the positions the projection removes, the same as the settings redaction, appear neither in the first-render injection nor in any pushed frame; a non-owner Peer receives only schema defaults, never configured values. +- Host-only ordinary fields never appear in the browser. +- A configuration reload with unchanged values, and the reconnect baseline after a Host restart, emit no `loader/volatile-update` and notify no subscriber. +- No anonymous `/plugins/events` route exists; an unauthenticated request cannot obtain the plugin graph or configuration; after reconnection the browser state matches the Host. +- After code hot reload the new activation receives a new `SyncedConfig` object holding the current values, and the old activation receives no new values once its teardown begins. +- On the Host, the new graph frame enters the pluginEvents follower queues before the plugin's own `loader/volatile-update` listeners run; the order on the wire is not required. +- Tests: unit tests for both faces of `client/modules` (removal, comparison, lazy creation, reference stability, listener registration and removal); a real composition test that boots a profile through the Loader, changes a patch, and asserts browser-visible values; the `client-plugin-live` and `client-config-sync` Web end-to-end tests, including reconnection after a transport restart. + +## Alternatives considered + +| Rejected | Reason | +|---|---| +| A separate browser `ClientConfig` schema | Two schemas drift; the Host schema already carries volatile declarations and validation | +| Sending the whole configuration with secrets removed | Leaks ordinary fields such as Host paths and URLs to the browser | +| Applying changes to browser entries through `entry.update({ config })` | The browser has no schema, so the Loader cannot tell volatile fields and only remounts | +| Changing the vendored Loader to add a global volatile event | Requires a logged vendor modification; listening on each entry's own `ctx` suffices | +| Placing the channel in `client/modules` | The bootstrap package would depend on typert and the gateway | +| Mounting `pluginEvents` through `api-remotes` | A failed `api-remotes` replacement would cut the plugin update channel | +| Declaring "replacement requires a page reload" for Connection and the gateway | Adds a manifest field and a UI branch; a page reload after a failed replacement is accepted | +| A unified `useConfig` framework hook in the renderer | Adds a framework-level hook; manual `hooks` injection already serves components | +| Reusing the projection and removal functions of `@deepseek-ai/dsh-settings` | The settings architecture will be adjusted after this mechanism, so no dependency yet | +| References that are only `ObservableSnapshot` | Inconsistent with the Host's `get()` on volatile references | +| One page-lifetime configuration object per package | An old instance being torn down during replacement would still receive new configuration, unlike the Host | +| Changing the vendored Loader to emit a commit event for Host enqueue order | A prepended listener already suffices, with no vendor change | +| A separate push channel for configuration | Duplicates the plugin-graph channel's authentication, reconnection, and snapshot semantics | +| A separate `client/config` runtime package with a publicly writable configuration service | Any plugin could rewrite another plugin's configuration, and entries would have to wait for that service by package name | +| Plugins importing the types from `@deepseek-ai/dsh-client-modules/types` | Couples every configured plugin to the bootstrap module-system package and exposes the implementing class | +| Emitting `loader/volatile-update` in the browser too | The field references' `subscribe` suffices; the event requires reaching into Cordis's filter mechanism | + +## Consequences + +| Risk | Description | +|---|---| +| The channel depends on Connection | Plugin-graph sync depends on Connection and the gateway Client face. Hot-replacing them restarts this plugin and reopens the stream, reconciled by the new generation's baseline; if their new code fails to import or activate, the page receives no plugin updates until it reloads (accepted) | +| Listeners registered on other plugins' `ctx` | The Host face registers on tracked entries' `ctx`; `clientModules` must withdraw every listener when it unloads | +| Self-built references | Client references implement `Volatile` structurally without Cosmokit's internal write protocol, so `isVolatile` does not recognize them | +| Empty configuration objects | Browser plugins without synced fields also receive an empty read-only object as `config` | +| Push order not guaranteed | The configuration-first order holds only when every stream takes the same asynchronous steps from a Host event to the Gateway write queue; streams written in other ways, with or without waits of their own, may be written first | +| Every field may be absent | Each `SyncedConfig` field reads `V \| undefined`: secrets, unprojectable values, and Host values not yet matching the browser code are absent, so plugins handle the absent value at each read | diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md new file mode 100644 index 0000000000..4afa3940b9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md @@ -0,0 +1,215 @@ +# Agent Note: 前端插件配置同步 + +Status: implemented + +[English](2026-11-15-client-config-sync.md) | 中文 + +## Problem + +Host 上的插件配置可以实时更新:Loader 在只有 volatile 字段变化时原地提交引用并发出 `loader/volatile-update`,不重新挂载插件。浏览器侧没有对应链路: + +| 现象 | 原因 | +|---|---| +| 前端插件的 `apply(ctx, config)` 总是拿到空配置 | 页面 Loader 创建条目时只传 `name`([entries.ts](../../../../packages/client/modules/src/client/entries.ts)),cordis.yml 中该行的 `config` 不会到达浏览器 | +| 需要 Host 配置的包各自绕路 | 有的经 `webserver/index-inject` 写页面全局变量,只在页面加载时生效;有的借 `configForms` 设置镜像读取运行时值 | +| 插件图推送通道不合规 | `/plugins/events` 是 `auth: 'anonymous'` 路由;浏览器有 `EventSource` 和 `__DSH_TRANSPORT__.fetch` 两套读取实现,后者断开后不重连;帧序列没有「每代一份完整快照」约束 | + +## Decision + +### 设计原则 + +| 原则 | 内容 | +|---|---| +| 一套 Config | 插件只有一份配置类型,放在包的 `src/types.ts` 并由 Host 与 Client 两面共用;schema 只在 Host 面。浏览器不导出 `Config`,也不做配置校验 | +| 只同步 volatile | 浏览器只接收 Host schema 中声明为 volatile 的字段 | +| 剔除密钥 | volatile 字段内的 `role('secret')` 字段(包括 volatile 对象、数组、字典内部)在 Host 上剔除,不下发。该逻辑在 `client/modules` Host 面独立实现,不依赖 `@deepseek-ai/dsh-settings` | +| 插件自身支持热更新 | 同步配置的变化永远不重新挂载前端插件;插件在操作时读取引用,或把引用作为可订阅数据源交给组件 | +| 相等即无事 | 每层都按 deep equal 比较,值相等时不推送、不写入、不通知;重连收到的完整快照与当前值相等时不产生任何刷新 | +| 不同步的内容 | Host 专用普通字段、密钥、按浏览器区分的偏好不进入此链路;主题等在页面 HTML 预注入以避免首屏闪烁的值保持原状 | + +### 插件写法 + +```ts ignore-check +// src/types.ts — shared by both faces; types only +import type { Volatile } from '@deepseek-ai/cordis' + +/** Plugin configuration shared by the Host and Client faces. */ +export interface Config { + /** Host-only ordinary field; never synced. */ + cacheDir: string + /** Synced to the browser. */ + interactiveByDefault: Volatile + /** Synced as one value. */ + office: Volatile<{ maxBytes: number }> + /** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */ + apiKey?: Volatile +} +``` + +```ts ignore-check +// src/index.ts — Host face; the only schema +export const Config: z = z.object({ + cacheDir: z.string().default('.cache'), + interactiveByDefault: z.boolean().default(false).volatile(), + office: z.object({ maxBytes: z.natural().default(8 << 20) }).volatile(), + apiKey: z.string().role('secret').volatile(), +}) +``` + +```ts ignore-check +// src/client/index.ts — Client face; no Config export +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { Config } from '../types.ts' + +export function apply(ctx: Context, config: SyncedConfig): void { + // Every synced field may read undefined; the plugin decides what an absent value means. + const tooLarge = (bytes: number) => bytes > (config.office.get()?.maxBytes ?? Number.POSITIVE_INFINITY) + ctx.slots.register({ + name: 'demo.body', + inject: (): DemoBodyInjected => ({ hooks: { interactiveByDefault: config.interactiveByDefault }, tooLarge }), + }, DemoBody) +} +``` + +```tsx ignore-check +// src/client/DemoBody.tsx — the renderer binds the injected source as useInteractiveByDefault +export function DemoBody({ useInteractiveByDefault, tooLarge }: InjectFace) { + const interactive = useInteractiveByDefault(value => value) + // ... +} +``` + +只放类型的包 `@deepseek-ai/dsh-client-config/types` 导出的类型;插件依赖它而不依赖启动最早的 Client Modules 包,由 Client Modules 实现: + +```ts ignore-check +/** One synced field: Host-aligned `get()`, and directly an observable source for an injected hook. */ +export interface SyncedConfigRef extends Volatile, ObservableSnapshot> {} + +/** The Volatile fields of the shared Config type. */ +export type SyncedConfig = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : never +} +``` + +`get` 与 `getSnapshot` 返回同一个冻结快照:`get` 与 Host 的 volatile 引用写法一致,`getSnapshot` 与 `subscribe` 满足 `ObservableSnapshot`,引用本身即可放进 `hooks`,renderer 不需要额外适配。接口没有写操作;实现类只在 Client Modules 内部。 + +组件取值遵循 [client 规则](../../../../packages/client/AGENTS.md):插件在 slot inject 的 `hooks` 中手动注入 key 级数据源,组件只通过 renderer 绑定的 `use` 读取,不接触数据源本身。 + +### 归属 + +运行时归属仍在 `client/modules`;唯一新增的包是只放类型的 `@deepseek-ai/dsh-client-config`(两个面的 `apply` 都为空)。`client/modules` 本来就跟踪 Loader 条目、组合插件图并在浏览器创建条目,同步配置是条目的输入,由它一并负责: + +| 面 | 职责 | +|---|---| +| Host(`clientModules` 服务内部) | 在每个图行插件自身的 `ctx` 上监听 `loader/volatile-update`;插件 fiber 进入 ACTIVE(`internal/status`)或条目对账后重算;从 `fiber.effectiveConfig` 读取 schema 顶层 volatile 字段的值,按 schema 剔除 `role('secret')` 位置,得到该行同步值;与上次值 deep equal 比较,不等才写入图行 `config` 并重新发布图。只变化同步值时不重建 combo 产物 | +| Client(条目控制器内部) | 为图中出现过的每个包保存最新同步值;插件每次激活都得到一个新的配置对象(行暂时没有值时是空对象),与 Host fiber 每次激活重新解析出新引用一致;收到图时按字段 JSON 比较,把变化写入当前激活的对象 | +| Client(`ctx.config` 服务) | 只读:`resolveConfigByPackage(packageName)` 返回某个包当前激活收到的对象,供读取其他插件的配置;插件被替换后对象随之改变,没有运行中的激活时返回 `undefined` | + +Client 面的约束: + +| 约束 | 内容 | +|---|---| +| 懒生成 | 字段引用在首次访问时创建并缓存 | +| 实例身份 | 每次激活一个对象,与该激活同寿命;代码替换与行重新加入都产生新对象,持有最新值 | +| 不调用 `entry.update` | 同步配置不经过 Loader 的更新路径,不会触发重挂载,浏览器不发 `loader/volatile-update`;变化只经字段引用的 `subscribe` 通知 | +| 原子发布 | 一次图更新先设置所有变化字段,再通知它们的订阅者,与 Host 先提交全部引用再发事件一致 | +| 不校验值 | 值已由 Host 权威 schema 校验;浏览器只在图解析时校验行 `config` 是对象 | +| 交付方式 | 条目控制器在页面 Loader 上以 prepend 方式注册 `internal/config` 监听,为不导出 schema 的托管条目返回同步对象,Loader 插值在其内层运行,不会复制该对象。导出自身 `Config` schema 的前端面保持 Cordis 原有配置解析;这类前端面的行若同时带同步值,激活失败 | + +### 时序 + +Host 的一致性来自两点:schema 与代码同属一个模块,激活时用该 schema 解析原始配置;代码重载与配置重载由 Host 热重载串行执行,只有 ACTIVE 的实例原地接收 volatile 变化。Client 对齐后一点: + +| 情形 | Host | Client | +|---|---|---| +| 实例运行中,配置变化 | 原地提交全部引用后通知 | 原地写入当前激活的对象,全部写完后通知 | +| 替换已排队、拆除尚未开始时配置变化 | 实例仍 ACTIVE,原地更新 | 同左 | +| 拆除开始后配置变化 | 非 ACTIVE 实例不再原地更新,新实例解析最新配置 | 拆除开始时释放旧激活,旧对象不再写入;新激活以最新值开始 | +| 行被移除 | 实例被销毁,不再收到配置 | 移除时释放激活;行不在图中期间不写入 | +| Host 侧插件实例非 ACTIVE | 不适用 | 同步值与 Host 插件自身的 effective Config 一样跟随 Host 配置,激活失败时也是如此;尚未激活的实例发布其 schema 从原始配置解析出的值 | + +尚未激活的插件实例(新安装、升级、代码热重载)发布用它自己的 schema 从原始配置解析出的值,因此宣布新前端代码的那一帧已带着对应 Host schema 的值。只有开发时不兼容地修改 schema(改名、删字段),才可能在重建的 bundle 到达前,让旧前端代码短暂收到它不认识的值。 + +### 推送顺序 + +Host 插件更新配置后再向浏览器推送其他数据时,浏览器应先收到配置。这一顺序只在机制上通过以下几处保证,实际上不保证:各流的源从 Host 事件到把数据项放入 gateway 写出队列所经过的异步步骤数各不相同,即使插件没有自行插入等待,步骤更少的流也可能先被写出。插件不得依赖这一顺序: + +| 环节 | 做法 | +|---|---| +| Host 入队 | `clientModules` 在插件 ctx 上以 prepend 注册 `loader/volatile-update` 监听,在插件自己的监听之前同步把新图放入各 follower 队列 | +| pluginEvents 流 | `follow` 在自身生成器内产出增量,不经过额外委托的生成器多走一步 | +| gateway 写出 | 每条连接一个写出队列,各流的项在源产出时立即入队并按入队顺序写出,不再逐项等待上一次写入完成;排队字节超过 `streamOutboxBytes` 时整条连接暂停读取所有源 | +| 浏览器处理 | 每条 WebSocket 消息按到达顺序处理,配置写入在图帧处理时同步完成 | + +### 下发 + +首屏值随 `__DSH_BOOT__` 的图行下发;之后随插件事件流的 `baseline` 与 `graph` 帧下发,不另设配置帧。插件图的线类型由 `@deepseek-ai/dsh-client-modules/types` 导出。只有 owner 收到实际配置的值;其他所有 Peer(例如 LiveShare 查看端)在启动图和每个插件事件帧中收到各插件 schema 对空 Config 解析出的值,因此 Host schema 仍是默认值的唯一来源,owner 实际配置的值留在 Host;schema 拒绝空 Config 的行在这类页面上不带值。Remote access 策略只决定 Peer 能否跟随插件图。 + +### 推送通道 + +`/plugins/events` 改为常规鉴权的 Typert Remote 流 `pluginEvents/follow`,浏览器用 `RemoteSnapshotStream` 消费: + +| 帧 | 内容 | 浏览器处理 | +|---|---|---| +| `baseline` | 完整插件图(含各行同步配置) | 条目对账 | +| `graph` | 结构或同步配置变化后的完整插件图 | 条目对账 | +| `rebuilt` | `{ id, rev }`,单包代码重建 | 条目代码替换 | + +| 项 | 内容 | +|---|---| +| 鉴权 | 走 Remote 网关的常规认证与授权,删除匿名 `/plugins/events` 路由;浏览器面在 Remote access 允许 `pluginEvents/follow` 时开流 | +| 传输 | 删除 `EventSource` 与 `__DSH_TRANSPORT__.fetch` 两套实现;liveshare、webworker 等外壳经 connection 已提供的 Remote 载体接入 | +| 重连 | 由 `RemoteStream` 负责;每代先收 `baseline`,断线期间的遗漏由新快照补齐 | +| 桌面端 | 与 Web 共用同一 Remote 流 | +| 归属 | Remote 服务 `pluginEvents` 由 `client/hmr` Host 面持有,与 bundle stat 轮询同包,不声明 `ctx` 类型合并;`client/modules` 是零依赖的 bootstrap 包,不引入 typert 与 gateway 依赖 | +| 浏览器依赖 | 浏览器面自行 `$mount` 本包生成的 `pluginEvents` 命名空间,不经 `api-remotes` 组装,因此 `api-remotes` 可以独立热替换;必需依赖为 `modules`、`remote`(gateway Client 面,其下为 connection)与 `remoteAccess` | + +### 能力边界:可收编的现有用法 + +本 Note 不迁移现有用法;[迁移 Note](../../proposed/architecture/2026-11-15-client-config-sync-migration.zh.md) 负责盘点与顺序。本机制具备收编以下用法的能力:经 `webserver/index-inject` 下发 Host 配置的页面全局变量、以 `configForms` 读取运行时值的插件、只在前端声明而无法配置的 `Config`。 + +## Verification + +以下行为成立并由测试覆盖: + +- 前端插件 `apply` 的 `config` 参数首屏即为 Host 当前 volatile 值;修改 `cordis.patch.yml` 的 volatile 字段后,浏览器中引用值更新、订阅组件重新渲染,前端与 Host 插件 fiber 都不重挂载。 +- 投影剔除的 `role('secret')` 位置(与 settings 的剔除范围相同)不出现在首屏注入和任一推送帧中;非 owner 的 Peer 只收到 schema 默认值,收不到实际配置的值。 +- Host 专用普通字段不出现在浏览器。 +- 值不变的配置重载、Host 重启后的重连 baseline 都不产生 `loader/volatile-update`,也不通知订阅者。 +- `/plugins/events` 匿名路由不存在;未认证请求无法获取插件图或配置;断线重连后浏览器状态与 Host 一致。 +- 代码热重载后新激活拿到持有当前值的新 `SyncedConfig` 对象,旧激活在拆除开始后不再收到新值。 +- Host 上,新图帧在插件自己的 `loader/volatile-update` 监听执行之前进入 pluginEvents 各 follower 队列;不要求线上的先后顺序。 +- 测试:`client/modules` 两面单元测试(剔除、比较、懒生成、引用稳定、监听注册与卸载);真实组合测试经 Loader 启动 profile、修改 patch 并断言浏览器可见值;`client-plugin-live` 与 `client-config-sync` 两个 Web 端到端测试,包括传输重启后的重连。 + +## Alternatives considered + +| Rejected | 理由 | +|---|---| +| 另立一份前端 `ClientConfig` schema | 两份 schema 会漂移;volatile 声明与校验已由 Host schema 承担 | +| 整份配置去掉密钥后下发 | 会把 Host 路径、URL 等普通字段泄漏到浏览器 | +| 前端条目经 `entry.update({ config })` 应用变化 | 前端无 schema,Loader 无法判断 volatile,只会重挂载 | +| 修改 vendored Loader 增加全局 volatile 事件 | 需登记 vendor 本地修改;在条目自身 `ctx` 上监听即可满足 | +| 通道放进 `client/modules` | bootstrap 包会因此依赖 typert 与 gateway | +| 经 `api-remotes` 挂载 `pluginEvents` | `api-remotes` 的替换失败会切断插件更新通道 | +| 为 connection 与 gateway 增加「替换需刷新页面」声明 | 新增 manifest 字段与界面分支;接受替换失败时刷新页面 | +| renderer 提供统一的 `useConfig` 框架 hook | 新增框架级 hook;手动注入 `hooks` 已满足组件取值 | +| 复用 `@deepseek-ai/dsh-settings` 的投影与剔除函数 | settings 架构尚待在本机制之后统一调整,先不建立依赖 | +| 引用只保留 `ObservableSnapshot` | 与 Host volatile 引用的 `get()` 写法不一致 | +| 每个包一个页面级配置对象 | 替换期间正在退出的旧实例仍会收到新配置,与 Host 不一致 | +| 修改 vendored Loader 发出提交事件以保证 Host 入队顺序 | prepend 监听已能满足,不需要 vendor 改动 | +| 另开一条配置专用推送通道 | 与插件图通道重复鉴权、重连与快照语义 | +| 独立 `client/config` 运行时包提供公开写入的配置服务 | 任何插件都能改写别的插件的配置;条目还需按包名等待该服务 | +| 插件从 `@deepseek-ai/dsh-client-modules/types` 导入类型 | 让每个使用配置的插件都依赖启动最早的模块系统包,并暴露实现类 | +| 浏览器也发 `loader/volatile-update` | 字段引用的 `subscribe` 已足够,事件需要深入 Cordis 的过滤机制 | + +## Consequences + +| 风险 | 说明 | +|---|---| +| 通道依赖 connection | 插件图同步依赖 connection 与 gateway Client 面。热替换它们会连带重启本插件并重开流,由新一代 baseline 对账;若其新代码导入或激活失败,页面在刷新前收不到插件更新(已接受) | +| 在他人 `ctx` 上注册监听 | Host 面在被跟踪条目的 `ctx` 上注册,`clientModules` 卸载时必须撤销全部监听 | +| 自建引用 | Client 面引用是自建的 `Volatile` 结构实现,不使用 cosmokit 内部写入协议,`isVolatile` 不识别它们 | +| 空配置对象 | 没有同步字段的前端插件也收到一个空的只读对象作为 `config` | +| 推送顺序不保证 | 配置先到只在各流从 Host 事件到 gateway 写出队列经过相同异步步骤时成立;其他写法的流,无论是否自行等待,都可能先被写出 | +| 每个字段都可能缺值 | `SyncedConfig` 的每个字段读到 `V \| undefined`:密钥、无法投影的值、尚未与浏览器代码对应的 Host 值都会缺失,插件需在每次读取时处理缺值 | diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml index e910137117..2bfd88d57c 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md index 7e2a5111c3..9cc6ced02e 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md @@ -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. diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md index 6887d9feb8..79c0cb2345 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md @@ -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 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml new file mode 100644 index 0000000000..db0702f47e --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md new file mode 100644 index 0000000000..8c33335f55 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -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. diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md new file mode 100644 index 0000000000..645a79c881 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -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,因此弱网不会让草稿附件在切换中丢失。刷新或崩溃仍会丢弃附件;崩溃时不会写标记,因此没有提示。 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml index a690ccf5df..a91fc751b4 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md index bd58e32ff8..d27a69753f 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md @@ -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 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md index d25e3637e1..3e1591ca18 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md @@ -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 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。必需完成值超限会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。 ## 已知限制与暂缓事项 diff --git a/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.i18n.yaml b/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.i18n.yaml index b2f61d6ca2..8861b1db4b 100644 --- a/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.i18n.yaml @@ -9,14 +9,14 @@ en: 3238dfb7db7dfdd8 zh: ec3bdd9a9da0a321 /agent-note-user-authorized-subagent-model-routes/decision: - en: 9eeb42f10be1bd28 - zh: 24e6cca2db77444a + en: 36f00a578ea7adbd + zh: 431cb3d054765414 /agent-note-user-authorized-subagent-model-routes/alternatives-considered: - en: e41c17226190ea8b - zh: d3b1395fafe75f01 + en: 72a41079e819f693 + zh: 0e6c673374932555 /agent-note-user-authorized-subagent-model-routes/consequences: - en: 26244ba796f6ed70 - zh: 47e9744719b05f0b + en: 856c751fcf2326d9 + zh: 3f3ee671b0dfd2e3 /agent-note-user-authorized-subagent-model-routes/related-decisions: en: 0eead87ec1172d81 zh: 4e776a583f5a00a5 diff --git a/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.md b/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.md index c47168e602..cdf13cf485 100644 --- a/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.md +++ b/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.md @@ -12,11 +12,11 @@ Registering an LLM adapter makes its routes reachable, but does not authorize an The Host-owned `subagent-model-selection` settings section stores an explicit `enabled` switch and `allowedModels`, an array of exact `{ provider, model }` routes. Enabling requires at least one route; disabling may retain the selected routes for later reuse. The Plugins settings card reads the live adapter directory through `session/modelCatalog`, lets the user stage the switch and routes, and saves both fields in one revision-fenced settings mutation. It stores no adapter-owned display names, descriptions, or reasoning-effort metadata. A stored or staged route absent from the current directory remains visible as unavailable and removable; a provider-local catalog failure does not block other providers or erase saved authorization or an unsaved selection. A connection reset discards the draft because namespace revisions are comparable only within one Host process. -The Host settings service snapshots the route list for each fresh top-level Session in `subagent/model-selection-policy` when the setting is enabled, before its first model request. Event presence means selection was enabled; the event does not store the global switch. Child Sessions inherit that exact list from their live parent, and resumed Sessions use the recorded event instead of current settings. Settings changes therefore affect only subsequently created top-level Sessions. Without the event, including an explicitly empty restored Session, explicit selection remains restricted to the current parent route. +Each delegation and discovery call reads the current setting; [live subagent model-selection setting](2026-11-17-live-subagent-model-selection-setting.md) supersedes the per-Session snapshot this note originally recorded. When the setting is disabled or its service is absent, explicit selection remains restricted to the current parent route. -The fixed `list_subagent_models` schema does not enumerate the policy. At call time, it lists authorized registered providers and intersects their advertised model catalogs with the recorded route list. Exact lookup requires authorization before resolving model metadata and all supported reasoning efforts, including for ids absent from the catalog. Without a recorded policy, discovery resolves only the parent Agent’s current effective route, even if the catalog omits it. The delegation executor independently checks any explicit provider, model, or effort selection against the same authorization before adapter preflight. A call with no selection fields retains configured or inherited routing. +The fixed `list_subagent_models` schema does not enumerate the policy. At call time, it lists authorized registered providers and intersects their advertised model catalogs with the current route list. Exact lookup requires authorization before resolving model metadata and all supported reasoning efforts, including for ids absent from the catalog. When the setting is disabled, discovery resolves only the parent Agent’s current effective route, even if the catalog omits it. The delegation executor independently checks any explicit provider, model, or effort selection against the same authorization before adapter preflight. A call with no selection fields retains configured or inherited routing. -Model selection has no unrestricted static mode. The default-off Host setting authorizes alternative child routes; without it, the parent route and its supported efforts remain selectable. Each delegation tool’s `modelSelection` option controls only its route fields. One delegation instance per scope enables `modelDiscovery` to own discovery; the setting, discovery, and delegation read the same package-local authorization projection. Web and Desktop presets mount discovery by default, enable spawn route fields, and leave fork route fields disabled to preserve inherited-prefix reuse; custom fork compositions may enable them under the same Session authorization. Tool installation does not sample or expand authorization. +Model selection has no unrestricted static mode. The default-off Host setting authorizes alternative child routes; without it, the parent route and its supported efforts remain selectable. Each delegation tool’s `modelSelection` option controls only its route fields. One delegation instance per scope enables `modelDiscovery` to own discovery; discovery and delegation read the same settings service. Web and Desktop presets mount discovery by default, enable spawn route fields, and leave fork route fields disabled to preserve inherited-prefix reuse; custom fork compositions may enable them under the same Host authorization. Tool installation does not sample or expand authorization. ## Alternatives considered @@ -28,15 +28,14 @@ Model selection has no unrestricted static mode. The default-off Host setting au **Store per-route reasoning-effort allowlists.** Rejected because the user decision concerns child models, while effort ids and compatibility belong to the exact adapter route. Every adapter-supported effort remains available after the route is authorized. -**Read current settings on every discovery or delegation call.** Rejected because a settings edit would silently change a running Session's model-visible capabilities and execution authority. The durable Session snapshot keeps resume and child inheritance deterministic. +**Read current settings on every discovery or delegation call.** Originally rejected because a settings edit would change a running Session's capabilities and execution authority; [live subagent model-selection setting](2026-11-17-live-subagent-model-selection-setting.md) adopts it because users expect the setting to apply immediately. ## Consequences - New adapter registrations and newly advertised models do not expand user authorization. - Adapter removal or catalog lookup failure can make provider discovery unavailable without deleting the saved route decision; an allowed model remains usable when its adapter accepts it even if the advisory catalog omits it. - The allowlist itself consumes no parent-request tokens. Only a `list_subagent_models` result enters the transcript. The `modelSelection` option adds three route fields; `modelDiscovery` adds a fixed discovery schema. Both options default off; shipped headless and SDK profiles carry neither. -- The policy event is log-only and is appended while an Agent is composed, before either SDK begins its run subscription. Shipped SDK profiles do not enable this Web-owned preference, so the event changes neither SDK's expected notifications or persisted-session output; package restore tests own its durable projection instead of fabricating an SDK composition solely to emit it. -- Unit coverage pins settings validation, malformed durable values, Session sampling and inheritance, shared definitions, parent-route defaults, discovery restrictions, executor denial, and the settings UI’s staged writes and revision checks. The assembled Web scenario pins the real settings document and Plugins card flow. +- Unit coverage pins settings validation, live reads in parent and child Sessions, shared definitions, parent-route defaults, discovery restrictions, executor denial, and the settings UI’s staged writes and revision checks. The assembled Web scenario pins the real settings document and Plugins card flow. ## Related decisions diff --git a/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.zh.md b/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.zh.md index 0ca908b24d..68acaa5e78 100644 --- a/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.zh.md +++ b/.agents/notes/implemented/feature/2026-08-24-user-authorized-subagent-model-routes.zh.md @@ -12,11 +12,11 @@ Status: implemented Host 自有的 `subagent-model-selection` 设置 section 保存显式 `enabled` 开关与 `allowedModels`,后者是由精确 `{ provider, model }` 路由组成的数组。启用时必须至少有一条路由;关闭时可以保留已选路由,供以后重新启用。Plugins 设置卡通过 `session/modelCatalog` 读取实时适配器目录,让用户暂存开关与路由,再在一次带 revision 限制的设置 mutation 中保存两个字段。它不保存适配器自有的显示名称、描述或推理强度元数据。当前目录中缺失的已存或暂存路由仍显示为不可用并允许移除;某个提供方的目录失败不会阻塞其他提供方,也不会清除已存授权或未保存选择。连接重置会丢弃草稿,因为 namespace revision 只能在同一个 Host 进程内比较。 -设置启用时,Host 设置服务为每个新顶层 Session 在首个模型请求前将路由列表记录为 `subagent/model-selection-policy`。事件存在表示选择已启用;事件不保存全局开关。子 Session 从在线父级继承同一精确列表,恢复的 Session 使用已记录事件而非当前设置。因此设置变更只影响之后创建的顶层 Session。没有该事件时,包括显式为空的恢复 Session,显式选择仍仅限当前父级路由。 +每次委派和发现调用都读取当前设置;[实时读取的 subagent 模型选择设置](2026-11-17-live-subagent-model-selection-setting.zh.md)取代了本 Agent Note 最初记录的逐 Session 快照。设置关闭或其服务缺失时,显式选择仍仅限当前父级路由。 -固定的 `list_subagent_models` schema 不枚举策略。调用时,它列出已授权且已注册的提供方,并取其公布模型目录与已记录路由列表的交集。精确查询先要求授权,再解析模型元数据及全部支持的推理强度,也允许目录未列出的 ID。没有已记录策略时,发现只解析父 Agent 当前生效的路由,即使目录未列出它。委派执行器会在适配器预检前独立校验显式提供方、模型或强度选择是否符合相同授权。没有选择字段的调用保留配置或继承的路由。 +固定的 `list_subagent_models` schema 不枚举策略。调用时,它列出已授权且已注册的提供方,并取其公布模型目录与当前路由列表的交集。精确查询先要求授权,再解析模型元数据及全部支持的推理强度,也允许目录未列出的 ID。设置关闭时,发现只解析父 Agent 当前生效的路由,即使目录未列出它。委派执行器会在适配器预检前独立校验显式提供方、模型或强度选择是否符合相同授权。没有选择字段的调用保留配置或继承的路由。 -模型选择没有无限制的静态模式。默认关闭的 Host 设置授权其他子级路由;没有该授权时,仍可选择父级路由及其支持的强度。各委派工具的 `modelSelection` 选项只控制自身路由字段。每个作用域的一个委派实例启用 `modelDiscovery` 并负责发现;设置、发现和委派读取包内同一个授权投影。Web 与 Desktop preset 默认挂载发现工具,启用 spawn 路由字段,并为 fork 保持关闭,以保留对继承前缀的复用;自定义 fork 组合可以在相同 Session 授权下启用这些字段。工具安装不采样或扩大授权。 +模型选择没有无限制的静态模式。默认关闭的 Host 设置授权其他子级路由;没有该授权时,仍可选择父级路由及其支持的强度。各委派工具的 `modelSelection` 选项只控制自身路由字段。每个作用域的一个委派实例启用 `modelDiscovery` 并负责发现;发现和委派读取同一个设置服务。Web 与 Desktop preset 默认挂载发现工具,启用 spawn 路由字段,并为 fork 保持关闭,以保留对继承前缀的复用;自定义 fork 组合可以在相同 Host 授权下启用这些字段。工具安装不采样或扩大授权。 ## Alternatives considered @@ -28,15 +28,14 @@ Host 自有的 `subagent-model-selection` 设置 section 保存显式 `enabled` **保存每条路由的推理强度允许列表。** 不采用,因为用户决定针对子级模型,而强度 id 与兼容性属于精确适配器路由。路由获准后,仍可使用适配器支持的每种强度。 -**每次发现或委派调用都读取当前设置。** 不采用,因为设置编辑会静默改变运行中 Session 的模型可见能力和执行权限。持久 Session 快照会让恢复与子级继承保持确定。 +**每次发现或委派调用都读取当前设置。** 最初不采用,因为设置编辑会改变运行中 Session 的能力和执行权限;[实时读取的 subagent 模型选择设置](2026-11-17-live-subagent-model-selection-setting.zh.md)采用了它,因为用户期望设置立即生效。 ## Consequences - 新适配器注册和新公布模型不会扩大用户授权。 - 适配器移除或目录查询失败可能使提供方发现不可用,但不会删除已存路由决定;只要适配器接受某个获准模型,即使建议性目录省略它,该模型仍可使用。 - 允许列表本身不消耗父级请求 token。只有 `list_subagent_models` 结果进入 transcript。`modelSelection` 选项增加三个路由字段;`modelDiscovery` 增加固定发现 schema。两个选项都默认关闭;随附 headless 与 SDK profile 两者都不携带。 -- 策略事件仅存在于日志,并在 Agent 组合期间、两套 SDK 开始订阅运行前追加。随附 SDK profile 不启用这项 Web 自有偏好,因此该事件不会改变任一 SDK 的预期通知或持久 Session 输出;其持久投影由包级恢复测试负责,不会为了发出该事件而虚构 SDK 组合。 -- 单元覆盖固定设置校验、异常持久值、Session 取样与继承、共享定义、父级路由默认值、发现限制、执行器拒绝,以及设置 UI 的暂存写入与 revision 检查。组装 Web 场景固定真实设置文档与 Plugins 设置卡流程。 +- 单元覆盖固定设置校验、父子 Session 中的实时读取、共享定义、父级路由默认值、发现限制、执行器拒绝,以及设置 UI 的暂存写入与 revision 检查。组装 Web 场景固定真实设置文档与 Plugins 设置卡流程。 ## Related decisions diff --git a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml index acba92a4e3..d8bd3470b9 100644 --- a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml @@ -9,14 +9,14 @@ en: 7115cbaefaa11d2d zh: 23aff8797a651a36 /agent-note-settings-driven-mcp-server-manager/decision: - en: 39cf3ae7e8a5799f - zh: 7a26503da73e238f + en: ac7cc4c046ca2377 + zh: 697233f3b09759de /agent-note-settings-driven-mcp-server-manager/alternatives-considered: - en: daad4acd963926cc - zh: 152f3d35a4fe3309 + en: 1154a35a2f9af53f + zh: 92ad94d6306463bb /agent-note-settings-driven-mcp-server-manager/testing: en: cbfd30400093ade5 zh: 018ad32e25c6c7fc /agent-note-settings-driven-mcp-server-manager/consequences: - en: 2a11ba309122335a - zh: 663670e2bf3c5a37 + en: 078ddb6329aae177 + zh: dc2b2f3c457feb53 diff --git a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md index 653be051a6..c77fbb57e4 100644 --- a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md +++ b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md @@ -20,19 +20,21 @@ Installed application plugins also bring their own servers. Each must add its se **A flat entry schema, validated cross-field.** The entry is flat with a `transport` discriminant, and write-time validation enforces the per-transport requirements and rejections (missing `command`/`url`, cross-transport fields, malformed templates) at the write — a schema-valid-but-unserviceable entry is never stored, and refusals name the offending field where a union's shape error would not. -**Children are plugin instances, not library calls.** Each enabled entry mounts `dsh-mcp-client` under the manager's fiber via `ctx.plugin()`. That reuses the tested activation/disposal semantics, makes `serverName` reservations collide correctly with statically composed instances (surfaced as a `failed`/`load` status with the actionable message), and lets manager disposal unwind every instance and its tools through ordinary fiber teardown. +**Children are plugin instances, not library calls.** Each enabled entry is a `dsh-mcp-client` instance that the MCP client host mounts under the manager's fiber via `ctx.plugin()`. That reuses the tested activation/disposal semantics, makes `serverName` reservations collide correctly with statically composed instances (surfaced as a `failed`/`load` status with the actionable message), and lets manager disposal unwind every instance and its tools through ordinary fiber teardown. + +**The MCP client host is the manager's only reach into mcp-client.** The manager creates an `McpClientHost` at construction and imports only that class and mcp-client types. The host validates an entry's client fields through each transport's own schema, so refusals still name the field; mounts instances under the manager's fiber; probes; and creates authorization owners from the manager's context. A plugin entry exports what the Loader loads and its Service and error classes, so the host is a Service class rather than a set of functions. **Whole-entry identity; `enabled` controls mounting.** A changed entry rebuilds the child instance; disabling or deleting it disposes the child. Reconciliation and `restart` serialize on one operation tail. Probes run independently, and configuration changes cancel affected probes before queued cleanup waits for them. The manager retains a failed cleanup record and refuses a replacement until the Host restarts, preventing overlapping server lifetimes. -**Status belongs to the child Fiber.** The supervisor publishes a cell read through `connectionStatusOf(fiber)`. It survives reloads of that Fiber and remains readable after disposal, which detaches observers. Fiber identity distinguishes instances across registration scopes without identity tokens in status payloads. The manager aggregates cells into `list()` and the `mcp-manager/status` event, absorbing equal statuses and remaining silent after disposal. Removed entries with incomplete cleanup remain listed with `configured: false`. The first reconcile waits for the manager’s own Fiber activation because strict service reads require an active Fiber. +**Status belongs to the child Fiber.** The supervisor publishes a cell that the host's `mount` hands to the manager once the instance activates. It survives reloads of that Fiber and remains readable after disposal, which detaches observers. Fiber identity distinguishes instances across registration scopes without identity tokens in status payloads. The manager aggregates cells into `list()` and the `mcp-manager/status` event, absorbing equal statuses and remaining silent after disposal. Removed entries with incomplete cleanup remain listed with `configured: false`. The first reconcile waits for the manager’s own Fiber activation because strict service reads require an active Fiber. **Templates keep secrets out of configuration.** Stored env and header values remain readable; a value that must stay hidden belongs in a template. The manager passes raw templates into the child Fiber. Opt-in mcp-client expansion resolves `${credential:REF}` from the current provider, whose local implementation also reads the inherited environment, so there is no separate environment scheme. Missing values leave non-strict clients waiting for credentials; referenced credential notifications can recover them. A changed value replaces the connection only after cleanup succeeds, while a same-value notification preserves the connection and retry budget. Diagnostics, tool-call failures, and `isError` results keep upstream text with every resolved value replaced by `[redacted]`, so the model can act on a server's error without seeing a secret the instance sent. -**mcp-client budgets and probe.** `startupTimeoutMs` is optional for standalone clients; the manager explicitly supplies a 30-second default. `probeServer(ctx, config, options)` connects, reads server identity, lists tool names, and closes without reserving a name or registering tools. Its own budget and configurable listing caps are independent of runtime startup. Probe success and transport closure are separate results, so successful discovery cannot hide incomplete cleanup. +**mcp-client budgets and probe.** `startupTimeoutMs` is optional for standalone clients; the manager explicitly supplies a 30-second default. The host's `probe(config, options)` connects, reads server identity, lists tool names, and closes without reserving a name or registering tools. Its own budget and configurable listing caps are independent of runtime startup. Probe success and transport closure are separate results, so successful discovery cannot hide incomplete cleanup. **The manager is its own Remote surface.** `McpServerManager` is a Typert Remote service: `watch` streams the complete server list on subscription and after every status or entry change, and `restart` and `probe` call the Host operations. Configuration writes remain on the Settings Remote, and the manager exposes no write method, so a browser cannot define a server command. -OAuth is deliberately out of scope: the credential-record and authorization seams plus the MCP SDK's `OAuthClientProvider` are the intended home, and a `needs-auth` status state is reserved for that change. +**OAuth stays on the credential and authorization seams.** The MCP SDK's `OAuthClientProvider` runs inside mcp-client: passive connections use committed grants and enter `waiting-authorization` when none is usable, while explicit sign-in runs through the manager's `startAuthorization` and the authorization seam. Each entry owns one stable `mcp-client/` credential key. ## Alternatives considered @@ -48,6 +50,12 @@ OAuth is deliberately out of scope: the credential-record and authorization seam **Poll status from the management surface.** Rejected: the Remote plane already forwards Host events; peers that shipped polling (Reasonix) or lacked a status event (OpenCode v1) treat it as a defect to fix. +**Export validation, probe, status, and authorization values from the mcp-client entry.** Rejected: plugin entries export what the Loader loads and their Service and error classes, not helper values. + +**Load the host as its own mcp-client entry with `host: true` that the manager injects.** Rejected: every composition that loads the manager would need a second row, and the client's configuration would carry a shape that connects no server. Its only gain, a manager that restarts when mcp-client reloads during development, does not justify either. + +**Move the connection machinery into a separate service package.** Rejected: per-server mcp-client instances use the same machinery, so every composition that loads mcp-client would also have to load the new service. + **A capability seam (Definition/Provider/Consumer) for "MCP management".** Rejected: one implementation and no independently evolving roles; a seam without a second provider is structure without an owner. ## Testing @@ -60,4 +68,5 @@ mcp-client unit tests cover status transitions, independent startup and probe bu - Liveness relies on transport closure and request failures; a Streamable HTTP server that stalls without closing is noticed when a request fails. - A rebuilt server’s tools remain unavailable until the replacement completes its initial sync. Replacement waits for confirmed transport closure and successful local cleanup. - The manager governs the global plane only; preset-scoped and static instances stay outside its list. +- The manager keeps the mcp-client code it loaded until the manager itself reloads; a development reload of mcp-client alone does not restart it. - `startupTimeoutMs` bounds startup attempts, while notification-driven re-sync requests still ride the SDK's request default — recorded as an mcp-client limitation. diff --git a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md index 875e6d3bd9..31890b1998 100644 --- a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md +++ b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md @@ -20,19 +20,21 @@ Status: implemented **扁平条目 schema,跨字段校验。** 条目是带 `transport` 判别字段的扁平结构,写入期校验在写入处强制逐传输要求与拒绝(缺 `command`/`url`、跨传输字段、模板写错)——schema 合法但不可执行的条目永远不会被存下,且拒绝会点名出错字段,union 的形状错误做不到。 -**子实例是插件实例,不是库调用。** 每个启用条目经 `ctx.plugin()` 在管理器 fiber 下挂载 `dsh-mcp-client`。这复用了经过测试的激活/销毁语义,让 `serverName` 预留与静态组合实例正确冲突(以带可操作消息的 `failed`/`load` 状态浮出),并让管理器销毁经普通 fiber 收卷解除每个实例及其工具。 +**子实例是插件实例,不是库调用。** 每个启用条目都是 MCP 客户端宿主经 `ctx.plugin()` 挂在管理器 fiber 下的 `dsh-mcp-client` 实例。这复用了经过测试的激活/销毁语义,让 `serverName` 预留与静态组合实例正确冲突(以带可操作消息的 `failed`/`load` 状态浮出),并让管理器销毁时经普通 fiber 收卷撤下每个实例及其工具。 + +**MCP 客户端宿主是管理器接触 mcp-client 的唯一途径。** 管理器在构造时创建 `McpClientHost`,并且只从 mcp-client 导入这个类和类型。宿主用各传输自己的 schema 校验条目的客户端字段,因此拒绝时仍点名字段;它把实例挂在管理器的 fiber 下、执行探测,并用管理器的 context 创建授权所有者。插件入口只导出 Loader 加载的内容及其 Service 与错误类,因此宿主是一个 Service 类,而不是一组函数。 **整条目决定实例;`enabled` 控制挂载。** 条目变化会重建子实例,停用或删除条目会销毁子实例。对账与 `restart` 在同一操作队列中串行执行。探测独立运行,配置变更先取消受影响的探测,再由队列中的清理操作等待它们结束。管理器保留清理失败记录,并在 Host 重启前拒绝替换,防止服务器生命周期重叠。 -**状态属于子 Fiber。** 监督器发布经 `connectionStatusOf(fiber)` 读取的状态单元。同一 Fiber 重载时保留该单元,最终销毁时移除观察者,但单元仍可读取。Fiber 身份直接区分不同注册作用域中的实例,无需在状态载荷中加入身份令牌。管理器聚合为 `list()` 和 `mcp-manager/status` 事件,吸收相等状态并在销毁后停止发出事件。配置已删除但清理未完成的条目仍以 `configured: false` 列出。首次对账等待管理器自身 Fiber 激活,因为严格服务读取要求 Fiber 已激活。 +**状态属于子 Fiber。** 监督器发布状态单元,实例激活后由宿主的 `mount` 交给管理器。同一 Fiber 重载时保留该单元,最终销毁时移除观察者,但单元仍可读取。Fiber 身份直接区分不同注册作用域中的实例,无需在状态载荷中加入身份令牌。管理器聚合为 `list()` 和 `mcp-manager/status` 事件,吸收相等状态并在销毁后停止发出事件。配置已删除但清理未完成的条目仍以 `configured: false` 列出。首次对账等待管理器自身 Fiber 激活,因为严格服务读取要求 Fiber 已激活。 **模板让密钥不进入配置。** 存储的 env 和 header 值仍可读,必须隐藏的值应使用模板。管理器把原始模板传入子 Fiber。mcp-client 显式启用模板展开后,从当前 provider 解析 `${credential:REF}`;其本地实现也读取继承的环境变量,因此没有单独的环境变量模板。缺失值使非严格客户端等待凭据,相关凭据通知可恢复连接。值变化时,连接只有在清理成功后才会替换;同值通知保留当前连接和重试预算。诊断、工具调用失败与 `isError` 结果保留上游文本,其中每个已解析的值都替换为 `[redacted]`,模型因此能依据服务器的错误行动,又看不到实例发送过的密钥。 -**mcp-client 预算与探测。** 独立客户端的 `startupTimeoutMs` 可省略,管理器明确提供 30 秒默认值。`probeServer(ctx, config, options)` 连接、读取服务器身份、列出工具名并关闭,不预留名称,也不注册工具。探测有独立于运行期启动的预算和可配置的列表上限。探测成功与传输关闭分别报告,因此发现成功不会掩盖清理未完成。 +**mcp-client 预算与探测。** 独立客户端的 `startupTimeoutMs` 可省略,管理器明确提供 30 秒默认值。宿主的 `probe(config, options)` 连接、读取服务器身份、列出工具名并关闭,不预留名称,也不注册工具。探测有独立于运行期启动的预算和可配置的列表上限。探测成功与传输关闭分别报告,因此发现成功不会掩盖清理未完成。 **管理器自身即 Remote 面。** `McpServerManager` 是 Typert Remote 服务:`watch` 在订阅时以及每次状态或条目变化后推送完整服务器列表,`restart` 与 `probe` 调用宿主操作。配置写入仍走 Settings Remote,管理器不提供写入方法,因此浏览器无法定义服务器命令。 -OAuth 刻意不在本次范围内:凭据记录与 authorization seam 加 MCP SDK 的 `OAuthClientProvider` 是预期归宿,`needs-auth` 状态位为那次变更保留。 +**OAuth 留在凭据与 authorization seam 上。** MCP SDK 的 `OAuthClientProvider` 在 mcp-client 内运行:被动连接只使用已提交的授权,没有可用授权时进入 `waiting-authorization`;显式登录经管理器的 `startAuthorization` 与 authorization seam 完成。每个条目拥有一个稳定的 `mcp-client/` 凭据 key。 ## 曾考虑的替代方案 @@ -48,6 +50,12 @@ OAuth 刻意不在本次范围内:凭据记录与 authorization seam 加 MCP S **让管理界面轮询状态。** 否决:Remote 面已转发宿主事件;发货了轮询的同类产品(Reasonix)或缺状态事件的(OpenCode v1)都把它当作待修缺陷。 +**从 mcp-client 入口导出校验、探测、状态与授权的值。** 否决:插件入口只导出 Loader 加载的内容及其 Service 与错误类,不导出辅助值。 + +**把宿主作为以 `host: true` 加载、由管理器注入的独立 mcp-client 条目。** 否决:每个加载管理器的组合都得多一行,客户端配置也要多出一种不连接任何服务器的形态。它唯一的好处是开发期 mcp-client 重载时管理器随之重启,不足以抵消这两点。 + +**把连接机制移到单独的服务包。** 否决:每台服务器的 mcp-client 实例使用同一套机制,因此所有加载 mcp-client 的组合都得额外加载这个新服务。 + **为「MCP 管理」开 capability seam(Definition/Provider/Consumer)。** 否决:只有一个实现、没有独立演化的角色;没有第二个 provider 的 seam 是无主的结构。 ## 测试 @@ -60,4 +68,5 @@ mcp-client 单测覆盖状态迁移、独立的启动与探测预算、模板绑 - 存活判断依赖传输关闭与请求失败;停滞但不关闭的 Streamable HTTP 服务器要等到请求失败时才会被发现。 - 被重建服务器的工具在替换连接完成首次同步前不可用。替换会等待传输确认关闭且本地清理成功。 - 管理器只治理全局面;preset 作用域与静态实例不在其列表内。 +- 管理器沿用它加载的 mcp-client 代码,直到管理器自身重载;开发期只重载 mcp-client 不会重启管理器。 - `startupTimeoutMs` 只为启动尝试设界,通知驱动的重同步请求仍走 SDK 请求默认值——已记录为 mcp-client 的限制。 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index 1f3c4ca363..c63cf8be98 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml @@ -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: e76e8129691db30f zh: fd242e67bab2633d diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md index 01913de55a..8c35956d61 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -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. diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index 4c54a66371..b1c0b6e42d 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md @@ -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 服务作为插件页中默认禁用的一个条目发布。 评审与工作树控件服务于同一个代码修改流程。统一插件入口让用户可以一次启用这些能力,无需根据底层包的拆分判断应该开启哪张卡片。包与两套工作树服务仍保持独立,分别负责会话开始前和对话中创建工作树的流程。 diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml index 4124137839..749b8adffb 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml @@ -18,8 +18,8 @@ en: e7cae8876e688f92 zh: 1d326330c34d128d /agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/decision/wire: - en: f15c4106f228f5f6 - zh: ab80cf4ce62ae84c + en: 387deee727dfc538 + zh: 1cae30f007f842d0 /agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/decision/page-side: en: c0610c8f5a0882f3 zh: d309cbc53183ec6e @@ -30,5 +30,5 @@ en: abb9d7ab9ef1df15 zh: 1704732daf5f2886 /agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/consequences: - en: 815b41dc4f9ffcee - zh: b57388264cc459c7 + en: a21bf34ac3983fbb + zh: c6278ef441587a48 diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md index 33ac74d954..43728342e9 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md @@ -60,7 +60,7 @@ BootManifest { ...; release?: WebBootRelease } ``` - [ClientModuleRegistry](../../../../packages/client/modules/src/index.ts) computes the release once at construction and `compose()` writes it into every graph; `release` stays outside `graph.rev`. There is no new config field and the composition is unchanged. -- `__DSH_BOOT__` and every SSE `graph` frame carry the field, so one graph frame carries both the Host release and its complete module graph; the client-hmr Host half is unchanged. A rebuilt frame comes from the same Host process as the graph frame before it on that SSE connection, so it inherits that frame's release. +- `__DSH_BOOT__` and every plugin-events `baseline` and `graph` frame carry the field, so one graph frame carries both the Host release and its complete module graph; the client-hmr Host half is unchanged. A rebuilt frame comes from the same Host process as the graph frame before it on that stream generation, so it inherits that frame's release. - `parseBootManifest` accepts an absent `release`, rejects a non-string `version` or `commit`, and drops members outside the identity, so equality compares only those two fields. `readRelease` reads only the `release` member of a received graph, so a page compares releases before it validates anything else; a release it cannot read counts as absent. Older pages that do not know the field ignore it. ### Page side @@ -136,8 +136,7 @@ Order of operations: - While the Host serves another release, plugin updates, including enabling or disabling a plugin on the Host, reach the page only after a reload. - When a Host returns to the page's release, only modules whose revisions differ are replaced. Revisions come from artifact metadata, so a rebuild of identical code still replaces the rebuilt modules once, without a prompt. - A composition without the dialog registered still pauses updates from another release and logs the warning; the user sees no prompt. -- The API connection and SSE are independent channels, so an old page can show a protocol error before the dialog appears. -- If a restarting Host answers `/plugins/events` with a non-200 status before registering the route, the browser closes that SSE stream for good, and the page cannot detect a release change until it reloads. +- After a terminal plugin-events stream failure the page cannot detect a release change until it reloads. - A source launch without dev-web has no commit, so development detection falls back to version changes. - Each tab prompts and remembers independently. - Unit tests pin the gate through `ClientEntries` (same-release replacement, another release applying nothing, the return to the boot release replacing only changed modules, dismissal, absent releases), the manifest parser, the Host-published release, the shared preset's Node-half defines, and the dialog's rendering and callbacks. diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md index f8e8f85f71..c668e9615b 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md @@ -60,7 +60,7 @@ BootManifest { ...; release?: WebBootRelease } ``` - [ClientModuleRegistry](../../../../packages/client/modules/src/index.ts) 在构造时计算一次 release,由 `compose()` 写入每个 graph;`release` 不计入 `graph.rev`。不新增配置项,组合配置不变。 -- `__DSH_BOOT__` 和每个 SSE `graph` 帧都带这个字段,所以一个 graph 帧同时携带 Host 的 release 和完整模块图;client-hmr 的 Host 半侧不变。rebuilt 帧与同一条 SSE 连接上前一个 graph 帧来自同一个 Host 进程,因此沿用那一帧的 release。 +- `__DSH_BOOT__` 和插件事件流的每个 `baseline`、`graph` 帧都带这个字段,所以一个 graph 帧同时携带 Host 的 release 和完整模块图;client-hmr 的 Host 半侧不变。rebuilt 帧与同一代流上前一个 graph 帧来自同一个 Host 进程,因此沿用那一帧的 release。 - `parseBootManifest` 允许 `release` 缺省,拒绝非字符串的 `version` 或 `commit`,并丢弃身份以外的成员,因此相等判断只看这两个字段。`readRelease` 只读取收到的 graph 的 `release` 成员,所以页面先比较 release,再校验其余内容;读不出的 release 视为缺省。不认识该字段的旧页面会忽略它。 ### 页面侧 @@ -136,8 +136,7 @@ class ClientEntries { - Host 提供其他 release 期间,插件更新(包括在 Host 上启用或停用插件)要等刷新后才会到达页面。 - Host 回到页面的 release 时,只替换 revision 不同的模块。revision 取自产物元数据,所以即使重新构建出的代码完全相同,也会把重建过的模块替换一次,不弹框。 - 组合里没有注册确认框时,仍会暂停来自其他 release 的更新并记录警告,用户看不到提示。 -- API 连接和 SSE 是两条独立通道,旧页面可能在确认框出现之前就已显示协议错误。 -- 重启中的 Host 若在注册路由前对 `/plugins/events` 返回非 200 状态,浏览器会永久关闭这条 SSE,页面在刷新前检测不到 release 变化。 +- 插件事件流以终止性错误结束后,页面在刷新前检测不到 release 变化。 - 不经 dev-web 的源码启动没有 commit,开发期只能检测到版本号变化。 - 每个标签页各自提示、各自记录。 - 单元测试通过 `ClientEntries` 固定 gate 的行为(同一 release 的替换、其他 release 不应用任何内容、回到启动 release 只替换变化了的模块、撤回、缺失 release),并覆盖 manifest 解析、Host 发布的 release、共享预设给 Node 半侧的 define,以及确认框的渲染与回调。 diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml index 98c3a9541a..0780e32ff0 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml @@ -27,8 +27,8 @@ en: 0dcc97d8105fab60 zh: d80d40ae3a0c601d /agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered: - en: 907e0b8424943d43 - zh: f45e583e7cb4eb63 + en: e377ad3c0327300e + zh: 4b9f7f83f464e657 /agent-note-direct-deepseek-search-and-fetch-apis/consequences: en: 7ec21c5b1124e5f8 zh: af769dbdb4face9f diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md index ee8b912b2e..6b535ace4f 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md @@ -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. Credentials instead come from one service, `ctx.deepseekAuth`, which releases the request headers of the API key or the account sign-in; 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. diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md index c7493c8e23..622195c6b6 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md @@ -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.deepseekAuth`,它释放 API 密钥或账号登录凭据的请求头;Messages 搜索与 Search/Fetch API 传输层保持独立。 **把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。 diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml new file mode 100644 index 0000000000..2ef5bf0f10 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.md new file mode 100644 index 0000000000..7ef1e8f306 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.md @@ -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. diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md new file mode 100644 index 0000000000..5a2a4bada2 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md @@ -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 中。 diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml index b1ee1847fe..f4408017fe 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml @@ -9,8 +9,8 @@ en: ad1da0c97cfc9c2d zh: f4420c0b004fd189 /agent-note-code-review-page/decision: - en: ba22bfdf639e29ba - zh: 3d018f17dcbba803 + en: b0ba35d7c5818dc3 + zh: 5414ec6190be0726 /agent-note-code-review-page/alternatives-considered: en: 963b1be39a0e4bac zh: 940b86a5e2036477 diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md index 80c8a8a05f..0c6e785abe 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md @@ -16,7 +16,7 @@ A left-navigation Code review page in [`dsh-experimental-client-ui-forge`](../.. - **Reads by URL** — the page's `forgePanel/review*` methods name a change request by URL and no Session; they share the Session-bound methods' implementation and are reachable only by callers that may use the Host's code host credentials. - **Description** — `readDescription` returns the Markdown body, labels, and signed addresses for private attachments, which the page substitutes before rendering with HTML omitted. - **Changes** — the page draws the changes view itself, split from the right-sidebar tab, with a panel state that holds only the shown change request; plugin lenses, annotations, and slots stay with the Session tab, whose extension points name a Session. -- **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. Picking another Workspace reports its blank to the page instead of navigating. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound. +- **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. A Workspace picked in the Hero is handled by the page, as every owner of the content handles its own picks: the page connects that Workspace's blank and shows it in the chat tab, where the main Conversation opens it as the main Session. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound. - **Hosts** — the page lists every configured host together; choosing among hosts and accounts waits for a second provider that lists change requests. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md index 6e34a40d58..0a8038c510 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md @@ -16,7 +16,7 @@ Status: implemented - **按 URL 读取**——页面的 `forgePanel/review*` 方法以 URL 而不是会话指定变更请求;它们与会话绑定的方法共用实现,只有可以使用 Host 代码托管凭据的调用方能访问。 - **描述**——`readDescription` 返回 Markdown 正文、标签以及私有附件的签名地址,页面替换这些地址后以省略 HTML 的方式渲染。 - **变更**——页面自己绘制变更视图(从右侧栏标签中拆出),面板状态只含显示中的变更请求;插件的透镜、行注释和插槽仍只在会话标签中,因为这些扩展点以会话为对象。 -- **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。选择另一个工作区时,把它的空白会话交给页面而不是跳转。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。 +- **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。在 Hero 中选择工作区由页面自己处理,这与内容的每个属主处理各自的选择一致:页面连接该工作区的空白会话并在对话标签中显示它,而主 Conversation 会把它打开为主会话。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。 - **主机**——页面把所有已配置的主机合并列出;在主机与账号之间选择要等到第二个能列出变更请求的提供方。 ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.i18n.yaml b/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.i18n.yaml new file mode 100644 index 0000000000..3bf69cb835 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-17-live-subagent-model-selection-setting.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-17-live-subagent-model-selection-setting.md +/agent-note-live-subagent-model-selection-setting: + en: 01cc7a22f888d43f + zh: 7e8db3cb85eb61e5 +/agent-note-live-subagent-model-selection-setting/problem: + en: 63a11d729aada846 + zh: a54b5069bb176440 +/agent-note-live-subagent-model-selection-setting/decision: + en: e6ea827eaf115283 + zh: 994dd77261bc9f4c +/agent-note-live-subagent-model-selection-setting/alternatives-considered: + en: 864544c31f8f92bc + zh: 3fbab0d1567228eb +/agent-note-live-subagent-model-selection-setting/consequences: + en: 3035a4f2981e01b9 + zh: 4b1f84b26258470c diff --git a/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.md b/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.md new file mode 100644 index 0000000000..eb5cc14813 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.md @@ -0,0 +1,30 @@ +# Agent Note: Live subagent model-selection setting + +Status: implemented + +English | [中文](2026-11-17-live-subagent-model-selection-setting.zh.md) + +## Problem + +[User-authorized subagent model routes](2026-08-24-user-authorized-subagent-model-routes.md) snapshotted the Host allowlist into each fresh top-level Session as `subagent/model-selection-policy`. A user who enabled the setting, added a route, or revoked one in the middle of a Session saw no effect until a new Session started; restored Sessions kept whatever list their creation recorded. The setting's observable meaning depended on when each Session was created, which the settings page could not explain. + +## Decision + +`SubagentModelSelectionConfig.allowedRoutes()` reads the volatile `enabled` value at each call and returns `undefined` immediately when selection is disabled; otherwise it validates `allowedModels` and returns a detached route list. The `subagent` executor and `list_subagent_models` call it through `ctx.get('subagentModelSelection')` for explicit route selection by model-selectable tools and for every discovery call, so an edit applies to the next call in every running, restored, and child Session. When the service is absent or the setting is disabled, explicit selection permits only the current parent route, as before. + +No Session event is appended and no projection is registered. The `subagent/model-selection-policy` declaration remains so released Session logs still validate, but no code reads it; a Session that recorded a policy follows the current setting. An enabled setting with an empty, malformed, or repeated route list fails each call that reads it with `INVALID_MODEL_SELECTION_SETTINGS` rather than rejecting Agent creation. Ordinary delegation and tools with model selection disabled do not read the list. + +## Alternatives considered + +**Keep the creation-time snapshot.** Rejected because the user-visible setting is a standing authorization, and an edit that silently skips every open Session reads as a broken control. The earlier note's concern that an edit changes a running Session's capabilities is the requested behavior. + +**Record a new policy event whenever the setting changes.** Rejected because it would append to every live Session on each settings save, still miss restored Sessions until they load, and leave two sources that could disagree. The allowlist is not model-visible input: the tool schemas are fixed, and only a `list_subagent_models` result or a delegation error reaches the model, and both are logged as tool results. + +**Honor a recorded policy when present and fall back to the setting.** Rejected because an old Session would then ignore later edits, recreating the inconsistency for exactly the Sessions users resume most. + +## Consequences + +- Revoking a route takes effect at the next call, including for children of a running parent; a route that was allowed earlier in the transcript can now be rejected with `MODEL_ROUTE_NOT_ALLOWED`. +- Replaying a Session no longer reproduces its authorization from the log alone; the tool results in the log still show what the model saw. +- Agent creation no longer depends on the setting service, so an invalid setting cannot block Sessions without delegation tools. +- Unit tests in `packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts` pin live reads, mid-Session edits in parent and child Sessions, and that a recorded policy is ignored. diff --git a/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.zh.md b/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.zh.md new file mode 100644 index 0000000000..a6ebc06b1a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.zh.md @@ -0,0 +1,30 @@ +# Agent Note: 实时读取的 subagent 模型选择设置 + +Status: implemented + +[English](2026-11-17-live-subagent-model-selection-setting.md) | 中文 + +## Problem + +[用户授权的 subagent 模型路由](2026-08-24-user-authorized-subagent-model-routes.zh.md)把 Host 允许列表快照到每个新顶层 Session 的 `subagent/model-selection-policy` 中。用户在 Session 进行中启用设置、添加路由或撤销路由后,要到新 Session 开始才会生效;恢复的 Session 保留其创建时记录的列表。设置的可见含义取决于每个 Session 的创建时间,设置页无法解释这一点。 + +## Decision + +`SubagentModelSelectionConfig.allowedRoutes()` 在每次调用时读取 volatile 的 `enabled`;选择关闭时立即返回 `undefined`,否则校验 `allowedModels` 并返回独立的路由列表。`subagent` 执行器和 `list_subagent_models` 在允许模型选择的工具显式选择路由时、每次发现调用时通过 `ctx.get('subagentModelSelection')` 调用它,因此设置编辑会对所有运行中、已恢复和子 Session 的下一次调用生效。服务缺失或设置关闭时,显式选择与之前一样只允许当前父级路由。 + +不追加 Session 事件,也不注册投影。`subagent/model-selection-policy` 声明保留,使已发布的 Session 日志仍能通过校验,但没有代码读取它;记录过策略的 Session 遵循当前设置。启用但路由列表为空、格式无效或重复时,读取该设置的每次调用都会以 `INVALID_MODEL_SELECTION_SETTINGS` 失败,而不是使 Agent 创建失败。普通委派和关闭模型选择的工具不读取该列表。 + +## Alternatives considered + +**保留创建时快照。** 不采用,因为用户可见的设置是持续生效的授权,编辑后静默跳过所有已打开的 Session,看起来就是控件失效。旧 Agent Note 担心编辑会改变运行中 Session 的能力,而这正是所需行为。 + +**设置变更时记录新的策略事件。** 不采用,因为每次保存设置都要向所有在线 Session 追加事件,已恢复的 Session 在加载前仍会遗漏,并留下两个可能不一致的来源。允许列表不是模型可见输入:工具 schema 固定,只有 `list_subagent_models` 结果或委派错误会到达模型,两者都作为工具结果记录在日志中。 + +**存在已记录策略时沿用它,否则回退到设置。** 不采用,因为旧 Session 会因此忽略之后的编辑,恰好在用户最常恢复的 Session 上重现不一致。 + +## Consequences + +- 撤销路由在下一次调用时生效,包括运行中父级的子级;transcript 早先允许的路由现在可能以 `MODEL_ROUTE_NOT_ALLOWED` 被拒绝。 +- 重放 Session 时不能仅凭日志重现其授权;日志中的工具结果仍显示模型看到的内容。 +- Agent 创建不再依赖设置服务,因此无效设置不会阻塞没有委派工具的 Session。 +- `packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts` 中的单元测试固定实时读取、父子 Session 中途编辑生效,以及忽略已记录策略。 diff --git a/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.i18n.yaml b/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.i18n.yaml new file mode 100644 index 0000000000..e5919ec866 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-17-sidebar-scrollbar-fade-in-css.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-17-sidebar-scrollbar-fade-in-css.md +/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition: + en: 9b7623eb8949b421 + zh: d70020274d864676 +/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/problem: + en: 88d0ec7e97d4d94a + zh: 23f3baf3e0a8bdf2 +/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/decision: + en: 5e1bbaf2825ceac7 + zh: 7c39baf282e8d63b +/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/alternatives-considered: + en: 484736bb70e14bbc + zh: 9101a98c7f6be310 +/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/consequences: + en: 63f48085261affd8 + zh: 88db30f2ee8a8928 diff --git a/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.md b/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.md new file mode 100644 index 0000000000..b5bb8a8642 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.md @@ -0,0 +1,39 @@ +# Agent Note: The sidebar scrollbar's delay and fade live in a CSS transition + +Status: implemented + +English | [中文](2026-11-17-sidebar-scrollbar-fade-in-css.zh.md) + +## Problem + +The sidebar draws its scrollbar thumb only while the pointer is over the column. [The pointer-revealed scrollbar note](../../archived/feature/2026-08-04-pointer-revealed-sidebar-scrollbars.md) shipped this with a 2-second JavaScript timer after the leave, and the thumb then vanished in one step. Product review asked for a 500ms hold followed by a visible fade (Issue #7921). That note rejected expressing the delay as a CSS transition; this note reverses that rejection. + +## Decision + +ui-theme registers `--dsh-scrollbar-thumb` and `--dsh-scrollbar-thumb-hover` with `@property` as inherited `` properties whose initial value is `transparent`, so a rebinding of the pair can be transitioned. `SidebarRoot` adds `quietBars` as soon as the pointer is outside the column box and keeps no timer. The `.root.quietBars` rule rebinds both properties to `transparent` with `transition: … 200ms linear 500ms`. The base `.root` rule declares no transition, so a reveal is immediate, and a pointer that returns during the delay removes the class before the colour moves. Under `prefers-reduced-motion: reduce`, the quiet rule sets `transition-duration: 0s`: a zero duration with a non-zero delay still starts a transition, so the thumb holds for 500ms and then switches in one frame. + +The transition runs on the column's custom property, not on a scrollbar pseudo-element. The WebKit thumb's `background: var(--dsh-scrollbar-thumb)` and Firefox's per-element `scrollbar-color` read the property's current animated value at each style update. In Chromium, `apps/web/tests/sidebar-scrollbar.e2e.ts` samples the resolved colour once per animation frame and sees the hold followed by the fade; with the reduced-motion rule removed, the reduced-motion case observes intermediate colours and fails. + +The fade is linear over 200ms, the timing SimpleBar uses. An eased 100ms fade of this pale thumb completes most of its change within a few frames and reads as a cut. + +Inside or outside is decided by the column's box on every `pointerenter` and `pointermove` that reaches the column, because the Settings panel is a fixed-position descendant and the column's menus are React portals: a pointer over them fires no `pointerleave` here while their moves still bubble to the column. The column's own `pointerleave` covers a pointer that leaves the window. + +## Alternatives considered + +**Keep the JavaScript timer and add only a CSS fade.** It needs the same `@property` registration for the fade and keeps a timer, its cancellation, and unmount cleanup in the component. Moving the delay into `transition-delay` removes that state and keeps both timings in one declaration. + +**Leave the properties unregistered.** An unregistered custom property switches in one step, so no transition can hold or fade the colour. + +**Draw an app-owned thumb element and fade its `opacity`.** It gives any fade curve in every engine and costs hit-testing, dragging, wheel, momentum, and hover styling of a replacement scrollbar, which the pointer-revealed scrollbar note already rejected for a cosmetic gain. + +**Hide the bar with `scrollbar-width: none` or `display: none` on `::-webkit-scrollbar`.** It releases the reserved gutter, so revealing the bar would shift every row sideways. + +## Consequences + +The registration is global: every surface that reads the pair now inherits a computed `` instead of the token text, and a value that is not a colour falls back to `transparent` rather than leaving the declaration invalid. Only `.root.quietBars` declares a transition, so other surfaces change neither timing nor colour; the scrollbar geometry golden is unchanged in both palettes. + +The component lost its timer, its document-level listener, and their cleanup. The delay and duration are stated once in the stylesheet, and `scrollbar-quiet-styles.client.spec.ts` pins the exact `transition` value. + +The fade is verified only in Chromium. Safari renders through the same WebKit pseudo-elements; if it does not repaint the thumb during the transition, the thumb holds and then disappears after about 700ms, so the delay still applies without a visible fade. + +A leave during a sidebar collapse or expand hides the thumb at once, because the collapse rule's `transition: width` declaration takes precedence over the quiet rule's. diff --git a/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.zh.md b/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.zh.md new file mode 100644 index 0000000000..6f71491baf --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 侧栏滚动条的延迟与淡出由 CSS 过渡实现 + +Status: implemented + +[English](2026-11-17-sidebar-scrollbar-fade-in-css.md) | 中文 + +## 问题 + +侧栏只在指针位于栏内时绘制滚动条滑块。[指针显示滚动条的 Agent Note](../../archived/feature/2026-08-04-pointer-revealed-sidebar-scrollbars.md) 以离开后 2 秒的 JavaScript 定时器实现了这一行为,之后滑块一步消失。产品评审要求离开后保留 500ms,再明显地淡出(Issue #7921)。那篇 Agent Note 否决了用 CSS 过渡表达延迟;本 Agent Note 推翻这一否决。 + +## 决策 + +ui-theme 通过 `@property` 把 `--dsh-scrollbar-thumb` 与 `--dsh-scrollbar-thumb-hover` 注册为可继承的 `` 属性,初始值为 `transparent`,因此这组变量的重新绑定可以过渡。`SidebarRoot` 在指针一离开栏的矩形范围时就加上 `quietBars`,不再持有定时器。`.root.quietBars` 规则把两个属性重新绑定为 `transparent`,并带有 `transition: … 200ms linear 500ms`。基础 `.root` 规则不声明过渡,因此显示是立即的;指针在延迟期间返回时,class 在颜色变化前就被移除。在 `prefers-reduced-motion: reduce` 下,隐藏规则设置 `transition-duration: 0s`:时长为零而延迟非零时过渡仍会启动,因此滑块保留 500ms 后在一帧内切换。 + +过渡发生在栏元素的自定义属性上,而不是滚动条伪元素上。WebKit 滑块的 `background: var(--dsh-scrollbar-thumb)` 与 Firefox 按元素声明的 `scrollbar-color` 在每次样式更新时读取该属性当前的动画值。在 Chromium 中,`apps/web/tests/sidebar-scrollbar.e2e.ts` 逐个动画帧采样解析后的颜色,能观察到先保留、再淡出;删除减弱动态效果规则后,减弱动态效果用例会观察到中间色并失败。 + +淡出为 200ms 线性,与 SimpleBar 的时序相同。这种浅色滑块若用 100ms 缓动淡出,大部分变化在几帧内完成,看起来像直接消失。 + +栏内或栏外由栏的矩形范围判定,对到达该栏的每次 `pointerenter` 与 `pointermove` 都会判定。原因是设置面板是固定定位的后代,栏的菜单是 React portal:指针位于其上时这里不会触发 `pointerleave`,而它们的移动事件仍会冒泡到栏。栏自身的 `pointerleave` 处理指针离开窗口的情况。 + +## 曾考虑的替代方案 + +**保留 JavaScript 定时器,只用 CSS 做淡出。** 淡出同样需要 `@property` 注册,而组件还要保留定时器、取消逻辑与卸载清理。把延迟移入 `transition-delay` 去掉了这些状态,两个时序也集中在一条声明里。 + +**不注册这两个属性。** 未注册的自定义属性一步切换,任何过渡都无法保留或淡出颜色。 + +**由应用自绘滑块元素并淡出其 `opacity`。** 它在所有引擎上都能实现任意淡出曲线,代价是要为替代滚动条承担命中测试、拖动、滚轮、惯性滚动与 hover 样式,指针显示滚动条的 Agent Note 已因收益只是外观而否决了它。 + +**用 `scrollbar-width: none` 或对 `::-webkit-scrollbar` 设置 `display: none` 隐藏滚动条。** 这会释放预留的滚动条空间,显示滚动条时每一行都会横向移动。 + +## 后果 + +注册是全局的:每个读取这组变量的表面现在继承计算后的 ``,而不是 token 文本;不是颜色的值会回落为 `transparent`,而不是让声明失效。只有 `.root.quietBars` 声明了过渡,因此其他表面的时序与颜色都不变;滚动条几何基准快照在两种配色下均未变化。 + +组件去掉了定时器、document 级监听及其清理。延迟与时长只在样式表中声明一次,`scrollbar-quiet-styles.client.spec.ts` 固定了完整的 `transition` 值。 + +淡出只在 Chromium 中验证过。Safari 通过同样的 WebKit 伪元素绘制;如果它在过渡期间不重绘滑块,滑块会保留并在约 700ms 后消失,延迟依然生效,只是没有可见的淡出。 + +在侧栏折叠或展开过程中离开时,滑块会立即隐藏,因为折叠规则的 `transition: width` 声明优先于隐藏规则的声明。 diff --git a/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.i18n.yaml b/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.i18n.yaml new file mode 100644 index 0000000000..6904cfb962 --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-13-no-new-cordis-root-reads.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.md +/agent-note-prohibit-new-reads-of-the-cordis-root-context: + en: b46331d0804f9d45 + zh: d8b3d8a47541c838 +/agent-note-prohibit-new-reads-of-the-cordis-root-context/problem: + en: c6935cb7ef54f299 + zh: 214ed828b3201539 +/agent-note-prohibit-new-reads-of-the-cordis-root-context/decision: + en: 458cdad9fce26157 + zh: 6ac3b9d7404b4996 +/agent-note-prohibit-new-reads-of-the-cordis-root-context/alternatives-considered: + en: 81d959fa34f3e682 + zh: 861f22528134e255 +/agent-note-prohibit-new-reads-of-the-cordis-root-context/consequences: + en: 6067864f7a2ff1c8 + zh: df4c9af26a1abd5d diff --git a/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.md b/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.md new file mode 100644 index 0000000000..06c269e013 --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.md @@ -0,0 +1,31 @@ +# Agent Note: Prohibit new reads of the Cordis root context + +Status: implemented + +English | [中文](2026-11-13-no-new-cordis-root-reads.zh.md) + +## Problem + +`ctx[Context.root]` returns the application's root context. A property read through it skips the `inject` check, because the root fiber has no runtime; a listener registered on it skips scope filtering; and it reads the root realm instead of the caller's isolate realm. DSH code uses it to read undeclared services, to listen to every Agent's events, to key per-application state, and to call boot APIs that require the root context. Each of these uses has, or needs, a declared replacement: an `inject` entry, `{ global: true }` on a listener, or a service that owns the root-level operation. + +The repository contains such reads across boot, host, preset, protocol, experimental, and test owners. Replacing all of them in one change would combine the enforcement decision with several service designs. + +## Decision + +New reads of the Cordis root context are prohibited in first-party JavaScript and TypeScript, including tests, fixtures, and scripts. The [checker](../../../../scripts/verify-cordis-root.ts), exposed as `pnpm run verify-cordis-root`, uses the TypeScript syntax tree and a type checker over each file alone. A read names the root symbol through a Cordis value binding of `Context` or `symbols`: `.root`, `['root']`, or `root` destructured in a declaration, a parameter default, or an assignment. A binding comes from `@deepseek-ai/cordis` or one of its subpaths through a static import, including renamed, default, namespace, and `import =` forms, or through a destructured or namespace `import()` or `require()` result; a local that shadows the import is not a binding. Any string literal whose value is exactly `cordis.root`, the key behind `Symbol.for('cordis.root')`, is also a read. Type positions, interfaces, type aliases, ambient declarations, comments, other strings, and source text embedded in a template are not reads. + +Existing reads have an exact baseline in `scripts/cordis-root.baseline.json`, kept by [the shared inventory module](../../../../scripts/baseline-inventory.ts) under the rules of the [unknown-cast inventory](2026-09-19-no-unknown-casts.md): baseline edits only delete entries or decrease counts, `--prune` removes retired entries and refuses to write while new reads exist, and no command adds an allowance. A read's fingerprint covers the tokens of the element access whose key is the root symbol, so a recorded read moved to another receiver is a new finding. + +Files that exercise the root contract itself are listed with a reason in `CORDIS_ROOT_EXEMPTIONS` inside the checker and are not scanned: the Cordis rc.12 specification and the checker. An exemption whose file no longer reads the root fails the gate. Vendored sources and frozen archived Agent Notes keep their inventory exclusions. The checker runs in CI static and primary modes and the local `hygiene` and `check-all` profiles in [the gate runner](../../../../scripts/run-gates.ts). The [defensive pattern](../../../../docs/defensive-patterns/general.md#plugins-do-not-read-the-cordis-root-context) states the rule and its replacements for authors, and the gate's rejection message links it. + +## Alternatives considered + +**Replace every existing read before enforcing the rule.** Rejected because several replacements need new services, such as a profile-composition service for the boot APIs and an application-lifecycle signal; enforcing first stops new reads while those designs are reviewed separately. + +**Use the `no-restricted-properties` lint rule.** Rejected because it matches the identifier `Context` by name, so a renamed import such as `CordisContext` passes, and it cannot match `Symbol.for('cordis.root')`. + +**Record the exempt files in the baseline.** Rejected because the baseline only shrinks, while the exempt files are expected to keep their reads; keeping them apart lets the baseline reach empty. + +## Consequences + +Owners must remove a recorded read before changing its receiver or moving it into an unlisted file, and prune its entry after removal. Passing the check establishes that no unlisted syntactic root read exists. It does not detect a root context obtained through another value, such as a stored reference, an alias of `Context`, a service that returns it, or code assembled from strings at runtime. diff --git a/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.zh.md b/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.zh.md new file mode 100644 index 0000000000..bb0679dea1 --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 禁止新增对 Cordis 根上下文的读取 + +Status: implemented + +[English](2026-11-13-no-new-cordis-root-reads.md) | 中文 + +## 问题 + +`ctx[Context.root]` 返回应用的根上下文。通过它读取属性会跳过 `inject` 检查,因为根 fiber 没有 runtime;在它上面注册的监听器会跳过 scope 过滤;它读取的是根 realm,而不是调用方所在的 isolate realm。DSH 代码用它读取未声明的服务、监听所有 Agent 的事件、作为应用级状态的键,以及调用要求根上下文的启动 API。这些用法都已有或需要一个显式声明的替代方式:`inject` 条目、监听器上的 `{ global: true }`,或负责根级操作的服务。 + +仓库中的此类读取分布在 boot、host、preset、protocol、experimental 和测试等多个所有者中。在一次变更中全部替换,会把执行规则的决定与多个服务设计混在一起。 + +## 决定 + +第一方 JavaScript 和 TypeScript(包括测试、fixture 和脚本)禁止新增对 Cordis 根上下文的读取。[检查器](../../../../scripts/verify-cordis-root.ts)通过 `pnpm run verify-cordis-root` 运行,使用 TypeScript 语法树,并对每个文件单独建立类型检查器。读取指通过 `Context` 或 `symbols` 的 Cordis 值绑定访问根符号:`.root`、`['root']`,或在声明、参数默认值或赋值中解构出的 `root`。绑定来自 `@deepseek-ai/cordis` 或其子路径,可以是静态导入(包括重命名、默认、命名空间和 `import =` 形式),也可以是解构或整体接收的 `import()` 或 `require()` 结果;遮蔽导入的局部变量不是绑定。值恰为 `cordis.root` 的任何字符串字面量也算读取,即 `Symbol.for('cordis.root')` 背后的键。类型位置、接口、类型别名、ambient 声明、注释、其他字符串以及嵌入模板中的源码文本不算读取。 + +现有读取使用 `scripts/cordis-root.baseline.json` 中的精确基线记录,由[共享清单模块](../../../../scripts/baseline-inventory.ts)按 [unknown 类型断言清单](2026-09-19-no-unknown-casts.zh.md)的规则维护:基线修改只能删除条目或减少次数,`--prune` 删除已失效的条目并在存在新读取时拒绝写入,且没有任何命令可以添加放行。读取的指纹覆盖以根符号为键的元素访问的 token,因此把已记录的读取换到另一个接收者上会产生新的检查发现。 + +测试根上下文约定本身的文件在检查器内的 `CORDIS_ROOT_EXEMPTIONS` 中逐个列出并注明原因,不参与扫描:Cordis rc.12 规范测试和检查器本身。若豁免文件不再读取根上下文,门禁失败。vendored 源码和已冻结的归档 Agent Notes 保留清单的排除规则。检查器参与[门禁运行器](../../../../scripts/run-gates.ts)中的 CI static 和 primary 模式以及本地 `hygiene` 和 `check-all` 配置。[防御性模式](../../../../docs/defensive-patterns/general.zh.md#plugins-do-not-read-the-cordis-root-context)为作者写明该规则及替代方式,门禁的拒绝信息链接到这一节。 + +## 考虑过的替代方案 + +**在执行规则前替换所有现有读取。** 已否决,因为部分替换需要新的服务,例如供启动 API 使用的 profile 组合服务和应用生命周期信号;先执行规则可以阻止新增读取,同时单独评审这些设计。 + +**使用 `no-restricted-properties` lint 规则。** 已否决,因为它按名称匹配标识符 `Context`,重命名导入(如 `CordisContext`)可以绕过,而且无法匹配 `Symbol.for('cordis.root')`。 + +**把豁免文件记入基线。** 已否决,因为基线只会缩小,而豁免文件预期会保留其读取;分开维护可以让基线最终清空。 + +## 影响 + +所有者在更换已记录读取的接收者或将其移入未登记的文件之前,必须先移除该读取,并在移除后裁剪其条目。通过此检查表明不存在未登记的语法层面的根读取。它无法检测通过其他值获得的根上下文,例如保存的引用、`Context` 的别名、返回根上下文的服务,或运行时由字符串拼装的代码。 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml index db6139954a..9346ae7076 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml @@ -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 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md index cb7ad564cd..86111905d8 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md @@ -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. diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md index fd5a6c3f45..8b779d84cc 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md @@ -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`;完整浏览器登录路径由源码追踪确认。 diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml new file mode 100644 index 0000000000..012f82ab67 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-11-15-client-config-sync-migration.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/proposed/architecture/2026-11-15-client-config-sync-migration.md +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync: + en: 5f71cf603f0c5013 + zh: 3976607b283e68dc +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/problem: + en: 38add9dc3b90ad7e + zh: 867e351401f537bc +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal: + en: 986dd8097aac4d3d + zh: 986dd8097aac4d3d +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/inventory: + en: 08dae763d773f24a + zh: 15b4bd80b4973dff +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/migration-rules: + en: 72202ccc050d7e35 + zh: a809ee548e005fcb +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/order: + en: 8b8ded15f43056c0 + zh: 3ea6067ed0c3310c +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/open-questions: + en: 103a6b7dca054eb4 + zh: 55b0881eca3e08ac +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/alternatives-considered: + en: a00b894cbcff0c34 + zh: 7f2a83f36df109ec +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/acceptance-criteria: + en: 15597a6f656e7268 + zh: f17a1cfcbef0fcbd +/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/risks: + en: 8f5e523d526b2026 + zh: 34a61d7c19df8650 diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md new file mode 100644 index 0000000000..ba52a8881c --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md @@ -0,0 +1,66 @@ +# Agent Note: Migrate existing browser configuration reads to configuration sync + +Status: proposed + +English | [中文](2026-11-15-client-config-sync-migration.zh.md) + +## Problem + +Before [browser plugin configuration sync](../../implemented/architecture/2026-11-15-client-config-sync.md), every package whose browser face needs Host configuration implemented its own read. These reads take effect only at page load, duplicate injection code, or use the settings editing channel as a runtime read channel. This Note inventories them and plans their migration; nothing runs before the architecture lands. + +## Proposal + +### Inventory + +| Category | Use | Packages | +|---|---|---| +| A. Page globals carry Host configuration | `webserver/index-inject` writes `window.__DSH_*__`, read once when the browser loads | `shortcuts`, `ui-sidebar-documentpreview`, `ui-account-notifications`, `ui-settings-models` (onboarding), `ui-settings-account` (contact details), `connection` (recovery parameters) | +| B. Runtime values read through `configForms` | The browser subscribes to accepted values of its own or another entry through the settings mirror | `ui-chat`, `ui-conversation`, `locale`, `ui-theme`, `ui-settings-account`, `ui-settings-general`, `ui-agent-preset`, experimental `timeline`, `client-ui-cot-translation`, `client-ui-forge`, `cua` | +| C. `Config` declared only on the Client face | The browser exports a schema, but the entry never receives configuration | Done in the architecture PR: `ui-context-menu` `resolutionTimeoutMs` and `ui-conversation` `maxConcurrentFileUploads` are top-level volatile fields of their Host schemas, and the Client schemas are removed | +| D. First-paint pre-injection | The page HTML pre-injects values to avoid a first-paint flash | `ui-theme` palette and font sizes | +| E. Settings editing | Settings pages edit inherited values, overrides, revisions, and writability | every `ui-settings-*` card | + +### Migration rules + +| Category | Handling | +|---|---| +| A | Make the fields volatile and move the `Config` type to `src/types.ts`; the browser reads `SyncedConfig`; remove the matching `index-inject` row and global. Confirm per field that its meaning can become "changes at runtime"; `connection` needs its recovery parameters before Connection itself activates and is assessed separately | +| B | Plugins reading their own entry read `SyncedConfig`; `configForms` keeps only writes and settings presentation. Reads of another entry's values (for example `ui-agent-preset` reading `ui-settings`) can use the read-only `ctx.config.resolveConfigByPackage(packageName)` | +| C | Remove the browser schema and `Config` export, move the type to `src/types.ts`, and declare a volatile schema on the Host face | +| D | Unchanged; the runtime part can be migrated separately | +| E | Outside this migration; adjusting the settings package and `configForms` is discussed separately once the configuration sync architecture is stable | + +### Order + +1. The architecture Note is implemented and merged. +2. Category C (no behavior dependency; exercises the mechanism). +3. Category A, one package at a time. +4. Category B, own reads first, then cross-plugin reads. +5. A separate Note for the overall adjustment of settings and `configForms`. + +### Open questions + +- Which fields each package makes volatile. +- Whether cross-plugin reads move to types inferred per package name through declaration merging. +- The first-render timing of `connection` recovery parameters and bootstrap rows. + +## Alternatives considered + +| Rejected | Reason | +|---|---| +| Migrating in the architecture PR | Widens the review and mixes mechanism questions with per-package semantics | +| Keeping page globals as a long-term parallel channel | Keeps two configuration sources and duplicated injection code | + +## Acceptance criteria + +- Category A and C packages no longer export a browser `Config` schema or read Host configuration globals. +- Category B plugins that read their own configuration no longer rely on `configForms` for runtime reads. +- After migration, a Host change to the matching volatile field takes effect without a page reload. + +## Risks + +| Risk | Description | +|---|---| +| Changed meaning | Values that took effect only at load become runtime-changeable, and plugins must support live updates | +| Pinned configuration | Making a field volatile brings it into the settings form's profile row, subject to the pinning rules in [profile-owned live configuration](../../implemented/architecture/2026-09-19-profile-owned-live-configuration.md) | +| First-render timing | `connection` needs its recovery parameters before it activates, earlier than synced configuration can take part | diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md new file mode 100644 index 0000000000..4714b909ff --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md @@ -0,0 +1,66 @@ +# Agent Note: 现有前端配置读取迁移到配置同步 + +Status: proposed + +[English](2026-11-15-client-config-sync-migration.md) | 中文 + +## Problem + +[前端插件配置同步](../../implemented/architecture/2026-11-15-client-config-sync.zh.md)落地前,浏览器需要 Host 配置的包各自实现了读取方式。这些方式只在页面加载时生效、复制注入代码,或把设置编辑通道当成运行时读取通道。本 Note 盘点这些用法并规划收编;架构落地前不执行。 + +## Proposal + +### 盘点 + +| 类别 | 用法 | 包 | +|---|---|---| +| A. 页面全局变量下发 Host 配置 | `webserver/index-inject` 写 `window.__DSH_*__`,前端加载时读一次 | `shortcuts`、`ui-sidebar-documentpreview`、`ui-account-notifications`、`ui-settings-models`(引导)、`ui-settings-account`(联系方式)、`connection`(恢复参数) | +| B. 以 `configForms` 读取运行时值 | 前端经设置镜像订阅自身或他人条目的已接受值 | `ui-chat`、`ui-conversation`、`locale`、`ui-theme`、`ui-settings-account`、`ui-settings-general`、`ui-agent-preset`、实验包 `timeline`、`client-ui-cot-translation`、`client-ui-forge`、`cua` | +| C. 只在前端声明的 `Config` | 前端导出 schema,但条目从不收到配置 | 已在架构 PR 中完成:`ui-context-menu` 的 `resolutionTimeoutMs` 与 `ui-conversation` 的 `maxConcurrentFileUploads` 已改为 Host 顶层 volatile 字段,前端 schema 已删除 | +| D. 首屏预注入 | 页面 HTML 预注入以避免首屏闪烁 | `ui-theme` 调色板与字号 | +| E. 设置编辑 | 设置页编辑继承值、覆盖值、修订号、可写性 | 各 `ui-settings-*` 卡片 | + +### 收编规则 + +| 类别 | 处理 | +|---|---| +| A | 字段改为 volatile,`Config` 类型移入 `src/types.ts`;前端改读 `SyncedConfig`;删除对应 `index-inject` 与全局变量。需逐字段确认语义可以变为「运行时可变」;`connection` 恢复参数在 connection 自身激活前就需要,须单独评估 | +| B | 读取自身条目的插件改读 `SyncedConfig`;`configForms` 只保留写入与设置页呈现。读取他人条目的值(例如 `ui-agent-preset` 读 `ui-settings`)可改用只读的 `ctx.config.resolveConfigByPackage(packageName)` | +| C | 前端删除 schema 与 `Config` 导出,类型移入 `src/types.ts`,Host 面声明 volatile schema | +| D | 保持不变;运行时变化部分可另行收编 | +| E | 不在本迁移范围;settings 包与 `configForms` 的调整在配置同步架构稳定后另行讨论 | + +### 顺序 + +1. 架构 Note 实现完成并合入。 +2. 类别 C(无行为依赖,验证机制)。 +3. 类别 A,逐包进行。 +4. 类别 B,先自身读取、后跨插件读取。 +5. settings 与 `configForms` 的整体调整另起 Note。 + +### 未决 + +- 每个包选择哪些字段改为 volatile。 +- 跨插件读取是否升级为按包名声明合并推导类型。 +- `connection` 恢复参数与 bootstrap 行的首屏时序。 + +## Alternatives considered + +| Rejected | 理由 | +|---|---| +| 与架构同一 PR 迁移 | 扩大评审面,机制问题与逐包语义问题混在一起 | +| 保留页面全局变量作为长期并行通道 | 维持两套配置来源与重复注入代码 | + +## Acceptance criteria + +- 类别 A、C 的包不再导出前端 `Config` schema 或读取 Host 配置全局变量。 +- 类别 B 中读取自身配置的插件不再依赖 `configForms` 做运行时读取。 +- 迁移后 Host 修改对应 volatile 字段无需刷新页面即生效。 + +## Risks + +| 风险 | 说明 | +|---|---| +| 语义变化 | 原本只在加载时生效的值变为运行时可变,插件需支持热更新 | +| 配置钉住 | 字段改为 volatile 会使设置表单把它纳入 profile 行,受[实时配置](../../implemented/architecture/2026-09-19-profile-owned-live-configuration.zh.md)中的钉住规则影响 | +| 首屏时序 | `connection` 在自身激活前就需要恢复参数,早于同步配置能参与的时间点 | diff --git a/.agents/skills/dsh-client-ui-ux/references/icons.md b/.agents/skills/dsh-client-ui-ux/references/icons.md index 5d9bbefb19..9ab34ff607 100644 --- a/.agents/skills/dsh-client-ui-ux/references/icons.md +++ b/.agents/skills/dsh-client-ui-ux/references/icons.md @@ -25,7 +25,7 @@ A shared view-box change affects every consumer at its own CSS size. Inspect bot For softness, check CSS dimensions and ancestor transforms, view box and drawing bounds, stroke versus filled contour, device-pixel placement, then color/opacity. Non-16 view boxes are valid; compare identical artwork before attributing sharpness to inline SVG versus sprites. -Use the [implemented stroke behavior](../../../../packages/client/ui-primitives/README.md#controls-and-icons): source stroke widths scale with the SVG viewport, and filled outlines scale as geometry. Do not add non-scaling strokes or convert filled contours during an ordinary placement or reuse fix. A change to that rendering contract belongs to a separately scoped library change with consumer validation; retain intentional silhouettes and knockouts. +Use the [implemented stroke behavior](../../../../packages/client/ui-primitives/README.md#controls-and-icons): Regular line artwork retains a 1 CSS pixel stroke and Medium retains 1.3 CSS pixels as the viewport changes. Shared and inline line artwork use non-scaling strokes; intentional fills scale as geometry. Do not change that rendering behavior or convert filled contours during an ordinary placement or reuse fix. Library rendering changes require consumer validation; retain intentional silhouettes and knockouts. Check straight-stroke edges at actual DPR after all scaling: center and width jointly determine coverage. Integer source coordinates alone do not guarantee crisp edges. Round positioned overlays in device pixels only when layout places otherwise crisp artwork between pixels; preserve anchoring and viewport containment. Keep antialiasing on curves/diagonals; do not globally round paths or use `crispEdges` to hide placement errors. Partial coverage is legitimate for 1.3px strokes. diff --git a/.github/review-ownership/README.md b/.github/review-ownership/README.md index 79103f593a..2bf7804c71 100644 --- a/.github/review-ownership/README.md +++ b/.github/review-ownership/README.md @@ -18,9 +18,9 @@ The [`weighted-approval` workflow](../workflows/weighted-approval.yml) publishes The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. The publisher marks the head pending before Python setup or lexer installation, so failed setup or an interrupted history fetch cannot leave a previous success in place. Setup and evaluation failures publish an error status. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status. The publisher also writes a `weighted approval decision` check run that reports the same decision as a conclusion — `action_required` while the policy is unmet, `success` when it holds, and `failure` on setup or evaluation failures — with the score or blocker in its title. Branch rules do not require that check run, so it never blocks a merge; it names the blocked state beside the status that gates the merge. The check run is published with a token minted from a dedicated approval App (`DSH_APPROVAL_APP_CLIENT_ID`, `DSH_APPROVAL_APP_PRIVATE_KEY`, `DSH_APPROVAL_APP_SLUG`, scope `checks: write`): GitHub attaches a check run created with the job token to the earliest Actions check suite on the head, and when that suite belongs to this `pull_request_target` workflow the merge box omits it, so the App identity makes the association stable. The App publishes only runs whose `app.slug` is the App; job-token runs from earlier evaluations stay untouched and can coexist on a head. When the token or slug is missing, the publisher falls back to the job token and updates job-token runs only, which keeps the label on the Checks page. The App token step runs with `continue-on-error`, so a missing App configuration fails only that step and leaves the job-token fallback; a failed check-run write is logged by the publisher and never changes the status. -Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@imccyu`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count. +Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@CreatixChu`, `@imccyu`, `@LegGasai`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count. -The PR author contributes `min(100, mergedPRCount) × 11 / 1000` points: 0 merged PRs → 0 points, 50 → 0.55, and 100 or more → 1.1. The publisher counts only merged PRs in this repository using the author’s immutable account ID, excluding the current PR. It stops at 100 matches and rejects incomplete history responses. Counts refresh at the next subscribed evaluation event. Author credit is separate from reviewer approvals and cannot satisfy the two-point requirement alone; the author’s own review remains excluded. Human and bot authors, including Dependabot, use the same rule. Drafts, blocking reviews, and sufficient reviewer points skip history lookup; logs mark credit as not evaluated. Otherwise, logs show author credit and the capped count separately. Below the cap, counting may scan the repository’s entire merged history; a failed required lookup publishes an error. +The PR author contributes `min(100, mergedPRCount) × 11 / 1000` points: 0 merged PRs → 0 points, 50 → 0.55, and 100 or more → 1.1. The publisher counts only merged PRs in this repository using the author’s immutable account ID, excluding the current PR. It stops at 100 matches and rejects incomplete history responses. Counts refresh at the next subscribed evaluation event. Author credit is separate from reviewer approvals and cannot satisfy the two-point requirement alone; the author’s own review remains excluded. Human and bot authors, including Dependabot, use the same rule, except that PRs authored by `@turtle2099` receive a fixed 0.2 points without a history lookup. Drafts, blocking reviews, and sufficient reviewer points skip history lookup; logs mark credit as not evaluated. Otherwise, logs show author credit and the capped count, or the fixed credit, separately. Below the cap, counting may scan the repository’s entire merged history; a failed required lookup publishes an error. A one-point approval receives weight `min(2, 1 + 4 × ownedLines / totalLines)` from modified or deleted old production-code lines, attributed by `git blame` at the merge base of the live base branch and exact reviewed head. Ownership of 0%, 12.5%, and 25% gives 1, 1.5, and 2 points; higher ownership remains capped at 2. The success threshold remains 2 total points, without rounding the score. New lines do not enter the denominator, and an empty denominator gives no boost. Existing two-point weights remain unchanged. GitHub commit-author accounts identify reviewers across author emails; unlinked authors remain in the denominator without contributing to a reviewer. The publisher logs measured ownership. It skips attribution when reviewer points plus author credit already meet the threshold or a blocking review exists. Displayed scores use at most three decimal places; the decision uses unrounded scores with a tolerance of `1e-12` points for floating-point error. The curve endpoints come from the policy’s default and required points. diff --git a/.github/review-ownership/approval-policy.json b/.github/review-ownership/approval-policy.json index 9ecc46ff5b..ebd0453a99 100644 --- a/.github/review-ownership/approval-policy.json +++ b/.github/review-ownership/approval-policy.json @@ -3,7 +3,9 @@ "defaultPoints": 1, "reviewerPoints": { "07akioni": 2, + "CreatixChu": 2, "imccyu": 2, + "LegGasai": 2, "tianyicui": 2, "tianyicui-bot": 2, "turtle1999": 2, diff --git a/.github/review-ownership/author-weight.mjs b/.github/review-ownership/author-weight.mjs index 21b9cafcae..0fda0c4b8a 100644 --- a/.github/review-ownership/author-weight.mjs +++ b/.github/review-ownership/author-weight.mjs @@ -1,5 +1,7 @@ -/** Author credit from merged pull requests in the same repository. */ +/** Author credit from merged pull requests in the same repository, or fixed points for listed logins. */ const CAP_COUNT = 100 +/** Author points that replace merged-history credit, keyed by lowercase login. */ +export const FIXED_AUTHOR_POINTS = new Map([['turtle2099', 0.2]]) /** * Convert merged PR count to author points, capped at 1.1. diff --git a/.github/review-ownership/check-approval.mjs b/.github/review-ownership/check-approval.mjs index d876e8e8c3..2f27f5aff1 100644 --- a/.github/review-ownership/check-approval.mjs +++ b/.github/review-ownership/check-approval.mjs @@ -5,7 +5,7 @@ import process from 'node:process' import { pathToFileURL } from 'node:url' import { productionOwnership, LOGIN } from './blame-ownership.mjs' -import { authorCreditPoints, countMergedAuthorPulls } from './author-weight.mjs' +import { FIXED_AUTHOR_POINTS, authorCreditPoints, countMergedAuthorPulls } from './author-weight.mjs' const API_VERSION = '2026-03-10' const MAX_PULL_REQUEST_RECORDS = 3_000 @@ -211,7 +211,7 @@ function timestamp(value, subject) { /** * Evaluate approval points from current reviews and repository permissions. * @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise, getOwnership?: typeof productionOwnership, getMergedCount?: typeof countMergedAuthorPulls}} options Runtime inputs. - * @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, authorCredit: {mergedCount: number, points: number} | null, requiredPoints: number, approvals: Array<{login: string, points: number, delegatedTo?: string, ownership?: {ownedLines: number, totalLines: number}}>, delegations: Array<{login: string, delegatedTo: string, commentId: number, reviewIds: number[], approved: boolean}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields; approval login owns the points, delegatedTo supplies its decision, delegations contains eligible active commands and their superseded decision review IDs, and null author credit means history was not evaluated. + * @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, authorCredit: {mergedCount: number | null, points: number} | null, requiredPoints: number, approvals: Array<{login: string, points: number, delegatedTo?: string, ownership?: {ownedLines: number, totalLines: number}}>, delegations: Array<{login: string, delegatedTo: string, commentId: number, reviewIds: number[], approved: boolean}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields; approval login owns the points, delegatedTo supplies its decision, delegations contains eligible active commands and their superseded decision review IDs, null author credit means credit was not evaluated, and null mergedCount means fixed author points. */ export async function evaluateApproval({ event, policySource, api, getOwnership = productionOwnership, getMergedCount = countMergedAuthorPulls }) { const pull = pullRequestFromEvent(event) @@ -264,8 +264,9 @@ export async function evaluateApproval({ event, policySource, api, getOwnership let authorCredit = null const reviewerPoints = approvals.reduce((sum, approval) => sum + approval.points, 0) if (blockers.length === 0 && reviewerPoints < policy.requiredPoints) { - const mergedCount = await getMergedCount(pull, api) - authorCredit = { mergedCount, points: authorCreditPoints(mergedCount) } + const fixedPoints = FIXED_AUTHOR_POINTS.get(pull.author.toLowerCase()) + const mergedCount = fixedPoints === undefined ? await getMergedCount(pull, api) : null + authorCredit = { mergedCount, points: fixedPoints ?? authorCreditPoints(mergedCount) } } const pointsBeforeOwnership = reviewerPoints + (authorCredit?.points ?? 0) if (blockers.length === 0 && pointsBeforeOwnership < policy.requiredPoints @@ -338,7 +339,7 @@ export async function runApprovalCheck({ event, policySource, api, checkApi = ap throw error } write(result.authorCredit - ? `Author credit: ${result.authorCredit.points} (${result.authorCredit.mergedCount} merged PRs).` + ? `Author credit: ${result.authorCredit.points} (${result.authorCredit.mergedCount === null ? `fixed for @${pull.author}` : `${result.authorCredit.mergedCount} merged PRs`}).` : `Author credit: not evaluated (${pull.draft ? 'draft' : result.blockers.length ? 'blocking review' : 'reviewer points suffice'}).`) write(`Approval score: ${result.points}/${result.requiredPoints}.`) writeList(write, 'Counted approvals', result.approvals.map(({ login, points, ownership, delegatedTo }) => diff --git a/.github/review-ownership/check-approval.test.mjs b/.github/review-ownership/check-approval.test.mjs index cf5f74583e..945323dcf5 100644 --- a/.github/review-ownership/check-approval.test.mjs +++ b/.github/review-ownership/check-approval.test.mjs @@ -45,7 +45,9 @@ test('loads the repository approval score policy', () => { assert.equal(policy.defaultPoints, 1) assert.deepEqual([...policy.reviewerPoints], [ ['07akioni', 2], + ['creatixchu', 2], ['imccyu', 2], + ['leggasai', 2], ['tianyicui', 2], ['tianyicui-bot', 2], ['turtle1999', 2], @@ -668,6 +670,21 @@ for (const [mergedCount, credit] of [[0, 0], [1, 0.011], [50, 0.55], [99, 1.089] }) } +test('turtle2099 contributes fixed author points without a history lookup', async () => { + const output = [] + const result = await runApprovalCheck({ + event: pullRequestEvent({ author: 'Turtle2099' }), policySource, runUrl: 'https://github.example/run/1', + getMergedCount: async () => { throw new Error('fixed author credit must skip history') }, + getOwnership: async () => ({ totalLines: 10, reviewerLines: { writer: 2 } }), + api: async path => path.includes('/reviews?') ? [review('writer', 'APPROVED')] : { permission: 'write' }, + write: line => output.push(line), + }) + assert.deepEqual(result.authorCredit, { mergedCount: null, points: 0.2 }) + assert.equal(result.approvals[0].points, 1.8) + assert.equal(result.state, 'success') + assert.ok(output.includes('Author credit: 0.2 (fixed for @Turtle2099).')) +}) + test('combines author credit and reviewer ownership at the passing threshold', async () => { for (let mergedCount = 0; mergedCount <= 90; mergedCount++) { const result = await evaluateApproval({ diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index adff87f633..fb625e0d85 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -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 = // +// Reminders posted before closing existed use `stale-pr-reminder` and announce no closing, so they are ignored. +const MARKER = // // 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 [ - ``, - `@${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 `\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} [options.sleep] Delay between comments. * @returns {Promise} */ -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}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index cb2d56b437..c6033e1fc5 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -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, '\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, /^\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, /^\n@author This pull request has had no activity for 14 days\./) + assert.match(comments[3].body, /^\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) }) diff --git a/.github/workflows/pr-check-on-head-branch.yml b/.github/workflows/pr-check-on-head-branch.yml index 7882c35d5b..f2d36b10af 100644 --- a/.github/workflows/pr-check-on-head-branch.yml +++ b/.github/workflows/pr-check-on-head-branch.yml @@ -87,8 +87,26 @@ jobs: if ! git merge-base "$HEAD_SHA" "$BASE_SHA" >/dev/null; then stop "the pull request shares no commit with $BASE_SHA within 150 commits of history, so nothing was merged or compiled; merge master into it and push, then this check runs again" fi - git -c user.name=pr-check -c user.email=pr-check@users.noreply.github.com merge --no-ff --no-edit -m "Merge $BASE_SHA into $HEAD_SHA" "$BASE_SHA" || - stop "the pull request cannot merge $BASE_SHA; merge master into it and push, then this check runs again" + # The blobless history makes Git fetch missing blobs from origin on demand. Within one process, Git's cache of + # loose-object directories does not see the merged blobs it writes, so a single `git merge` asks origin for + # them while it checks out the result, and origin, which has never seen them, refuses the whole fetch. + # The merge is computed by `git merge-tree` and checked out by a separate process, which rereads the + # directories. + set +e + merge_output=$(git merge-tree --write-tree "$HEAD_SHA" "$BASE_SHA") + merge_status=$? + set -e + if [ "$merge_status" -eq 1 ]; then + echo "$merge_output" + stop "the pull request conflicts with $BASE_SHA; merge master into it and push, then this check runs again" + fi + if [ "$merge_status" -ne 0 ]; then + stop "git merge-tree could not merge $BASE_SHA (exit $merge_status), so nothing was compiled" + fi + merge_commit=$(git -c user.name=pr-check -c user.email=pr-check@users.noreply.github.com commit-tree "${merge_output%%$'\n'*}" -p "$HEAD_SHA" -p "$BASE_SHA" -m "Merge $BASE_SHA into $HEAD_SHA") || + stop "the merged tree of $BASE_SHA could not be committed, so nothing was compiled" + git checkout --quiet --detach "$merge_commit" || + stop "the merged tree of $BASE_SHA could not be checked out, so nothing was compiled" echo "merged=true" >> "$GITHUB_OUTPUT" - uses: pnpm/action-setup@v5.0.0 diff --git a/.github/workflows/stale-pull-requests.yml b/.github/workflows/stale-pull-requests.yml index a0ccb7f2b5..db1c3f8115 100644 --- a/.github/workflows/stale-pull-requests.yml +++ b/.github/workflows/stale-pull-requests.yml @@ -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 }) diff --git a/AGENTS.md b/AGENTS.md index 37b385c8bb..f4b150a8df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,7 @@ packages/ @deepseek-ai/dsh- workspaces at packages/// identity/ anonymous identity settings/ user settings credentials/ credentials/authorization + account/ DeepSeek acp/ automation-only ACP interaction/ human interaction boot/ application boot diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 26cf2d417e..70a888ec00 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -51,6 +51,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`@lexical/text`](https://github.com/facebook/lexical) | MIT | | [`@lexical/utils`](https://github.com/facebook/lexical) | MIT | | [`@modelcontextprotocol/client`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT | +| [`@modelcontextprotocol/core`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT | | [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT | | [`@modelcontextprotocol/server`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT | | [`@noble/hashes`](https://github.com/paulmillr/noble-hashes) | MIT | diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index a035a44693..741c64c21d 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -12,8 +12,8 @@ en: cc03e6b75206661b zh: 99e41f4143198352 /deepseek-ai-dsh/profiles: - en: 523477a093beb0c2 - zh: f88ea21e5fbea969 + en: 85171337ac2fb2ff + zh: 705a4eef97d9b519 /deepseek-ai-dsh/optional-overlays: en: 3a40ddc44e55f79c zh: 8d3949132e1ef93c diff --git a/apps/cli/README.md b/apps/cli/README.md index 644eba2aa5..4a5dd73e04 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -34,7 +34,7 @@ dsh --help # the launcher's own help ## Profiles -A profile directory holds a `package.json` (out-of-tree plugin dependencies plus the profile manifest `dsh.profile` with its ordered `bundles` list) and a `cordis.patch.yml` (the user's own patch layer). `dsh-hmr`, when enabled in YAML, watches the profile manifest and both profile and home patch files, then recomposes all layers through one serialized reload. Without HMR, changes apply on restart. Edits arriving during watcher registration use the same nonfatal reload reporting as later edits. [Plugin Manager](../../packages/boot/plugin-manager/README.md) shares package operations and the profile write lock with `dsh plugin`; package updates retain disabled bundle selections. CLI package commands inherit authentication variables and terminal descriptors, including interactive build approval; service calls retain their scrubbed environment and captured diagnostics. +A profile directory holds a `package.json` (out-of-tree plugin dependencies plus the profile manifest `dsh.profile` with its ordered `bundles` list) and a `cordis.patch.yml` (the user's own patch layer). `dsh-hmr`, when enabled in YAML, watches the profile manifest, the profile and home patch files, and every `--patch` overlay file, then recomposes all layers through one serialized reload. Without HMR, changes apply on restart, except that a Config Editor save applies the current contents of every patch and overlay file. Edits arriving during watcher registration use the same nonfatal reload reporting as later edits. [Plugin Manager](../../packages/boot/plugin-manager/README.md) shares package operations and the profile write lock with `dsh plugin`; package updates retain disabled bundle selections. CLI package commands inherit authentication variables and terminal descriptors, including interactive build approval; service calls retain their scrubbed environment and captured diagnostics. Installation and profile startup enforce the declared `engines.dsh` range, or DSH peer ranges when it is absent, against the same runtime version shown by `dsh --version`. Incompatible plugins require an explicitly acknowledged exact-version exemption. The [plugin manager's compatibility reference](../../packages/boot/plugin-manager/README.md#version-compatibility-and-exemptions) documents `version-exemptions`, `allow-version`, `revoke-version`, persistence, and risks. diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 318e12440f..5d0ce78b86 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -34,7 +34,7 @@ dsh --help # the launcher's own help ## Profile -profile 目录包含一个 `package.json`,其中记录树外插件依赖,以及 profile manifest(元数据清单)`dsh.profile`、其中按顺序排列的 `bundles` 列表;还包含一个 `cordis.patch.yml`,其中保存用户自己的 patch 层。在 YAML 中启用的 `dsh-hmr` 监视 profile manifest、profile 与 home 级 patch 文件,再通过统一串行重载重新组合所有层。未启用 HMR 时,更改在重启后生效。监听器注册期间发生的编辑与后续编辑使用相同的非致命重载错误报告。[插件管理器](../../packages/boot/plugin-manager/README.zh.md) 与 `dsh plugin` 共享包操作和 profile 写锁;更新依赖会保留已停用的组合包选择。CLI 包操作继承认证环境和终端描述符,支持交互式构建批准;service 调用保留清理后的环境并捕获诊断。 +profile 目录包含一个 `package.json`,其中记录树外插件依赖,以及 profile manifest(元数据清单)`dsh.profile`、其中按顺序排列的 `bundles` 列表;还包含一个 `cordis.patch.yml`,其中保存用户自己的 patch 层。在 YAML 中启用的 `dsh-hmr` 监视 profile manifest、profile 与 home 级 patch 文件以及每个 `--patch` overlay 文件,再通过统一串行重载重新组合所有层。未启用 HMR 时,更改在重启后生效;例外是 Config Editor 保存时会应用所有 patch 与 overlay 文件的当前内容。监听器注册期间发生的编辑与后续编辑使用相同的非致命重载错误报告。[插件管理器](../../packages/boot/plugin-manager/README.zh.md) 与 `dsh plugin` 共享包操作和 profile 写锁;更新依赖会保留已停用的组合包选择。CLI 包操作继承认证环境和终端描述符,支持交互式构建批准;service 调用保留清理后的环境并捕获诊断。 安装和 profile 启动会按声明的 `engines.dsh` 范围(未声明时按 DSH peer 范围),检查与 `dsh --version` 显示值相同的运行时版本。不兼容插件需要用户明确确认精确版本豁免。[插件管理器的兼容性参考](../../packages/boot/plugin-manager/README.zh.md#version-compatibility-and-exemptions)说明 `version-exemptions`、`allow-version`、`revoke-version`、持久化规则与风险。 diff --git a/apps/cli/composition.md b/apps/cli/composition.md index 1fa22d5a13..be69ec247c 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -56,6 +56,8 @@ flowchart LR cfg --> plugin_dsh_base_authorization plugin_dsh_base_deepseek_account["deepseek-account
@deepseek-ai/dsh-deepseek-account"] cfg --> plugin_dsh_base_deepseek_account + plugin_dsh_base_deepseek_auth["deepseek-auth
@deepseek-ai/dsh-deepseek-auth"] + cfg --> plugin_dsh_base_deepseek_auth plugin_dsh_base_credentials["credentials
@deepseek-ai/dsh-credentials-local"] cfg --> plugin_dsh_base_credentials plugin_dsh_base_llm_pi_ai["llm-pi-ai
@deepseek-ai/dsh-llm-pi-ai"] @@ -86,6 +88,8 @@ flowchart LR cfg --> plugin_dsh_base_session_telemetry_otel plugin_dsh_base_subprocess["subprocess
@deepseek-ai/dsh-subprocess-local"] cfg --> plugin_dsh_base_subprocess + plugin_dsh_base_cli_account["cli-account
@deepseek-ai/dsh-cli-account"] + cfg --> plugin_dsh_base_cli_account plugin_dsh_base_sandbox["sandbox
@deepseek-ai/dsh-sandbox-local"] cfg --> plugin_dsh_base_sandbox plugin_dsh_base_sandbox_policy["sandbox-policy
@deepseek-ai/dsh-sandbox-policy"] @@ -234,6 +238,7 @@ flowchart LR | `settings` | `@deepseek-ai/dsh-settings` | | `authorization` | `@deepseek-ai/dsh-authorization` | | `deepseek-account` | `@deepseek-ai/dsh-deepseek-account` | +| `deepseek-auth` | `@deepseek-ai/dsh-deepseek-auth` | | `credentials` | `@deepseek-ai/dsh-credentials-local` | | `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` | | `session-persistence-jsonl` | `@deepseek-ai/dsh-session-persistence-jsonl` | @@ -249,6 +254,7 @@ flowchart LR | `otel` | `@deepseek-ai/dsh-otel` | | `session-telemetry-otel` | `@deepseek-ai/dsh-session-telemetry-otel` | | `subprocess` | `@deepseek-ai/dsh-subprocess-local` | +| `cli-account` | `@deepseek-ai/dsh-cli-account` | | `sandbox` | `@deepseek-ai/dsh-sandbox-local` | | `sandbox-policy` | `@deepseek-ai/dsh-sandbox-policy` | | `bash-sandbox` | `@deepseek-ai/dsh-bash-sandbox` | diff --git a/apps/cli/package.json b/apps/cli/package.json index 54aaf4de0d..0c5c178a22 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -63,6 +63,7 @@ "@deepseek-ai/dsh-schedule": "workspace:*", "@deepseek-ai/dsh-sdk-app": "workspace:*", "@deepseek-ai/dsh-sdk-minimal": "workspace:*", + "@deepseek-ai/dsh-session-persistence-sqlite": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-session-reference": "workspace:*", "@deepseek-ai/dsh-skill": "workspace:*", @@ -176,7 +177,8 @@ "@types/ws": "8.18.1", "ajv": "^8.20.0", "execa": "^10.0.1", - "ws": "8.21.3" + "ws": "8.21.3", + "@deepseek-ai/dsh-deepseek-auth": "workspace:*" }, "exports": { "./profile-boot": { diff --git a/apps/cli/reference/README.i18n.yaml b/apps/cli/reference/README.i18n.yaml index 2c33416553..93a4389770 100644 --- a/apps/cli/reference/README.i18n.yaml +++ b/apps/cli/reference/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8d2cfff9bab7327f zh: 21515ab6e6798504 /dsh-cli-behavior-reference/web-profile: - en: 149c5571acd51baf - zh: 300e3c2425273a92 + en: afc6ddcd63f24664 + zh: ed11d2ad6d7a9852 /dsh-cli-behavior-reference/shared-deployment-behavior: en: f02219118dcec531 zh: fe2977628d7340da diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md index dc84a267d8..ff5b1914ad 100644 --- a/apps/cli/reference/README.md +++ b/apps/cli/reference/README.md @@ -128,7 +128,7 @@ The production Web runner needs built package and frontend artifacts (`pnpm run Process shutdown gives the plugin tree up to five seconds to dispose. The first `SIGINT`/`SIGTERM` starts that graceful drain — `SIGTERM` is a supervisor's ordinary stop request and exits 0 on every surface, `SIGINT` reports 130; a second signal forces immediate exit. If one-shot normal completion is already stuck in disposal, the first `Ctrl+C` is the escalation and exits immediately instead of being swallowed. -The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget for each instruction chain, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root and includes `read_image`, but omits text filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers. +The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget for each instruction chain, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root and includes `read_image`, but omits text filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and every `--patch` overlay file, and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers. New sessions in base-backed profiles default to the `workspace-write` permission preset. Bash and filesystem mutations are restricted to the session workspace and platform temporary roots; reads and network access are not confined, while process visibility depends on the selected sandbox backend — bwrap runs commands in a private PID namespace that hides host processes, and Landlock and Seatbelt leave host process visibility unchanged. `DSH_PERMISSION_MODE` changes the process fallback. Stored General-settings permissions affect later Web sessions, not an already-open one. The standalone `sdk-minimal` tree instead pins `danger-full-access` and mounts no approval or permission-settings service. diff --git a/apps/cli/reference/README.zh.md b/apps/cli/reference/README.zh.md index 2de7755983..bc1e6ed8ac 100644 --- a/apps/cli/reference/README.zh.md +++ b/apps/cli/reference/README.zh.md @@ -128,7 +128,7 @@ dsh web --help 进程关闭时,插件树最多有 5 秒完成 dispose。首次收到 `SIGINT` 或 `SIGTERM` 时会开始优雅排空:`SIGTERM` 是监督进程发出的常规停止请求,在所有运行模式下都以 0 退出;`SIGINT` 则报告 130。第二次收到信号时会立即强制退出。如果一次性运行在正常结束时已经卡在 dispose 阶段,第一次按下 `Ctrl+C` 就会直接升级为强制退出,而不会被忽略。 -基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以每条指令链 65,536 字节的渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录并包含 `read_image`,但省略文本文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。 +基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以每条指令链 65,536 字节的渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录并包含 `read_image`,但省略文本文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层以及每个 `--patch` overlay 文件的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。 基于 base 的 profile 中,新会话默认使用 `workspace-write` 权限预设。Bash 和文件系统修改仅限于会话 workspace 与平台临时根目录;读取和网络访问不受限制,进程可见性则取决于所选沙箱后端——bwrap 在私有 PID 命名空间中运行命令并隐藏宿主进程,Landlock 与 Seatbelt 保持宿主进程可见性不变。`DSH_PERMISSION_MODE` 更改进程后备值。General settings 中存储的权限影响后续 Web 会话,不改变已打开的会话。独立的 `sdk-minimal` 配置树则固定为 `danger-full-access`,且不挂载 approval 或权限 settings 服务。 diff --git a/apps/cli/src/profile-boot.ts b/apps/cli/src/profile-boot.ts index 2b1977deed..9ac6ffbe42 100644 --- a/apps/cli/src/profile-boot.ts +++ b/apps/cli/src/profile-boot.ts @@ -14,14 +14,12 @@ import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { FiberState, type Context } from '@deepseek-ai/cordis' -import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { boot, readProfilePatches, createRuntimeResolution, initProfile, installFailLoud, - loadOverlayPatches, loadProfile, reportSkippedBundles, PluginPackages, @@ -204,8 +202,8 @@ interface ComposedProfile { profile: Profile /** Immutable runtime resolution computed before any plugin imports. */ resolution: RuntimeResolution - /** Command-line overlay contents, frozen for this invocation. */ - overlays: PatchOptions[] + /** Absolute command-line overlay files, in argv order. */ + overlayPaths: string[] } /** @@ -231,8 +229,7 @@ async function composeProfile( if (resolvedProfile !== undefined) writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG) const resolutionOptions = { installAnchor: resolvedProfile?.installAnchor ?? INSTALL_ANCHOR, profile } const resolution = await createRuntimeResolution(resolutionOptions) - const overlays = patchFiles.flatMap(file => loadOverlayPatches(NAME, resolve(file))) - return { profile, resolution, overlays } + return { profile, resolution, overlayPaths: patchFiles.map(file => resolve(file)) } } /** An application-owned profile and its independent installation fallback. */ @@ -331,7 +328,7 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con installAnchor: options.resolvedProfile?.installAnchor ?? INSTALL_ANCHOR, startedBundles: composed.profile.layers.map(layer => layer.packageName), cwd: process.cwd(), home: resolveDshHome(), - overlays: composed.overlays, telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED, + overlayPaths: composed.overlayPaths, telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED, } const ctx = await boot(NAME, rootConfig, readProfilePatches(NAME, profileContext, composed.profile), async (hostCtx) => { app.current = hostCtx diff --git a/apps/cli/tests/agent-team-headless.e2e.ts b/apps/cli/tests/agent-team-headless.e2e.ts index 026a54903c..c32f92c614 100644 --- a/apps/cli/tests/agent-team-headless.e2e.ts +++ b/apps/cli/tests/agent-team-headless.e2e.ts @@ -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 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) => { diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index acb6e4ab37..29f1217c4c 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -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']) { @@ -1265,6 +1263,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', ['deepseek-llm-api-extensions', '@deepseek-ai/dsh-deepseek-llm-api-extensions'], ['session-log-deepseek', '@deepseek-ai/dsh-session-log-deepseek'], ['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'], + ['deepseek-auth', '@deepseek-ai/dsh-deepseek-auth'], ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'], ['sandbox', '@deepseek-ai/dsh-sandbox-local'], ['filesystem', '@deepseek-ai/dsh-fs-local'], diff --git a/apps/cli/tests/expected/dump-config-schema.json b/apps/cli/tests/expected/dump-config-schema.json index ce57b82073..6a5fb77153 100644 --- a/apps/cli/tests/expected/dump-config-schema.json +++ b/apps/cli/tests/expected/dump-config-schema.json @@ -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": { diff --git a/apps/cli/tests/optional-bundle-transitions.e2e.ts b/apps/cli/tests/optional-bundle-transitions.e2e.ts index ac04460a79..d7e81f2c47 100644 --- a/apps/cli/tests/optional-bundle-transitions.e2e.ts +++ b/apps/cli/tests/optional-bundle-transitions.e2e.ts @@ -95,7 +95,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option const profile = app.loadProfileDirectory('bundle-test', directory, installAnchor) const profileContext: ProfileContext = { name: 'web', dir: directory, patchPath: profile.patchPath, installAnchor, cwd: workspace, home, - startedBundles: profile.layers.map(layer => layer.packageName), overlays: [], telemetryDisabledEnv: '1', + startedBundles: profile.layers.map(layer => layer.packageName), overlayPaths: [], telemetryDisabledEnv: '1', } const resolution = await app.createRuntimeResolution({ installAnchor, home, profile }) const listeners = new Set<() => void>() diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index c7ef7c99e1..ea7301ee1b 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -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. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/tools.json b/apps/cli/tests/profiles/cua-mcp/expected/tools.json index 3dcb8da4dc..3b0395878f 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/tools.json +++ b/apps/cli/tests/profiles/cua-mcp/expected/tools.json @@ -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. 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": { diff --git a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl index 9f15c8c621..235e8e695e 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl @@ -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":""} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl index 23df1c78fb..6ec383b0be 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl @@ -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":"\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: \"\", 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"}],"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: \"\", 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":"\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: \"\", 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 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"}],"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: \"\", 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 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"} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl index 7fd42a7bc1..75dbb725de 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl @@ -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":"\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: \"\", 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"}],"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: \"\", 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":"\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: \"\", 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 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"}],"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: \"\", 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 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"}}} diff --git a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs index a2d5cc5ea1..a150fa124f 100644 --- a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs +++ b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs @@ -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') } diff --git a/apps/cli/tests/profiles/headless/tests/harness.ts b/apps/cli/tests/profiles/headless/tests/harness.ts index 43164c9d7b..c354102286 100644 --- a/apps/cli/tests/profiles/headless/tests/harness.ts +++ b/apps/cli/tests/profiles/headless/tests/harness.ts @@ -9,6 +9,7 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key' +import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth' import TokenMeter from '@deepseek-ai/dsh-token-meter' import ToolResultPruner from '@deepseek-ai/dsh-compaction-tool-result-pruner' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -70,6 +71,7 @@ export async function codingHarness(workdir: string, options: CodingHarnessOptio systemPrompt: { personaPrefix: options.personaPrefix ?? '' }, }) await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(DeepSeekAuth) await ctx.plugin(LlmDeepSeek, { ...options.modelContextWindow === undefined && options.modelMaxTokens === undefined ? {} : { models: [{ diff --git a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts index 69c95ef485..1960f024bf 100644 --- a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts @@ -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 diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index d3129c027b..f71cf9b768 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -1,5 +1,5 @@ -import { executeModelToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { executeToolFixture, executeModelToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import { mkdtemp, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -20,6 +20,7 @@ import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key' +import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth' import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' @@ -63,6 +64,7 @@ async function ptcModeHarness(cwd: string): Promise { tools: { mode: 'ptc' }, }) await harness.plugin(AgentLoop, { agents: [] }) + await harness.plugin(DeepSeekAuth) await harness.plugin(LlmDeepSeek) if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime) await harness.plugin(BashEnvPlugin) @@ -83,6 +85,7 @@ async function workspacePtcModeHarness(): Promise { await harness.plugin(ToolFs) await harness.plugin(AgentInstructions, { maxBytes: 65536 }) await harness.plugin(AgentLoop, { agents: [] }) + await harness.plugin(DeepSeekAuth) await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] }) await mountRuntime(harness) return harness @@ -152,6 +155,50 @@ async function backgroundPtcModeHarness(cwd: string): Promise { } describe('PTC mode typed values: keyless real-process contracts', () => { + it('returns formatted read content from inspect through the real outer run_code result', async () => { + workdir = await realpath(await mkdtemp(join(tmpdir(), 'dsh-ptc-inspect-read-'))) + const path = join(workdir, 'a.txt') + await writeFile(path, 'alpha\nbeta\n') + ctx = await typedPtcModeHarness() + await ctx.plugin(ToolFs) + + const formatted = `${path}\nfile\n\n1: alpha\n2: beta\n\n(End of file - total 2 lines)\n` + const native = await executeToolFixture(ctx, { + callId: brandString('inspect-read-reference'), name: 'read', + arguments: { file_path: path }, signal: testToolSignal, + }) + expect(native.isError).toBe(false) + expect(native.content).toEqual([{ type: 'text', text: formatted }]) + + const result = await runCode(ctx, `inspect(await tools.read({ file_path: ${JSON.stringify(path)} }));`) + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: formatted + '\n' }]) + expect(result.value).toEqual({ + logs: [formatted + '\n'], sandbox: { mode: 'danger-full-access', denied: false }, + }) + }) + + it.each(['renderer', 'policy'])('keeps an empty %s output silent while preserving program data', async (source) => { + ctx = await typedPtcModeHarness() + ctx.tools.register(defineTool({ + name: 'silent_result', description: 'Return data without display text.', parameters: {}, + output: { + schema: { type: 'object', properties: { answer: { type: 'number', required: true } }, additionalProperties: false }, + render: () => source === 'renderer' ? [] : [{ type: 'text', text: 'original rendering' }], + }, + execute: async () => ({ answer: 42 }), + ...source === 'policy' ? { finalizeContent: () => [] } : {}, + })) + const result = await runCode(ctx, ` + const value = await tools.silent_result({}); + if (value.answer !== 42) throw new Error('program data changed'); + inspect(value); + `) + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: '(run_code completed with no output)' }]) + expect(result.value).toEqual({ logs: [], sandbox: { mode: 'danger-full-access', denied: false } }) + }) + it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => { ctx = await typedPtcModeHarness() ctx.tools.register(defineTool({ @@ -305,15 +352,15 @@ describe('PTC mode typed values: keyless real-process contracts', () => { } as Agent const value = completion(await runCode(ctx, ` - const listed = await tools.cordis_inspect_list({}); + const listed = await tools.cordis_inspect({}); const provider = listed.providers.find(item => item.id === 'Tool'); - const inspected = await tools.cordis_inspect_query({ + const inspected = await tools.cordis_inspect({ query: { platform: provider.platform, provider: provider.id, method: provider.methods[0].name, - }); + } }); inspect(JSON.stringify({ provider: provider.id, names: inspected.data.tools.map(tool => tool.name) })); `, testToolSignal, agent)) - expect(value).toEqual({ provider: 'Tool', names: ['cordis_inspect_list', 'cordis_inspect_query'] }) + expect(value).toEqual({ provider: 'Tool', names: ['cordis_inspect'] }) }) }) diff --git a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts index 480ffe2032..3faedc4a74 100644 --- a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts +++ b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts @@ -2,7 +2,7 @@ * Keyless comparison of actual SDK and Desktop/Web step-admitted tool sets. * Keep intentional differences in tool-parity.ts; unused exceptions fail. * Team mode is excluded while its known composition mismatch is tracked in #7172. - * SDK minimal, Creator-only tools, graphical context and optional runtime payloads + * SDK minimal, other presets, graphical context and optional runtime payloads * are outside this fixed standard/PTC, top-level-session comparison. */ import { createServer } from 'node:http' diff --git a/apps/cli/tests/profiles/sdk/tool-parity.ts b/apps/cli/tests/profiles/sdk/tool-parity.ts index fce089fc02..0b6299051e 100644 --- a/apps/cli/tests/profiles/sdk/tool-parity.ts +++ b/apps/cli/tests/profiles/sdk/tool-parity.ts @@ -9,8 +9,12 @@ interface Exception { /** Intentional product differences; obsolete entries fail alongside undeclared differences. */ export const toolParityExceptions: Record = { - standard: [{ tool: 'list_subagent_models', side: 'desktop', - reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }], + standard: [ + { tool: 'list_subagent_models', side: 'desktop', + reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, + { tool: 'cordis_inspect', side: 'desktop', + reason: 'Web exposes inspection of its Host and connected Client runtime; the SDK profile does not compose the Cordis inspection providers.' }, + ], ptc: [ { tool: 'list_subagent_models', side: 'desktop', reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, diff --git a/apps/cli/tests/resolved-profile-boot.spec.ts b/apps/cli/tests/resolved-profile-boot.spec.ts index b8415fb974..40630df491 100644 --- a/apps/cli/tests/resolved-profile-boot.spec.ts +++ b/apps/cli/tests/resolved-profile-boot.spec.ts @@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { join, relative } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { @@ -139,7 +139,7 @@ describe('runProfile with an application-owned profile', () => { try { const { shutdown } = await runProfile({ environment, profile: 'desktop', resolvedProfile: runtime, - patchFiles: [overlay], args: ['--port', '0', '--no-open'], + patchFiles: [relative(process.cwd(), overlay)], args: ['--port', '0', '--no-open'], }) expect(installProxyFromEnvironment).toHaveBeenCalledWith(environment, expect.any(Function)) const resolution = vi.mocked(createRuntimeResolution).mock.settledResults @@ -165,7 +165,9 @@ describe('runProfile with an application-owned profile', () => { ]) expect(rows.find(row => row.id === 'target')?.config).toEqual({ overlay: true, priority: 'overlay' }) expect(rows.find(row => row.id === 'session-telemetry-otel')?.disabled).toBe(true) - expect(ctx.profileContext).toMatchObject({ dir: home, patchPath: profilePatch, installAnchor: runtime.installAnchor }) + expect(ctx.profileContext).toMatchObject({ + dir: home, patchPath: profilePatch, installAnchor: runtime.installAnchor, overlayPaths: [overlay], + }) await shutdown.shutdown(0) expect(dispose).toHaveBeenCalledOnce() expect(disposeProxy).toHaveBeenCalledOnce() diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index 0fb662568f..90d8da8d72 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -1,6 +1,6 @@ import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry' -import { subagentModelSelectionProjectionDefinition } from '@deepseek-ai/dsh-tool-subagent/src/model-selection-state.ts' +import type {} from '@deepseek-ai/dsh-tool-subagent/model-selection-settings' import { createRequire } from 'node:module' import { randomUUID } from 'node:crypto' import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises' @@ -221,7 +221,7 @@ async function bootWeb( bootCtx.provide('profileContext', { name: surface, dir: profileDir, patchPath: profile.patchPath, installAnchor: INSTALL_ANCHOR, home, cwd: home, startedBundles: profileBundles ?? ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'], - overlays: [], telemetryDisabledEnv: '1' }) + overlayPaths: [], telemetryDisabledEnv: '1' }) await bootCtx.plugin(PluginPackages, { resolution }) bootCtx.provide('connection', { fetch: { register: () => () => {} }, @@ -351,7 +351,7 @@ describe('the shipped Web composition', () => { // excluded for the reason the TUI composition e2e excludes them — they // depend on ripgrep being present on the machine. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([ - 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode', + 'ask_user_question', 'bash', 'cordis_inspect', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'skill', @@ -359,12 +359,24 @@ describe('the shipped Web composition', () => { 'workflow', 'working_directory', 'write', ]) expect(ctx.commands.find(handle.agent, 'goal')).toBeDefined() + for (const query of [undefined, { platform: 'host', provider: 'Config', method: 'listConfigs', input: { name: '@deepseek-ai/dsh-agent-loop' } }] as const) { + const inspected = await executeToolFixture(ctx, { + agent: handle.agent, callId: brandString(`standard-inspect-${query === undefined ? 'list' : 'query'}`), name: 'cordis_inspect', + arguments: query === undefined ? {} : { query }, signal: new AbortController().signal, + }) + expect(inspected.isError).toBe(false) + const text = inspected.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + const value: unknown = JSON.parse(text) + const path = query === undefined ? 'providers' : 'data.entries' + const entry = query === undefined ? { platform: 'host', id: 'Config' } : { name: '@deepseek-ai/dsh-agent-loop' } + expect(value).toHaveProperty(path, expect.arrayContaining([expect.objectContaining(entry)])) + } } finally { await handle.dispose() } }) - it('applies the default-off subagent model allowlist only to new sessions', async () => { + it('reads the default-off subagent model allowlist live for existing sessions', async () => { await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false, allowedModels: [], @@ -381,16 +393,17 @@ describe('the shipped Web composition', () => { sessionId: brandString('preset-model-selection-enabled'), setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), }) - const policy = await ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition) try { expect(toolNames(ctx, disabled.agent)).toContain('list_subagent_models') expect(toolParameterNames(ctx, disabled.agent, 'subagent')).toEqual(expect.arrayContaining([ 'model', 'provider', 'reasoning_effort', ])) - expect(policy.stateOf(disabled.agent.session)).toBeNull() - expect(policy.stateOf(enabled.agent.session)).toEqual([ + expect(ctx.subagentModelSelection.allowedRoutes()).toEqual([ { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, ]) + for (const agent of [disabled.agent, enabled.agent]) { + expect(agent.session.snapshotEvents().some(event => event.type === 'subagent/model-selection-policy')).toBe(false) + } expect(toolNames(ctx, enabled.agent)).toContain('list_subagent_models') expect(toolParameterNames(ctx, enabled.agent, 'subagent')).toEqual(expect.arrayContaining([ 'model', 'provider', 'reasoning_effort', @@ -399,7 +412,6 @@ describe('the shipped Web composition', () => { expect(toolParameterNames(ctx, agent, 'subagent_fork')).toEqual(['cwd', 'description', 'name', 'prompt']) } } finally { - await policy.dispose() await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false }) await enabled.dispose() await disabled.dispose() @@ -603,7 +615,7 @@ describe('the shipped Web composition', () => { try { const tools = toolNames(ctx, handle.agent) expect(tools).toEqual(expect.arrayContaining([ - 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager', + 'cordis_inspect', 'plugin_manager', ])) for (const removed of ['cordis_define', 'cordis_run', 'cordis_stop', 'cordis_undefine', 'cordis_inspect_self']) { expect(tools).not.toContain(removed) @@ -985,8 +997,7 @@ describe('the standard preset documentation skill', () => { expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path) const schemas = testCtx.tools.schemas(standardAgent.agent) expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent)) - expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_list') - expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_query') + expect(schemas.map(tool => tool.name)).toContain('cordis_inspect') for (const handle of [baseline, standardAgent]) { handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply ready.' }], source: { kind: 'user' } })) await handle.agent.whenIdle() @@ -1116,13 +1127,13 @@ describe('a user preset declared from the shipped cordis rows', () => { try { for (const handle of [shipped, copied]) { expect(toolNames(copyCtx, handle.agent)).toEqual(expect.arrayContaining([ - 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager', + 'cordis_inspect', 'plugin_manager', ])) } const signal = new AbortController().signal const listed = await executeToolFixture(copyCtx, { callId: brandString('copied-preset-inspect-list'), - name: 'cordis_inspect_list', + name: 'cordis_inspect', arguments: {}, signal, agent: copied.agent, @@ -1130,7 +1141,7 @@ describe('a user preset declared from the shipped cordis rows', () => { expect(listed.isError).toBe(false) const providers = (JSON.parse(resultText(listed)) as { providers: Array<{ id: string; platform: string }> }).providers expect(providers.filter(provider => provider.platform === 'host').map(provider => provider.id)) - .toEqual(['Service', 'Event', 'Config', 'Tool']) + .toEqual(['Service', 'Event', 'Config', 'Runtime', 'Tool']) // The `Tool` provider is the one built over the host context: it // answers with the shared registry's view of the REQUESTING agent, @@ -1139,15 +1150,15 @@ describe('a user preset declared from the shipped cordis rows', () => { onTestFinished(() => { spills.mockRestore() }) const queried = await executeToolFixture(copyCtx, { callId: brandString('copied-preset-inspect-tools'), - name: 'cordis_inspect_query', - arguments: { platform: 'host', provider: 'Tool', method: 'listTools' }, + name: 'cordis_inspect', + arguments: { query: { platform: 'host', provider: 'Tool', method: 'listTools' } }, signal, agent: copied.agent, }) expect(queried.isError).toBe(false) // The tool catalog may exceed the inline budget; assert its complete stored text. const queriedText = spills.mock.calls.at(-1)?.[0].content ?? resultText(queried) - for (const toolName of ['bash', 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager']) { + for (const toolName of ['bash', 'cordis_inspect', 'plugin_manager']) { expect(queriedText).toContain(`"name": "${toolName}"`) } @@ -1158,8 +1169,8 @@ describe('a user preset declared from the shipped cordis rows', () => { const listConfigs = async (input: Record, callId: string): Promise => { const page = await executeToolFixture(copyCtx, { callId: brandString(callId), - name: 'cordis_inspect_query', - arguments: { platform: 'host', provider: 'Config', method: 'listConfigs', input }, + name: 'cordis_inspect', + arguments: { query: { platform: 'host', provider: 'Config', method: 'listConfigs', input } }, signal, agent: copied.agent, }) @@ -1177,8 +1188,8 @@ describe('a user preset declared from the shipped cordis rows', () => { expect(firstPage.nextOffset).toBe(5) const projected = await executeToolFixture(copyCtx, { callId: brandString('copied-preset-inspect-config'), - name: 'cordis_inspect_query', - arguments: { platform: 'host', provider: 'Config', method: 'listConfigs', input: { entry: toolsRow!.id } }, + name: 'cordis_inspect', + arguments: { query: { platform: 'host', provider: 'Config', method: 'listConfigs', input: { entry: toolsRow!.id } } }, signal, agent: copied.agent, }) diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index b26c7e5db3..54b3afee69 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -27,7 +27,7 @@ "path": "../../packages/host/webserver" }, { - "path": "../../packages/credentials/deepseek-account" + "path": "../../packages/account/deepseek-account" }, { "path": "../../packages/boot/plugin-manager" diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 57cd212b1d..3e54d0e07e 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -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 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 2a80a71ae5..4fb011f0b6 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -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. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 561f1526c0..db0a99cb50 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -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 和工作区均显示本地化的登录失效提示。 diff --git a/apps/desktop/src/client/WelcomePage.tsx b/apps/desktop/src/client/WelcomePage.tsx index b367061732..6a63dc7249 100644 --- a/apps/desktop/src/client/WelcomePage.tsx +++ b/apps/desktop/src/client/WelcomePage.tsx @@ -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 diff --git a/apps/desktop/src/preload-platform-account.ts b/apps/desktop/src/preload-platform-account.ts index ac7e42f0ae..5733a7fa2c 100644 --- a/apps/desktop/src/preload-platform-account.ts +++ b/apps/desktop/src/preload-platform-account.ts @@ -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', diff --git a/apps/desktop/tsconfig.client.json b/apps/desktop/tsconfig.client.json index eb17ebe087..7e24cdcda3 100644 --- a/apps/desktop/tsconfig.client.json +++ b/apps/desktop/tsconfig.client.json @@ -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" diff --git a/apps/desktop/tsconfig.host.json b/apps/desktop/tsconfig.host.json index 2701caf5a6..92ec693165 100644 --- a/apps/desktop/tsconfig.host.json +++ b/apps/desktop/tsconfig.host.json @@ -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" diff --git a/apps/web/tests/agent-preset-authoring.e2e.ts b/apps/web/tests/agent-preset-authoring.e2e.ts index 5ab43f206b..0727af2cab 100644 --- a/apps/web/tests/agent-preset-authoring.e2e.ts +++ b/apps/web/tests/agent-preset-authoring.e2e.ts @@ -43,6 +43,16 @@ describe('web e2e: preset roster guidance', () => { it('reads mode details and examples without changing the new-task default', async () => { onTestFailed(() => saveFailureShot(page, 'preset-roster-guide')) const settings = page.getByRole('dialog', { name: '设置' }) + for (const name of ['标准模式', '创造模式']) { + const sharedTrigger = settings.getByRole('button', { name: `模式说明: ${name}`, exact: true }) + await sharedTrigger.click() + const sharedGuide = page.getByRole('dialog', { name, exact: true }) + await sharedGuide.getByText(/只读运行时检查/).waitFor() + expect(await sharedGuide.innerText()).not.toContain('增加了运行时检查') + if (name === '创造模式') expect(await sharedGuide.innerText()).toContain('创造模式专注于定制 DSH') + await page.keyboard.press('Escape') + await sharedGuide.waitFor({ state: 'detached' }) + } const trigger = settings.getByRole('button', { name: '模式说明: PTC 模式', exact: true }) await trigger.click() const guide = page.getByRole('dialog', { name: 'PTC 模式', exact: true }) diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 624a5e3f96..2d2d675ae3 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -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"') @@ -486,7 +487,7 @@ it.each([false, true])('starts Creator from Plugins with Coding Tools=%s without expect(scaffold.ctx.sessionProjections.checkpoint(creator.session).agentPreset?.val).toBe('cordis') expect(scaffold.ctx.agentPresets.composedPreset(creator.ctx)).toBe('cordis') expect(scaffold.ctx.tools.schemas(creator).map(tool => tool.name)) - .toEqual(expect.arrayContaining(['cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager'])) + .toEqual(expect.arrayContaining(['cordis_inspect', 'plugin_manager'])) // The Session starts under Creator; a chip selection after the list updates records no switch. expect(creator.session.snapshotEvents().filter(event => event.type === 'agent-preset/selected')).toEqual([]) expect(creator.session.snapshotEvents().some(event => event.type === 'user/message' || event.type === 'turn/start')).toBe(false) diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 869eda7fdc..7438bc86ce 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -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 { + 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 { + return (await showSessionPanel(page)).locator(SHARED_TASKS_SECTION) +} + async function openTeamSettings(page: Page, chinese = false): Promise { 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 => { + 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((resolve) => { + panel.evaluate(element => new Promise((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) }) }) diff --git a/apps/web/tests/anchored-panels.e2e.ts b/apps/web/tests/anchored-panels.e2e.ts index 5770d228c7..e62d618503 100644 --- a/apps/web/tests/anchored-panels.e2e.ts +++ b/apps/web/tests/anchored-panels.e2e.ts @@ -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' }, diff --git a/apps/web/tests/assembled-boot.ts b/apps/web/tests/assembled-boot.ts index 3ecaa90a4d..a45ff68471 100644 --- a/apps/web/tests/assembled-boot.ts +++ b/apps/web/tests/assembled-boot.ts @@ -191,11 +191,6 @@ class ResizeObserverStub { unobserve(): void {} } -class EventSourceStub { - addEventListener(): void {} - close(): void {} -} - const win = window as FixtureWindow let unmount: (() => Promise) | undefined let mountedRemote: RemoteMock | undefined @@ -244,7 +239,6 @@ export function installAssembledBootEnv(): void { Object.defineProperty(navigator, 'language', { value: 'en-US', configurable: true }) document.title = 'DeepSeek Harness' vi.stubGlobal('ResizeObserver', ResizeObserverStub) - vi.stubGlobal('EventSource', EventSourceStub) vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => setTimeout(() => { callback(0) }, 0) as unknown as number) vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) }) diff --git a/apps/web/tests/background-job-list.e2e.ts b/apps/web/tests/background-job-list.e2e.ts index fff8cd823d..f0d0ee013c 100644 --- a/apps/web/tests/background-job-list.e2e.ts +++ b/apps/web/tests/background-job-list.e2e.ts @@ -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(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('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(/^ ) return
-

{t('nav')}

-

{t('sectionIntro')}

+
+

{t('nav')}

+

{t('sectionIntro')}

+
{state.error === null ? null :

{state.error}

} {([true, false] as const).map((builtIn) => { const rows = state.rows.filter(row => isBuiltInPreset(row) === builtIn diff --git a/packages/client/ui-agent-preset/src/client/guide-locales.ts b/packages/client/ui-agent-preset/src/client/guide-locales.ts index d193002324..2401935497 100644 --- a/packages/client/ui-agent-preset/src/client/guide-locales.ts +++ b/packages/client/ui-agent-preset/src/client/guide-locales.ts @@ -10,7 +10,7 @@ export const guideEn = { guideStandardIntro: 'Choose Standard mode when starting a new task. Describe what you want to accomplish, point to the relevant files, and explain how to check the result.', guideStandardExplanation: [ '### How it works', - 'The agent calls tools directly to read and edit files, search, and run terminal commands. It includes Skills, planning, goals, subagents, workflows, plugin management, and context compaction.', + 'The agent calls tools directly to read and edit files, search, and run terminal commands. It includes Skills, planning, goals, subagents, workflows, plugin management, read-only runtime inspection, and context compaction.', 'For questions about DSH and plugin or preset work you request, the dsh-doc skill guides the agent to the installed documentation and source. Its instructions load only when requested or relevant; loading it does not change files, tools, or the profile.', '### When to choose it', 'Start here for everyday coding, file work, and research. Standard mode can also write scripts and process files in batches. PTC changes how tool calls are organized; it is not required for batch tasks.', @@ -55,7 +55,7 @@ export const guideEn = { guideCordisIntro: 'Choose Creator mode for a new task. Describe the capability you want, where it should appear, and how you will verify it.', guideCordisExplanation: [ '### What you can create', - 'Creator mode includes the standard task tools and adds runtime inspection. Standard and Creator share the dsh-doc guidance for plugin and preset development. The agent can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', + 'Creator mode focuses on customizing DSH. It shares read-only runtime inspection and dsh-doc guidance with Standard mode. The agent can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', '### Plugins and modes', 'A plugin adds capabilities to DSH, such as a tool, a service connection, or a UI entry. A mode is an agent preset that selects tools and defines how the agent works in a task. A plugin can be included in a custom preset.', '### How the result takes effect', @@ -89,7 +89,7 @@ export const guideZh: Record = { guideStandardIntro: '新建任务时选择「标准模式」,说明要完成什么、相关文件在哪里,以及怎样判断任务完成。', guideStandardExplanation: [ '### 工作方式', - 'Agent 直接调用工具来读写文件、检索资料和执行终端命令。包含 Skills、计划、目标、子 Agent、工作流、插件管理和上下文压缩等能力。', + 'Agent 直接调用工具来读写文件、检索资料和执行终端命令。包含 Skills、计划、目标、子 Agent、工作流、插件管理、只读运行时检查和上下文压缩等能力。', '对于 DSH 相关问题以及你要求的插件或预设工作,dsh-doc skill 引导 Agent 查阅已安装的文档和源码。其指令仅在被要求加载或与当前任务相关时加载;加载该 skill 不会改变文件、工具或 profile。', '### 什么时候选', '日常编程、文件处理和资料整理可以从这里开始。标准模式也能编写脚本、批量处理文件;PTC 改变的是工具调用方式,批量任务并不必须使用 PTC。', @@ -134,7 +134,7 @@ export const guideZh: Record = { guideCordisIntro: '新建任务时选择「创造模式」,说明希望增加什么能力、从哪里使用,以及怎样验证效果。', guideCordisExplanation: [ '### 可以创造什么', - '创造模式包含标准任务工具,并增加了运行时检查。标准模式和创造模式共用 dsh-doc 指引,用于插件和预设开发。Agent 可以创建插件来添加能力或界面,也可以创建预设,为特定工作组合工具和提示词。', + '创造模式专注于定制 DSH。它与标准模式共用只读运行时检查和 dsh-doc 指引。Agent 可以创建插件来添加能力或界面,也可以创建预设,为特定工作组合工具和提示词。', '### 插件与模式的关系', '插件为 DSH 增加能力,例如工具、服务连接或界面入口。模式是一份 Agent 预设,用来选择任务可用的工具,并约定 Agent 的工作方式。自定义模式中也可以使用自己开发的插件。', '### 怎样让成果生效', @@ -163,7 +163,7 @@ export const guideJa = { 'guideCopied': 'コピーしました', 'guideFootnotes': '脚注', 'guideStandardIntro': '新しいタスクを始めるときは標準モードを選びます。達成したいことを説明し、関連するファイルを示し、結果の確認方法を伝えてください。', - 'guideStandardExplanation': '### 仕組み\n\nエージェントはツールを直接呼び出してファイルの読み取りや編集、検索、ターミナルコマンドの実行を行います。スキル、計画、目標、サブエージェント、ワークフロー、プラグイン管理、コンテキストの圧縮に対応しています。\n\n### 選ぶべき場面\n\n日々のコーディング、ファイル作業、調査はまずここから始めてください。標準モードではスクリプトの作成やファイルの一括処理も行えます。PTC はツール呼び出しの構成を変えるものであり、一括処理に必須ではありません。', + 'guideStandardExplanation': '### 仕組み\n\nエージェントはツールを直接呼び出してファイルの読み取りや編集、検索、ターミナルコマンドの実行を行います。スキル、計画、目標、サブエージェント、ワークフロー、プラグイン管理、読み取り専用のランタイム検査、コンテキストの圧縮に対応しています。\n\n### 選ぶべき場面\n\n日々のコーディング、ファイル作業、調査はまずここから始めてください。標準モードではスクリプトの作成やファイルの一括処理も行えます。PTC はツール呼び出しの構成を変えるものであり、一括処理に必須ではありません。', 'guideStandardUsage': '### バグを修正する\n\n> 検索フォームを二度送信すると結果が消える原因を調べてください。修正して関連するテストを実行し、原因と変更内容を説明してください。\n\n期待される出力: コードの変更、関連するテスト結果、原因の説明。\n\n### プロジェクトのメモを整理する\n\n> このプロジェクト内の Markdown メモを読み、合意された決定と未解決の課題を、元ファイルへのリンク付きで要約してください。\n\n期待される出力: 元のメモと照合できる参照付きの要約。', 'guidePtcIntro': '新しいタスクを始めるときは PTC モードを選びます。入力ファイル、処理ルール、出力形式を指定してください。コードはエージェントが書きます。', 'guidePtcExplanation': '### ツールの呼び出され方\n\nPTC は Programmatic Tool Calling の略です。この組み込みプリセットでは、エージェントは run_code を使い、生成された SDK 経由でツールを呼び出す TypeScript プログラムを書きます。プログラムではループ、条件分岐、エラー処理、必要に応じて並行呼び出しを利用できます。\n\n### モデルに届くもの\n\nツールの結果はまずプログラムに届き、そこでフィルタリングや結合ができます。モデルが受け取るのはプログラムが出力または返した内容です。画像の結果は別途添付されます。ネストされたツール呼び出しも記録され、ツール権限の対象のままです。\n\n### 標準モードとの比較\n\nどちらのモードもコーディングや一括処理のタスクを扱えます。標準モードは個々のツールを直接公開し、PTC はツール呼び出しをコードで整理します。現在の PTC プリセットではワークフローとプラグイン管理ツールが無効になっています。速度とトークン消費はタスクやプログラムの結果の扱い方によって変わります。', @@ -172,7 +172,7 @@ export const guideJa = { 'guideMinimalExplanation': '### 含まれるもの\n\n永続的なシェルツール 1 つ、read_image、固定のシステムプロンプト。画像の読み取りには画像対応モデルが必要です。古い履歴はコンテキストの負荷に応じて自動的に圧縮されます。エージェントがアイドル状態のときに /compact を使えば手動で圧縮できます。この組み込みプリセットはスキル、計画、標準のランタイムコンテキストを読み込みません。\n\n### 選ぶべき場面\n\n実験や比較のベースラインとして使用します。シェルコマンド経由でファイルの読み取りやスクリプトの実行はできますが、長いタスクを管理するための組み込み手段は少なくなります。ツールが少ないからといって、初心者にとって必ずしも簡単になるわけではありません。', 'guideMinimalUsage': '### 小さなバグ修正で性能を比較する\n\n> このプロジェクトのテストを実行し、失敗の原因を見つけて最小限の修正をしてください。関連するテストを再度実行し、結果を報告してください。\n\n同じ開始状態から、標準モードと最小モードで同じタスクを別々に実行します。タスクの完了状況、ツール呼び出し、生じた変更を比較してください。最小モードはターミナルコマンドを通じて作業を行います。', 'guideCordisIntro': '新しいタスクにはクリエイターモードを選びます。実現したい機能、表示される場所、確認方法を説明してください。', - 'guideCordisExplanation': '### 作成できるもの\n\nクリエイターモードには標準的なタスクツールに加え、ランタイムの検査、Cordis プラグインやエージェントプリセットの作成ガイドが含まれます。機能や UI を追加するプラグインを作成することも、特定の作業向けにツールとプロンプトを組み合わせたプリセットを作成することもできます。\n\n### プラグインとモード\n\nプラグインはツール、サービス接続、UI エントリなど、DSH に機能を追加します。モードはエージェントプリセットであり、ツールを選択し、タスク内でのエージェントの動作を定義します。プラグインはカスタムプリセットに含めることができます。\n\n### 結果を反映させる方法\n\nソースコードを生成するだけでなく、エージェントにインストールと確認を依頼してください。プラグインは変更内容によっては即座に読み込まれるか、再起動が必要になる場合があります。新しく作成したプリセットは、新しいタスクを始めるときに選択されます。', + 'guideCordisExplanation': '### 作成できるもの\n\nクリエイターモードは DSH のカスタマイズに重点を置いています。読み取り専用のランタイム検査と dsh-doc のガイドを標準モードと共有しています。エージェントは機能や UI を追加するプラグインを作成することも、特定の作業向けにツールとプロンプトを組み合わせたプリセットを作成することもできます。\n\n### プラグインとモード\n\nプラグインはツール、サービス接続、UI エントリなど、DSH に機能を追加します。モードはエージェントプリセットであり、ツールを選択し、タスク内でのエージェントの動作を定義します。プラグインはカスタムプリセットに含めることができます。\n\n### 結果を反映させる方法\n\nソースコードを生成するだけでなく、エージェントにインストールと確認を依頼してください。プラグインは変更内容によっては即座に読み込まれるか、再起動が必要になる場合があります。新しく作成したプリセットは、新しいタスクを始めるときに選択されます。', 'guideCordisUsage': '### UI を追加する\n\n> サイドバーにプロジェクトメモのエントリを追加する DSH プラグインを作成してください。このワークスペース内の Markdown ファイルを閲覧でき、選択したメモをプレビューできるようにしてください。インストールしてページが開くことを確認してください。\n\n期待される出力: 動作するエントリとプレビューページを備えた、インストール済みのプラグイン。残っている有効化手順があればそれも含みます。\n\n### ツールを追加する\n\n> このプロジェクトのテストレポートを読み、失敗したテストを要約するツールを備えたプラグインを作成してください。登録し、サンプルのレポートで確認してください。\n\n期待される出力: 呼び出し可能なツールを備えたプラグインと、確認済みのサンプル呼び出し。\n\n### 独自のモードを作成する\n\n> 標準モードをベースに「コードレビュー」モードを作成してください。潜在的なバグとテストの不足を優先し、ファイルパスと行番号を示し、ファイルを変更する前に確認を求めるようにしてください。選択可能なプリセットとして保存してください。\n\n期待される出力: 新しいタスク用のカスタムプリセット。これらのレビュー指示はエージェントを導くものであり、実行できる操作は権限設定によって決まります。', } satisfies Record @@ -188,7 +188,7 @@ export const guideEs = { guideStandardIntro: 'Elija el modo Estándar al iniciar una nueva tarea. Describe lo que quieres lograr, señala los archivos relevantes y explica cómo verificar el resultado.', guideStandardExplanation: [ '### Cómo funciona', - 'El agente llama a herramientas directamente para leer y editar archivos, buscar y ejecutar comandos de terminal. Incluye habilidades, planificación, objetivos, subagentes, flujos de trabajo, gestión de complementos y compactación de contexto.', + 'El agente llama a herramientas directamente para leer y editar archivos, buscar y ejecutar comandos de terminal. Incluye habilidades, planificación, objetivos, subagentes, flujos de trabajo, gestión de complementos, inspección del tiempo de ejecución de solo lectura y compactación de contexto.', '### Cuándo elegirlo', 'Comience aquí para la codificación, el trabajo con archivos y la investigación diaria. El modo estándar también puede escribir scripts y procesar archivos en lotes. PTC cambia la forma en que se organizan las llamadas a herramientas; no es necesario para tareas por lotes.', ].join('\n\n\n\n'), @@ -232,7 +232,7 @@ export const guideEs = { guideCordisIntro: 'Elija el modo Creador para una nueva tarea. Describe la capacidad que deseas, dónde debería aparecer y cómo la verificarás.', guideCordisExplanation: [ '### Lo que puedes crear', - 'El modo Creador incluye las herramientas de tareas estándar además de inspección del tiempo de ejecución y orientación para crear Cordis complementos y ajustes preestablecidos de agentes. Puede crear un complemento que agregue una capacidad o interfaz de usuario, o un ajuste preestablecido que combine herramientas e indicaciones para un trabajo en particular.', + 'El modo Creador se centra en personalizar DSH. Comparte la inspección del tiempo de ejecución de solo lectura y la orientación de dsh-doc con el modo Estándar. El agente puede crear un complemento que agregue una capacidad o interfaz de usuario, o un ajuste preestablecido que combine herramientas e indicaciones para un trabajo en particular.', '### Complementos y modos', 'Un complemento agrega capacidades a DSH, como una herramienta, una conexión de servicio o una entrada de UI. Un modo es un ajuste preestablecido del agente que selecciona herramientas y define cómo trabaja el agente en una tarea. Se puede incluir un complemento en un ajuste preestablecido personalizado.', '### Cómo surte efecto el resultado', @@ -263,7 +263,7 @@ export const guideFr = { guideStandardIntro: 'Choisissez le mode Standard lorsque vous démarrez une nouvelle tâche. Décrivez ce que vous souhaitez accomplir, pointez vers les fichiers pertinents et expliquez comment vérifier le résultat.', guideStandardExplanation: [ '### Comment ça marche', - "L'agent appelle directement des outils pour lire et modifier des fichiers, rechercher et exécuter des commandes de terminal. Il comprend les compétences, la planification, les objectifs, les sous-agents, les flux de travail, la gestion des plugins et le compactage du contexte.", + "L'agent appelle directement des outils pour lire et modifier des fichiers, rechercher et exécuter des commandes de terminal. Il comprend les compétences, la planification, les objectifs, les sous-agents, les flux de travail, la gestion des plugins, l\'inspection d\'exécution en lecture seule et le compactage du contexte.", '### Quand le choisir', "Commencez ici pour le codage quotidien, le travail sur les fichiers et la recherche. Le mode standard peut également écrire des scripts et traiter des fichiers par lots. PTC modifie la façon dont les appels d'outils sont organisés ; il n'est pas requis pour les tâches par lots.", ].join('\n\n\n\n'), @@ -307,7 +307,7 @@ export const guideFr = { guideCordisIntro: 'Choisissez le mode Créateur pour une nouvelle tâche. Décrivez la fonctionnalité souhaitée, où elle doit apparaître et comment vous la vérifierez.', guideCordisExplanation: [ '### Ce que vous pouvez créer', - "Le mode Créateur inclut les outils de tâches standard, ainsi qu'une inspection d'exécution et des conseils pour la création de Cordis plug-ins et préréglages d'agent. Il peut créer un plugin qui ajoute une fonctionnalité ou une interface utilisateur, ou un préréglage combinant des outils et des invites pour une tâche particulière.", + "Le mode Créateur se concentre sur la personnalisation de DSH. Il partage l'inspection d'exécution en lecture seule et les conseils de dsh-doc avec le mode Standard. L'agent peut créer un plugin qui ajoute une fonctionnalité ou une interface utilisateur, ou un préréglage combinant des outils et des invites pour une tâche particulière.", '### Plugins et modes', "Un plug-in ajoute des fonctionnalités à DSH, telles qu'un outil, une connexion à un service ou une entrée d'interface utilisateur. Un mode est un préréglage d'agent qui sélectionne les outils et définit la manière dont l'agent fonctionne dans une tâche. Un plugin peut être inclus dans un préréglage personnalisé.", '### Comment le résultat prend effet', @@ -338,7 +338,7 @@ export const guideDe = { guideStandardIntro: 'Wählen Sie den Standardmodus, wenn Sie eine neue Aufgabe starten. Beschreiben Sie, was Sie erreichen möchten, zeigen Sie auf die relevanten Dateien und erklären Sie, wie Sie das Ergebnis überprüfen können.', guideStandardExplanation: [ '### Wie es funktioniert', - 'Der Agent ruft Tools direkt auf, um Dateien zu lesen und zu bearbeiten, zu suchen und Terminalbefehle auszuführen. Es umfasst Fähigkeiten, Planung, Ziele, Subagenten, Arbeitsabläufe, Plugin-Verwaltung und Kontextkomprimierung.', + 'Der Agent ruft Tools direkt auf, um Dateien zu lesen und zu bearbeiten, zu suchen und Terminalbefehle auszuführen. Es umfasst Fähigkeiten, Planung, Ziele, Subagenten, Arbeitsabläufe, Plugin-Verwaltung, schreibgeschützte Laufzeitprüfung und Kontextkomprimierung.', '### Wann man es wählt', 'Beginnen Sie hier mit alltäglicher Codierung, Dateiarbeit und Recherche. Im Standardmodus können auch Skripts geschrieben und Dateien stapelweise verarbeitet werden. PTC ändert die Organisation von Toolaufrufen; Für Batch-Aufgaben ist es nicht erforderlich.', ].join('\n\n\n\n'), @@ -382,7 +382,7 @@ export const guideDe = { guideCordisIntro: 'Wählen Sie den Erstellermodus für eine neue Aufgabe. Beschreiben Sie die gewünschte Funktion, wo sie angezeigt werden soll und wie Sie sie überprüfen.', guideCordisExplanation: [ '### Was Sie erstellen können', - 'Der Erstellermodus umfasst die Standardaufgabentools sowie eine Laufzeitprüfung und Anleitungen zum Erstellen von Cordis-Plugins und Agent-Voreinstellungen. Es kann ein Plugin erstellt werden, das eine Funktion oder Benutzeroberfläche hinzufügt, oder eine Voreinstellung, die Tools und Eingabeaufforderungen für einen bestimmten Job kombiniert.', + 'Der Erstellermodus konzentriert sich auf die Anpassung von DSH. Er bietet dieselbe schreibgeschützte Laufzeitprüfung und dieselben dsh-doc-Anleitungen wie der Standardmodus. Der Agent kann ein Plugin erstellen, das eine Funktion oder Benutzeroberfläche hinzufügt, oder eine Voreinstellung, die Tools und Eingabeaufforderungen für einen bestimmten Job kombiniert.', '### Plugins und Modi', 'Ein Plugin fügt DSH Funktionen hinzu, beispielsweise ein Tool, eine Dienstverbindung oder einen UI-Eintrag. Ein Modus ist eine Agentenvoreinstellung, die Tools auswählt und definiert, wie der Agent in einer Aufgabe arbeitet. Ein Plugin kann in eine benutzerdefinierte Voreinstellung eingebunden werden.', '### Wie das Ergebnis wirksam wird', @@ -413,7 +413,7 @@ export const guideRu = { guideStandardIntro: 'Выбирайте стандартный режим при запуске новой задачи. Опишите, чего вы хотите добиться, укажите соответствующие файлы и объясните, как проверить результат.', guideStandardExplanation: [ '### Как это работает', - 'Агент напрямую вызывает инструменты для чтения и редактирования файлов, поиска и выполнения команд терминала. Он включает в себя навыки, планирование, цели, субагенты, рабочие процессы, управление плагинами и сжатие контекста.', + 'Агент напрямую вызывает инструменты для чтения и редактирования файлов, поиска и выполнения команд терминала. Он включает в себя навыки, планирование, цели, субагенты, рабочие процессы, управление плагинами, проверку во время выполнения только для чтения и сжатие контекста.', '### Когда это выбирать', 'Начните здесь ежедневное программирование, работу с файлами и исследования. Стандартный режим также позволяет писать сценарии и обрабатывать файлы в пакетном режиме. PTC изменяет организацию вызовов инструментов; для пакетных задач это не требуется.', ].join('\n\n\n\n'), @@ -457,7 +457,7 @@ export const guideRu = { guideCordisIntro: 'Выберите режим «Создатель» для новой задачи. Опишите желаемую возможность, где она должна появиться и как вы ее проверите.', guideCordisExplanation: [ '### Что вы можете создать', - 'Режим Creator включает в себя стандартные инструменты задач, а также проверку во время выполнения и рекомендации по созданию подключаемых модулей Cordis и предустановок агента. Он может создать плагин, добавляющий возможности или пользовательский интерфейс, или предустановку, объединяющую инструменты и подсказки для конкретной работы.', + 'Режим Creator предназначен для настройки DSH. Он предоставляет ту же проверку во время выполнения только для чтения и те же рекомендации dsh-doc, что и стандартный режим. Агент может создать плагин, добавляющий возможности или пользовательский интерфейс, или предустановку, объединяющую инструменты и подсказки для конкретной работы.', '### Плагины и режимы', 'Плагин добавляет к DSH возможности, такие как инструмент, подключение к службе или запись пользовательского интерфейса. Режим — это предустановка агента, которая выбирает инструменты и определяет, как агент работает над задачей. Плагин может быть включен в пользовательский пресет.', '### Как результат вступает в силу', @@ -488,7 +488,7 @@ export const guidePt = { guideStandardIntro: 'Escolha o modo Padrão ao iniciar uma nova tarefa. Descreva o que você deseja realizar, indique os arquivos relevantes e explique como verificar o resultado.', guideStandardExplanation: [ '### Como funciona', - 'O agente chama ferramentas diretamente para ler e editar arquivos, pesquisar e executar comandos de terminal. Inclui habilidades, planejamento, metas, subagentes, fluxos de trabalho, gerenciamento de plugins e compactação de contexto.', + 'O agente chama ferramentas diretamente para ler e editar arquivos, pesquisar e executar comandos de terminal. Inclui habilidades, planejamento, metas, subagentes, fluxos de trabalho, gerenciamento de plugins, inspeção de tempo de execução somente leitura e compactação de contexto.', '### Quando escolher', 'Comece aqui para codificação diária, trabalho de arquivo e pesquisa. O modo padrão também pode escrever scripts e processar arquivos em lotes. PTC altera a forma como as chamadas de ferramenta são organizadas; não é necessário para tarefas em lote.', ].join('\n\n\n\n'), @@ -532,7 +532,7 @@ export const guidePt = { guideCordisIntro: 'Escolha o modo Criador para uma nova tarefa. Descreva o recurso desejado, onde ele deve aparecer e como você o verificará.', guideCordisExplanation: [ '### O que você pode criar', - 'O modo Criador inclui ferramentas de tarefas padrão, além de inspeção de tempo de execução e orientação para criação de Cordis plug-ins e predefinições de agente. Ele pode criar um plug-in que adicione um recurso ou UI, ou uma predefinição que combine ferramentas e prompts para um trabalho específico.', + 'O modo Criador se concentra na personalização do DSH. Ele compartilha a inspeção de tempo de execução somente leitura e a orientação do dsh-doc com o modo Padrão. O agente pode criar um plug-in que adicione um recurso ou UI, ou uma predefinição que combine ferramentas e prompts para um trabalho específico.', '### Plug-ins e modos', 'Um plug-in adiciona recursos a DSH, como uma ferramenta, uma conexão de serviço ou uma entrada de IU. Um modo é uma predefinição de agente que seleciona ferramentas e define como o agente trabalha em uma tarefa. Um plugin pode ser incluído em uma predefinição personalizada.', '### Como o resultado entra em vigor', diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index 3d1d210aeb..db07f996b9 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -3,29 +3,29 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-agent-team/README.md /: - en: cecfe90c9079279f - zh: 58062db454093088 + en: 7dc6eba0f4471f92 + zh: 9fdf11a94995a75d /deepseek-ai-dsh-client-ui-agent-team: en: 39c47e6e926425bf zh: 0fd155c454355e3a /deepseek-ai-dsh-client-ui-agent-team/summary: - en: 88103cec4c91d755 - zh: 6536e4307a5ce122 + en: f856eb1b0b6645d1 + zh: 91fa3b344ec21e66 /deepseek-ai-dsh-client-ui-agent-team/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: ffbcd39a17cd2fb1 - zh: db21ca6ca1cdf853 + en: 8a132e3052543d8e + zh: b51b602604796800 /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: - en: 2f606827b3ab14bc - zh: 7f713d10268e7498 + en: 49312c9357e23060 + zh: ce1a9b52667977e8 /deepseek-ai-dsh-client-ui-agent-team/understand-the-implementation: - en: 24377b9e51d557de - zh: 9205961784386745 + en: 34ad591d4c206d69 + zh: 0f6796c19f4ebfb8 /deepseek-ai-dsh-client-ui-agent-team/further-exploration: - en: 4d9214370681b02e - zh: 4acb21b9ecf25e85 + en: 5bc48efe19557367 + zh: c00e5e1a75d0afa8 /deepseek-ai-dsh-client-ui-agent-team/model-experience: en: 47ebeba07d72759d zh: 8fe8133f6dd845a9 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index 24a7572af0..de0d2545cf 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -1,5 +1,5 @@ --- -description: "Inspect the shared task board from the Web conversation header." +description: "Inspect the shared task board in the Web Session panel's Shared tasks section." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package displays shared tasks below the Subagent tree in one header panel. Host projection frames keep task state current without a refresh control. Ordinary subagent navigation owns the member list and teammate conversations. The Web bundle loads this package; it adds no model-facing input. +This package adds the Shared tasks section to the Session panel, between Subagents and Background jobs. Host projection frames keep task state current without a refresh control. Ordinary subagent navigation owns the member list and teammate conversations. The Web bundle loads this package; it adds no model-facing input. ## Table of Contents @@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings pane, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings pane shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the pane focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings pane, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it; the state and its 12px chevron share the same foreground color. The settings pane shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the pane focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Session panel to see members in the Subagents section and tasks in the Shared tasks section below it. Child conversations keep subagent navigation without a Team switch, including before their subagent address is discovered. The board reads the current Session’s `agentTeam` projection, so it appears only in a Session whose own projection is enabled. The Shared tasks section lists the tasks in progress first, then the pending ones, each in source order, then the completed ones with the latest in source order first, since a task carries no completion time. It shows five tasks and then the Session panel's fold control, “Show {count} more”, which shows the rest and then reads “Show less”; the list folds only when that holds back two tasks or more, and the choice holds for the Session, also after the panel is hidden and shown again. The section is hidden while the Session has no shared tasks and no task-record error, independently of the Subagents section. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. @@ -37,7 +37,7 @@ The [Web bundle](../../bundle/web-app/README.md) loads this package by default. Ready pending tasks use idle, blocked pending tasks use warning, in-progress tasks use ongoing, and completed tasks use done. -The noncollapsible Shared tasks header uses a Checklist icon and completed, in-progress, and pending counts, with zero counts omitted and wording and separators matching the input task list. Compact read-only rows show the subject, status, and a chevron, with 13px primary titles and hover geometry aligned to subagent rows; expanded details use 12px text. Task rows use 7px vertical padding, 6px horizontal padding, and 7px gaps to align their clickable content with subagent rows. All task details start closed; opening one closes the previous task. Details show only the full description when present, followed by a single-line owner label and owner name in the same color with a 4px gap. Long owner names are ellipsized and reveal their full text in a tooltip only when clipped. Task-text and owner tooltips appear after 500ms of hover. Owners display the task's saved `ownerName`, such as `lead` or `reviewer/checker`, independently of loaded subagent catalogs. A task without `ownerName` displays its `ownerId`; a task without either field displays the localized unowned label. The shared menu is 360px wide with 6px outer padding, constrained to fit the viewport. Shared tasks have a 4px top margin rather than a divider. Both section headers keep a 7px icon/title gap and an additional 4px before their counts. Only the menu scrolls; task lists and details have no nested scrolling. Agents mutate tasks through tools; the panel provides no mutation controls. A projection failure appears separately above any retained tasks and remains visible when no tasks exist. +The panel draws the section title, and the title control (`conversation.session.panel.section.actions`, key `shared-tasks`) shows completed, in-progress, and pending counts, with zero counts omitted and wording and separators matching the input task list. Compact read-only rows show the subject, status, and a chevron on one 28px line, with 13px primary titles; expanded details use 12px text and start at the title's edge. Resting the pointer on a collapsed row for 500ms opens a hover card with the full subject, the owner, the description, and the status. Task rows follow the panel's columns, like subagent rows: the status glyph's center 14px from the row start, titles at 30px, and the chevron's center 14px from the row end. All task details start closed; opening one closes the previous task. Details show only the full description when present, followed by a single-line owner label and owner name in the same color with a 4px gap. Long owner names are ellipsized and reveal their full text in a tooltip only when clipped. Owner tooltips appear after 500ms of hover. Owners display the task's saved `ownerName`, such as `lead` or `reviewer/checker`, independently of loaded subagent catalogs. A task without `ownerName` displays its `ownerId`; a task without either field displays the localized unowned label. The Session panel scrolls the board; task lists and details have no nested scrolling. Agents mutate tasks through tools; the panel provides no mutation controls. A projection failure appears separately above any retained tasks and remains visible when no tasks exist. ----- @@ -47,15 +47,15 @@ The noncollapsible Shared tasks header uses a Checklist icon and completed, in-p
Implementation internals — click to expand -The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns pane navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.pane` with key `agent-team`. Disposing the plugin fiber removes its registrations. +The Client export registers its locale dictionaries, its Session panel section with the title control, and its model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns pane navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.pane` with key `agent-team`. Disposing the plugin fiber removes its registrations. -The Subagent catalog owns the shared panel, scrolling, hover, keyboard, and dismissal interactions. This package contributes the task section only below the root conversation’s tree. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph. +The Session panel owns showing, scrolling, and dismissing the section, which registers as `shared-tasks` at `order: 250`. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph. The [Chat visibility policy](../ui-chat/src/client/contract/chat-visibility.ts) hides only historical commands named `team` whose trimmed recorded arguments are exactly `on` or `off` and whose outcome is pending or successful. The remaining receipts use a localized running summary or preserve raw successful output, with a localized completed fallback when that text is empty. Rendering neither reads the current Team projection nor parses English outcome text. Filtering and localization affect only Chat presentation: command records, logs, trajectory, and raw errors remain unchanged. | File | Role | |---|---| -| [`src/client/mount.ts`](src/client/mount.ts) | Locale, catalog-section, and model-menu registrations | +| [`src/client/mount.ts`](src/client/mount.ts) | Locale, Session panel section, and model-menu registrations | | [`src/client/TeamBoard.tsx`](src/client/TeamBoard.tsx) | Projection-derived task section | | [`src/client/locales.ts`](src/client/locales.ts) | Panel and command copy in eight languages | | [`src/index.ts`](src/index.ts) | Inert Host entry | @@ -69,7 +69,7 @@ The [Chat visibility policy](../ui-chat/src/client/contract/chat-visibility.ts) - [Web bundle](../../bundle/web-app/README.md) — mounts the Client plugin by default. - [Agent Teams service](../../team/agent-team/README.md) — authoritative task and projection behavior. -- [Conversation UI](../ui-conversation/README.md) — the stable header slot and addressed-subagent navigation surface. +- [Session panel](../ui-session-panel/README.md) — hosts the Shared tasks section and draws its title. ----- diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index ba3a240d1e..25831c0e1b 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -1,5 +1,5 @@ --- -description: "从 Web 对话标题栏查看共享任务板。" +description: "在 Web 会话面板的「共享任务」分栏中查看共享任务板。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -此包在同一个页头面板中,将共享任务显示在 Subagent 树下方。Host 投影帧持续更新任务状态,无需刷新控件。普通 subagent(子智能体)导航负责成员列表和队友对话。Web bundle 默认加载此包;它不添加模型可见输入。 +此包为会话面板添加「共享任务」分栏,位于「子智能体」与「后台任务」之间。Host 投影帧持续更新任务状态,无需刷新控件。普通 subagent(子智能体)导航负责成员列表和队友对话。Web bundle 默认加载此包;它不添加模型可见输入。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置面板后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置面板将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置面板时聚焦可用的开关。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置面板后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择;状态文字与其 12px 箭头使用相同的前景色。设置面板将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置面板时聚焦可用的开关。新 Session 默认关闭。开启后,打开根会话的会话面板,即可在「子智能体」分栏查看成员,并在其下方的「共享任务」分栏查看任务。子会话保留子智能体导航,不显示 Team 开关,包括尚未发现子代理地址时。任务板读取当前 Session 的 `agentTeam` 投影,因此只在自身投影已开启的 Session 中显示。「共享任务」分栏先列进行中的任务,再列待处理的任务,各按任务原顺序;最后是已完成的任务,原顺序靠后的在前,因为任务没有完成时间。它只显示五个任务,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的任务并变为「收起」;只有能收起两个及以上任务时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变。会话没有共享任务且没有任务记录错误时,隐藏「共享任务」分栏,与「子智能体」分栏互不影响。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 会话记录过模型请求后,从菜单开关关闭团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 @@ -37,7 +37,7 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成 可开始的 pending 任务使用 idle 灰点,被依赖阻塞的 pending 任务使用 warning 橙点,in-progress 任务使用 ongoing loading,completed 任务使用 done 绿点。 -不可折叠的“共享任务”标题使用 Checklist 图标,并显示已完成、进行中和待处理数量;省略零值,文案和分隔符与输入区任务列表一致。紧凑只读行显示主题、状态和展开箭头,13px 主标题与悬停区域对齐子智能体行;展开详情使用 12px 文字。任务行使用 7px 垂直内边距、6px 水平内边距和 7px 间距,使可点击内容与 subagent 行对齐。所有任务详情初始关闭,打开一项会关闭上一项。详情仅显示完整描述(如有),下方以单行显示负责人标签和负责人名称,两者使用相同颜色,间距为 4px。过长的负责人名称以省略号截断,仅在被截断时通过工具提示显示完整内容。任务文字和负责人的工具提示在悬停 500ms 后显示。负责人显示任务保存的 `ownerName`,例如 `lead` 或 `reviewer/checker`,不依赖已加载的 subagent 目录。缺少 `ownerName` 时显示 `ownerId`;两个字段都没有时显示本地化的无负责人标签。共享菜单宽度为 360px,外层内边距为 6px,并受视口可用宽度约束。共享任务上方保留 4px 外边距,不显示分隔线。两个区域标题均保留 7px 图标与文字间距,并在统计数量前额外留出 4px。仅菜单本身滚动,任务列表与详情不单独滚动。Agent 通过工具修改任务;面板不提供修改控件。投影失败以独立警告显示在保留的任务上方,即使没有任务也保持可见。 +分栏标题由面板绘制,标题控件(`conversation.session.panel.section.actions`,键为 `shared-tasks`)显示已完成、进行中和待处理数量;省略零值,文案和分隔符与输入区任务列表一致。紧凑只读行在 28px 的一行中显示主题、状态和展开箭头,主标题 13px;展开详情使用 12px 文字,并从标题边缘开始。指针在收起的行上停留 500ms 后,悬停卡片显示完整主题、负责人、描述和状态。任务行与子智能体行一样遵循面板的列:状态图标中心距行起始 14px,标题从 30px 开始,箭头中心距行末端 14px。所有任务详情初始关闭,打开一项会关闭上一项。详情仅显示完整描述(如有),下方以单行显示负责人标签和负责人名称,两者使用相同颜色,间距为 4px。过长的负责人名称以省略号截断,仅在被截断时通过工具提示显示完整内容。负责人的工具提示在悬停 500ms 后显示。负责人显示任务保存的 `ownerName`,例如 `lead` 或 `reviewer/checker`,不依赖已加载的 subagent 目录。缺少 `ownerName` 时显示 `ownerId`;两个字段都没有时显示本地化的无负责人标签。会话面板负责任务板滚动,任务列表与详情不单独滚动。Agent 通过工具修改任务;面板不提供修改控件。投影失败以独立警告显示在保留的任务上方,即使没有任务也保持可见。 ----- @@ -47,15 +47,15 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成
实现细节——点击展开 -Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责面板导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.pane` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。 +Client export 通过 Cordis effect 注册语言字典、带标题控件的会话面板分栏与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责面板导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.pane` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。 -Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。本包仅在根会话的树下方提供任务区。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。 +会话面板负责分栏的显示、滚动和关闭;分栏注册为 `shared-tasks`,`order: 250`。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。 [Chat 可见性策略](../ui-chat/src/client/contract/chat-visibility.ts) 仅隐藏名称为 `team`、已记录参数去除首尾空白后恰为 `on` 或 `off`,且尚未完成或执行成功的历史命令。其余回执在执行中显示本地化摘要,成功时保留原始结果文本,文本为空则使用本地化的完成提示。渲染既不读取当前 Team 投影,也不解析英文结果文案。过滤与本地化仅影响 Chat 展示:命令记录、日志、轨迹和原始错误均保持不变。 | 文件 | 职责 | |---|---| -| [`src/client/mount.ts`](src/client/mount.ts) | 语言字典、目录任务区和模型菜单注册 | +| [`src/client/mount.ts`](src/client/mount.ts) | 语言字典、会话面板分栏和模型菜单注册 | | [`src/client/TeamBoard.tsx`](src/client/TeamBoard.tsx) | 从投影派生的任务区 | | [`src/client/locales.ts`](src/client/locales.ts) | 八种语言的面板与命令文案 | | [`src/index.ts`](src/index.ts) | 不执行行为的 Host entry | @@ -69,7 +69,7 @@ Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。 - [Web bundle](../../bundle/web-app/README.zh.md)——默认挂载本 Client plugin。 - [Agent Teams 服务](../../team/agent-team/README.zh.md) — 任务和投影行为的权威来源。 -- [会话 UI](../ui-conversation/README.zh.md)——稳定 header slot 与 addressed-subagent 导航表层。 +- [会话面板](../ui-session-panel/README.zh.md)——承载「共享任务」分栏并绘制其标题。 ----- diff --git a/packages/client/ui-agent-team/package.json b/packages/client/ui-agent-team/package.json index b85d87be28..edfe203eb1 100644 --- a/packages/client/ui-agent-team/package.json +++ b/packages/client/ui-agent-team/package.json @@ -34,7 +34,8 @@ "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-chat", "@deepseek-ai/dsh-client-ui-layout", - "@deepseek-ai/dsh-client-ui-primitives" + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel" ], "platform": "web" } @@ -69,7 +70,7 @@ "@deepseek-ai/dsh-client-ui-model-selection": "workspace:*", "@deepseek-ai/dsh-client-ui-layout": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", - "@deepseek-ai/dsh-client-ui-subagent": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*" }, "files": [ diff --git a/packages/client/ui-agent-team/src/client/TeamBoard.module.css b/packages/client/ui-agent-team/src/client/TeamBoard.module.css index 3d10436a16..d810d35351 100644 --- a/packages/client/ui-agent-team/src/client/TeamBoard.module.css +++ b/packages/client/ui-agent-team/src/client/TeamBoard.module.css @@ -1,46 +1,18 @@ +/* Rows share the Session panel's columns: the glyph's center 14px from the row + start, text at 30px, and the chevron's center 14px from the row end. */ .board { min-width: 0; - padding: 8px 7px; -} - -.board[data-with-members='true'] { - margin-top: 4px; -} - -.header { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 4px 7px; - margin: 0 0 4px; - padding: 0; -} - -.lead, -.glyph, -.chevron { - display: grid; - flex: none; - place-items: center; - color: var(--dsw-alias-label-tertiary); -} - -.title { - flex: none; - color: var(--dsw-alias-label-primary); - font-size: 13px; - font-weight: 500; - line-height: 24px; } +/* Beside the section title, one line that clips before the title does. */ .progress { - margin-inline-start: 4px; + min-width: 0; + overflow: hidden; color: var(--dsw-alias-label-tertiary); - font-size: 13px; - font-weight: 400; + font: var(--dsw-font-xxs-12); font-variant-numeric: tabular-nums; - line-height: 20px; - overflow-wrap: anywhere; + text-overflow: ellipsis; + white-space: nowrap; } .tasks { @@ -59,18 +31,16 @@ box-sizing: border-box; display: flex; align-items: center; - gap: 7px; - width: calc(100% + 12px); + gap: 8px; + width: 100%; min-width: 0; - margin: 0 -6px; - padding: 7px 6px; + min-height: 28px; + padding: 4px 6px; border: 0; - border-radius: var(--dsw-radius-md); + border-radius: var(--dsw-radius-sm); background: transparent; color: var(--dsw-alias-label-primary); - font: inherit; - font-size: 13px; - line-height: 17px; + font: var(--dsw-font-xs-13); text-align: left; cursor: pointer; } @@ -86,9 +56,14 @@ } } -.glyph { - width: 14px; - height: 17px; +.glyph, +.chevron { + display: grid; + flex: none; + place-items: center; + width: 16px; + height: 20px; + color: var(--dsw-alias-label-tertiary); } .subject { @@ -113,13 +88,8 @@ transform: rotate(180deg); } -.chevron { - width: 28px; - height: 17px; -} - .details { - padding: 0 0 8px 21px; + padding: 0 6px 8px 30px; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 18px; @@ -156,8 +126,8 @@ .error { display: flex; align-items: flex-start; - gap: 7px; - padding: 8px 0; + gap: 8px; + padding: 5px 6px; color: var(--dsw-alias-state-error-primary); font-size: 12px; line-height: 18px; diff --git a/packages/client/ui-agent-team/src/client/TeamBoard.tsx b/packages/client/ui-agent-team/src/client/TeamBoard.tsx index d6d0538fa9..a3aa0b60b2 100644 --- a/packages/client/ui-agent-team/src/client/TeamBoard.tsx +++ b/packages/client/ui-agent-team/src/client/TeamBoard.tsx @@ -1,23 +1,37 @@ -import { useState } from 'react' +/** Shared tasks section of the Session panel: the task rows and the progress beside the section title. */ +import { useMemo, useState } from 'react' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { TeamTaskView, TeamTaskId } from '@deepseek-ai/dsh-agent-team/client' +import type { TeamProjection, TeamTaskView, TeamTaskId } from '@deepseek-ai/dsh-agent-team/client' import type {} from '@deepseek-ai/dsh-api-session-controller/client' import { - IconChecklistOutlineRegular, IconChevronDownOutlineRegular, + HoverCard, HoverCardGroup, IconChevronDownOutlineRegular, StateDot, Tooltip, type StateDotState, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type {} from '@deepseek-ai/dsh-client-ui-subagent/client' +import type { PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { NS, type TeamKey } from './locales.ts' +import type { createTeamBoardStore } from './team-board-store.ts' import css from './TeamBoard.module.css' -/** Full props of the task board below the shared subagent catalog. */ +/** Full props of the shared tasks section body. */ export type TeamBoardProps = - PropsRuntime<'conversation.session.header.actions.subagent.footer'> & PropsLocale + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderFactories + & PropsStore> + & PropsLocale + +/** Tasks the list shows before its fold control holds the rest back. */ +const FOLD_LIMIT = 5 type VisibleTask = TeamTaskView & { status: Exclude } +const NO_TASKS: readonly VisibleTask[] = [] + +/** Full props of the progress beside the section title. */ +export type TeamProgressProps = + PropsRuntime<'conversation.session.panel.section.actions'> & PropsLocale + const statusKeys = { pending: 'status.pending', in_progress: 'status.in_progress', completed: 'status.completed', } satisfies Record @@ -26,6 +40,26 @@ const dotStates = { pending: 'idle', in_progress: 'ongoing', completed: 'done', } satisfies Record +function visibleTasks(team: TeamProjection): VisibleTask[] { + return team.tasks.filter((task): task is VisibleTask => task.status !== 'deleted') +} + +/** + * Order the tasks for the list: the ones in progress, then the pending ones, + * each in source order, then the completed ones with the latest in source + * order first. A task carries no completion time, so source order stands in + * for it. + * @param tasks - the visible tasks in source order. + * @returns the tasks in display order. + */ +function listOrder(tasks: readonly VisibleTask[]): VisibleTask[] { + return [ + ...tasks.filter(task => task.status === 'in_progress'), + ...tasks.filter(task => task.status === 'pending'), + ...tasks.filter(task => task.status === 'completed').reverse(), + ] +} + function progressLabel(tasks: readonly VisibleTask[], t: TeamBoardProps['t']): string { const completed = tasks.filter(task => task.status === 'completed').length const active = tasks.filter(task => task.status === 'in_progress').length @@ -37,7 +71,7 @@ function progressLabel(tasks: readonly VisibleTask[], t: TeamBoardProps['t']): s ].join('\u2002·\u2002') } -function TaskRow({ task, rootId, expanded, onToggle, t }: Pick & { +function TaskRow({ task, rootId, expanded, onToggle, renderFactorySlot, t }: Pick & { task: VisibleTask rootId: SessionId expanded: boolean @@ -46,23 +80,35 @@ function TaskRow({ task, rootId, expanded, onToggle, t }: Pick - - - + + + + + {task.subject} + + + )} + content={renderFactorySlot('conversation.session.panel.details', { + title: task.subject, + lines: [t('hover.owner', { name: owner }), ...task.description ? [task.description] : []], + status: { state, label: status }, + })} + /> {expanded && (
{task.description &&

{task.description}

} @@ -78,35 +124,66 @@ function TaskRow({ task, rootId, expanded, onToggle, t }: Pick (state.projectionsBySession[sessionId]?.values.subagentCatalog?.length ?? 0) > 0) + const unfolded = useStore(state => state.unfolded) const [expandedTaskId, setExpandedTaskId] = useState(null) + const ordered = useMemo(() => team?.enabled === true ? listOrder(visibleTasks(team)) : NO_TASKS, [team]) if (!team?.enabled) return null - const tasks = team.tasks.filter((task): task is VisibleTask => task.status !== 'deleted') - const failure = team.failure === undefined ? null : ( -
{t('failure', { message: team.failure })}
- ) - if (tasks.length === 0) return failure === null ? null :
{failure}
+ if (ordered.length === 0 && team.failure === undefined) return null + // Folding holds back two tasks or more, since the fold control takes a row itself. + const foldable = ordered.length > FOLD_LIMIT + 1 + const tasks = foldable && !unfolded ? ordered.slice(0, FOLD_LIMIT) : ordered + const label = unfolded ? t('list.less') : t('list.more', { count: ordered.length - FOLD_LIMIT }) return ( -
-

- - {t('tasks')} - {progressLabel(tasks, t)} -

- {failure} -
    - {tasks.map(task => ( - { setExpandedTaskId(current => current === task.id ? null : task.id) }} - t={t} - /> - ))} -
-
+
+ {team.failure !== undefined && ( +
{t('failure', { message: team.failure })}
+ )} + {tasks.length > 0 && ( + // Moving between rows swaps their hover cards without another dwell. + +
    + {tasks.map(task => ( + { setExpandedTaskId(current => current === task.id ? null : task.id) }} + renderFactorySlot={renderFactorySlot} + t={t} + /> + ))} +
+
+ )} + {foldable && renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded, + label, + name: t('list.foldName', { label }), + onToggle: () => { actions.unfoldedSet(!unfolded) }, + })} +
) } + +/** + * Render the tasks' progress beside the section title, one line that clips. + * @param props - the `agentTeam` projection and copy. + * @returns the progress phrase, or null without visible tasks. + */ +export function TeamProgress({ useProjection, t }: TeamProgressProps) { + const team = useProjection('agentTeam') + if (!team?.enabled) return null + const progress = progressLabel(visibleTasks(team), t) + if (progress === '') return null + return {progress} +} diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index 17797b2eb3..3ff5b8f5ee 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -39,16 +39,12 @@ .state, .chevron { flex: none; -} - -.state { color: var(--dsw-alias-label-tertiary); } .chevron { width: 12px; height: 12px; - color: var(--dsw-alias-menu-icon); } .pane { diff --git a/packages/client/ui-agent-team/src/client/index.ts b/packages/client/ui-agent-team/src/client/index.ts index 23de9e7ee5..08484146ff 100644 --- a/packages/client/ui-agent-team/src/client/index.ts +++ b/packages/client/ui-agent-team/src/client/index.ts @@ -4,7 +4,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import { registerAgentTeamUi } from './mount.ts' export { inject } from './mount.ts' -export type { TeamBoardProps } from './TeamBoard.tsx' +export type { TeamBoardProps, TeamProgressProps } from './TeamBoard.tsx' export type { TeamKey } from './locales.ts' /** diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts index f7bba69ff8..33fb6c330f 100644 --- a/packages/client/ui-agent-team/src/client/locales.ts +++ b/packages/client/ui-agent-team/src/client/locales.ts @@ -8,12 +8,14 @@ export const zh = { 'progress.completed': '{count} 已完成', 'progress.active': '{count} 进行中', 'progress.pending': '{count} 待处理', + 'list.more': '显示其余 {count} 个', + 'list.less': '收起', + 'list.foldName': '{label}(共享任务)', 'command.title': '智能体团队协作', 'command.running': '执行中', 'command.done': '已完成', 'command.failed': '执行失败', 'command.failedReason': '执行失败:{reason}', - trigger: '任务板', 'mode.label': '开启智能体团队协作', 'mode.on': '开启', 'mode.off': '关闭', @@ -32,6 +34,7 @@ export const zh = { tasks: '共享任务', owner: '负责人', unowned: '未分配', + 'hover.owner': '负责人:{name}', blocked: '被依赖阻塞', 'status.pending': '待处理', 'status.in_progress': '进行中', @@ -46,12 +49,14 @@ export const en = { 'progress.completed': '{count} completed', 'progress.active': '{count} in progress', 'progress.pending': '{count} pending', + 'list.more': 'Show {count} more', + 'list.less': 'Show less', + 'list.foldName': '{label} (shared tasks)', 'command.title': 'Agent teamwork', 'command.running': 'Running', 'command.done': 'Completed', 'command.failed': 'Failed', 'command.failedReason': 'Failed: {reason}', - trigger: 'Task board', 'mode.label': 'Enable agent teamwork', 'mode.on': 'On', 'mode.off': 'Off', @@ -70,6 +75,7 @@ export const en = { tasks: 'Shared tasks', owner: 'Owner', unowned: 'Unowned', + 'hover.owner': 'Owner: {name}', blocked: 'Blocked by dependencies', 'status.pending': 'Pending', 'status.in_progress': 'In progress', @@ -81,6 +87,9 @@ export const ja = { 'progress.completed': '{count}件完了', 'progress.active': '{count}件進行中', 'progress.pending': '{count}件保留中', + 'list.more': '残り{count}件を表示', + 'list.less': '折りたたむ', + 'list.foldName': '{label}(共有タスク)', 'command.title': 'エージェント連携', 'command.running': '実行中', 'command.done': '完了', @@ -97,7 +106,6 @@ export const ja = { 'disable.cancel': 'キャンセル', 'disable.confirm': '無効にする', 'disable.close': '閉じる', - 'trigger': 'タスクボード', 'loading': 'タスクボードを読み込み中…', 'unavailable': 'タスクボードは利用できません', 'failure': '保存されたタスクレコードが無効です: {message}', @@ -105,6 +113,7 @@ export const ja = { 'tasks': '共有タスク', 'owner': 'オーナー', 'unowned': 'オーナーなし', + 'hover.owner': '担当:{name}', 'blocked': '依存関係によりブロック中', 'status.pending': '保留中', 'status.in_progress': '進行中', @@ -116,6 +125,9 @@ export const es = { 'progress.completed': '{count} completado', 'progress.active': '{count} en progreso', 'progress.pending': '{count} pendiente', + 'list.more': 'Mostrar {count} más', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (tareas compartidas)', 'command.title': 'Colaboración entre agentes', 'command.running': 'En ejecución', 'command.done': 'Completado', @@ -132,7 +144,6 @@ export const es = { 'disable.cancel': 'Cancelar', 'disable.confirm': 'Confirmar desactivación', 'disable.close': 'Cerrar', - trigger: 'Tablero de tareas', loading: 'Cargando tablero de tareas…', unavailable: 'El tablero de tareas no está disponible', failure: 'Registro de tarea persistente no válido: {message}', @@ -140,6 +151,7 @@ export const es = { tasks: 'Tareas compartidas', owner: 'propietario', unowned: 'Sin dueño', + 'hover.owner': 'Responsable: {name}', blocked: 'Bloqueado por dependencias', 'status.pending': 'Pendiente', 'status.in_progress': 'En progreso', @@ -151,6 +163,9 @@ export const fr = { 'progress.completed': '{count} terminé', 'progress.active': '{count} en cours', 'progress.pending': '{count} en attente', + 'list.more': 'Afficher {count} de plus', + 'list.less': 'Afficher moins', + 'list.foldName': '{label} (tâches partagées)', 'command.title': 'Collaboration entre agents', 'command.running': 'En cours', 'command.done': 'Terminé', @@ -167,7 +182,6 @@ export const fr = { 'disable.cancel': 'Annuler', 'disable.confirm': 'Confirmer la désactivation', 'disable.close': 'Fermer', - trigger: 'Tableau des tâches', loading: 'Chargement du tableau des tâches…', unavailable: 'Le tableau des tâches n’est pas disponible', failure: 'Enregistrement de tâche persistant non valide : {message}', @@ -175,6 +189,7 @@ export const fr = { tasks: 'Tâches partagées', owner: 'Propriétaire', unowned: 'Sans propriétaire', + 'hover.owner': 'Responsable : {name}', blocked: 'Bloqué par les dépendances', 'status.pending': 'En attente', 'status.in_progress': 'En cours', @@ -186,6 +201,9 @@ export const de = { 'progress.completed': '{count} abgeschlossen', 'progress.active': '{count} in Bearbeitung', 'progress.pending': '{count} ausstehend', + 'list.more': '{count} weitere anzeigen', + 'list.less': 'Weniger anzeigen', + 'list.foldName': '{label} (geteilte Aufgaben)', 'command.title': 'Agentenzusammenarbeit', 'command.running': 'Wird ausgeführt', 'command.done': 'Abgeschlossen', @@ -202,7 +220,6 @@ export const de = { 'disable.cancel': 'Abbrechen', 'disable.confirm': 'Deaktivierung bestätigen', 'disable.close': 'Schließen', - trigger: 'Aufgabenübersicht', loading: 'Aufgabenübersicht wird geladen…', unavailable: 'Aufgabenübersicht ist nicht verfügbar', failure: 'Ungültiger gespeicherter Aufgabeneintrag: {message}', @@ -210,6 +227,7 @@ export const de = { tasks: 'Geteilte Aufgaben', owner: 'Besitzer', unowned: 'Unbesessen', + 'hover.owner': 'Zuständig: {name}', blocked: 'Blockiert durch Abhängigkeiten', 'status.pending': 'Ausstehend', 'status.in_progress': 'In Bearbeitung', @@ -221,6 +239,9 @@ export const ru = { 'progress.completed': '{count} завершено', 'progress.active': '{count} в процессе', 'progress.pending': '{count} в ожидании', + 'list.more': 'Показать ещё {count}', + 'list.less': 'Свернуть', + 'list.foldName': '{label} (общие задачи)', 'command.title': 'Совместная работа агентов', 'command.running': 'Выполняется', 'command.done': 'Завершено', @@ -237,7 +258,6 @@ export const ru = { 'disable.cancel': 'Отмена', 'disable.confirm': 'Подтвердить отключение', 'disable.close': 'Закрыть', - trigger: 'Доска задач', loading: 'Загрузка доски задач…', unavailable: 'Доска задач недоступна', failure: 'Недопустимая сохранённая запись задачи: {message}', @@ -245,6 +265,7 @@ export const ru = { tasks: 'Общие задачи', owner: 'Владелец', unowned: 'Невладеющий', + 'hover.owner': 'Ответственный: {name}', blocked: 'Заблокировано зависимостями', 'status.pending': 'Ожидается', 'status.in_progress': 'В процессе', @@ -256,6 +277,9 @@ export const pt = { 'progress.completed': '{count} concluído', 'progress.active': '{count} em andamento', 'progress.pending': '{count} pendente', + 'list.more': 'Mostrar mais {count}', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (tarefas compartilhadas)', 'command.title': 'Colaboração entre agentes', 'command.running': 'Em execução', 'command.done': 'Concluído', @@ -272,7 +296,6 @@ export const pt = { 'disable.cancel': 'Cancelar', 'disable.confirm': 'Confirmar desativação', 'disable.close': 'Fechar', - trigger: 'Quadro de tarefas', loading: 'Carregando quadro de tarefas…', unavailable: 'O quadro de tarefas não está disponível', failure: 'Registro de tarefa persistente inválido: {message}', @@ -280,6 +303,7 @@ export const pt = { tasks: 'Tarefas compartilhadas', owner: 'Proprietário', unowned: 'Sem dono', + 'hover.owner': 'Responsável: {name}', blocked: 'Bloqueado por dependências', 'status.pending': 'Pendente', 'status.in_progress': 'Em andamento', diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index c2dec89b0a..c84e653564 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -2,7 +2,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-api-session-controller/client' -import type {} from '@deepseek-ai/dsh-client-ui-subagent/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' @@ -12,7 +12,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx' import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from './TeamModeToggle.tsx' -import { TeamBoard } from './TeamBoard.tsx' +import { TeamBoard, TeamProgress } from './TeamBoard.tsx' +import { createTeamBoardStore } from './team-board-store.ts' import { TeamCommandRow } from './TeamCommandRow.tsx' import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts' @@ -27,12 +28,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { export const inject = ['slots', 'locale'] /** - * Register the task-board dictionaries and subagent catalog sections. - * The panel reads the root Session’s `agentTeam` projection through standard Session hooks. + * Register the task-board dictionaries and the Session panel's shared tasks section. + * The section reads the root Session’s `agentTeam` projection through standard Session hooks. * @param ctx - Client Context carrying the injected locale and slot services. */ export function registerAgentTeamUi(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'client-ui-agent-team: dictionaries') + const t = ctx.locale.bind(NS) ctx.slots.inject('conversation.chat.commandview', () => ctx.slots.register({ name: 'conversation.chat.commandview', key: 'team', locale: NS, }, TeamCommandRow)) @@ -68,7 +70,20 @@ export function registerAgentTeamUi(ctx: ClientContext): void { }, TeamModePane)) }) }) - ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'agent-team', locale: NS, - }, TeamBoard)) + ctx.slots.inject('conversation.session.panel.section', function* () { + yield ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'shared-tasks', + // After subagents (200), before background jobs (300). + order: 250, + label: () => t('tasks'), + locale: NS, + store: createTeamBoardStore(), + }, TeamBoard) + yield ctx.slots.register({ + name: 'conversation.session.panel.section.actions', + key: 'shared-tasks', + locale: NS, + }, TeamProgress) + }) } diff --git a/packages/client/ui-agent-team/src/client/team-board-store.ts b/packages/client/ui-agent-team/src/client/team-board-store.ts new file mode 100644 index 0000000000..312f7d72e4 --- /dev/null +++ b/packages/client/ui-agent-team/src/client/team-board-store.ts @@ -0,0 +1,38 @@ +/** + * Whether the user unfolded the shared tasks list of the Session panel. The + * registration declares it as an exclusive store, so each Session keeps its + * own while its scope is retained, across hiding and showing the panel. + */ + +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' + +/** The fold of one Session's shared tasks list. */ +export interface TeamBoardState { + /** Whether the list shows every task instead of holding back the tasks past its limit. */ + unfolded: boolean +} + +/** The shared tasks store's write set. */ +type TeamBoardActions = { + unfoldedSet: (draft: TeamBoardState, unfolded: boolean) => void +} + +/** + * Declare the shared tasks section's store. + * @returns the store handle to declare on the registration. + */ +export function createTeamBoardStore(): EngineStoreHandle { + return defineStore({ + init: (): TeamBoardState => ({ unfolded: false }), + actions: { + /** + * Record the user's choice to show every task or fold the list again. + * @param d - draft state. + * @param unfolded - whether the list now shows every task. + */ + unfoldedSet: (d, unfolded: boolean) => { + d.unfolded = unfolded + }, + }, + }) +} diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index 95011ef4cf..22def8176a 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -5,9 +5,10 @@ import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from '../src/client/TeamModeToggle.tsx' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import { TeamBoard } from '../src/client/TeamBoard.tsx' +import { TeamBoard, TeamProgress } from '../src/client/TeamBoard.tsx' import { TeamCommandRow } from '../src/client/TeamCommandRow.tsx' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected } from '../src/client/TeamDisableConfirmation.tsx' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { apply, inject } from '../src/client/index.ts' import { apply as nodeApply } from '../src/index.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -20,43 +21,52 @@ async function bench() { const collapseHeader = ctx.slots.register({ name: 'root', children: { - 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, 'conversation.input.model': { kind: 'single', scope: 'session' }, 'shell.overlay': { kind: 'list', scope: 'root' }, }, } as never, () => null) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() - const entry = () => ctx.slots.entries('conversation.session.header.actions.subagent.footer') + const entry = () => ctx.slots.entries('conversation.session.panel.section') .find(candidate => candidate.component === TeamBoard) - return { ctx, fiber, entry, collapseHeader } + const progress = () => ctx.slots.entries('conversation.session.panel.section.actions') + .find(candidate => candidate.component === TeamProgress) + return { ctx, fiber, entry, progress, collapseHeader } } describe('task-board browser plugin', () => { - it('registers a disposable root task-board section without navigation or Team Remote services', async () => { + it('registers a disposable shared tasks section with its progress, without navigation or Team Remote services', async () => { const b = await bench() expect(inject).toEqual(['slots', 'locale']) expect(b.entry()).toMatchObject({ - options: { id: 'agent-team' }, + options: { id: 'shared-tasks', order: 250 }, locale: 'agent-team', }) expect(b.entry()!.inject).toBeUndefined() + expect(resolveSlotLabel(b.entry()!.options.label)).toBe('Shared tasks') + expect(b.progress()).toMatchObject({ options: { key: 'shared-tasks' }, locale: 'agent-team' }) expect(b.ctx.slots.entries('conversation.session.header.actions')).toHaveLength(0) const t = b.ctx.locale.bind('agent-team') - expect(t('trigger')).toBe('Task board') + expect(t('tasks')).toBe('Shared tasks') await b.fiber.dispose() expect(b.entry()).toBeUndefined() + expect(b.progress()).toBeUndefined() expect(t('empty')).toBe('empty') }) - it('re-registers when the conversation header slot is declared again', async () => { + it('re-registers when the section slot is declared again', async () => { const b = await bench() expect(b.entry()).toBeDefined() b.collapseHeader() expect(b.entry()).toBeUndefined() b.ctx.slots.register({ name: 'root', - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, + children: { + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + }, } as never, () => null) await Promise.resolve() expect(b.entry()).toBeDefined() diff --git a/packages/client/ui-agent-team/tests/team-board.client.spec.tsx b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx index f60eb99e4a..7f81bcc470 100644 --- a/packages/client/ui-agent-team/tests/team-board.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx @@ -8,8 +8,10 @@ import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-sess import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import { TeamBoard, type TeamBoardProps } from '../src/client/TeamBoard.tsx' +import { TeamBoard, TeamProgress, type TeamBoardProps, type TeamProgressProps } from '../src/client/TeamBoard.tsx' +import { createTeamBoardStore } from '../src/client/team-board-store.ts' import { en, zh } from '../src/client/locales.ts' +import type { PanelDetailsProps, PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' afterEach(() => { cleanup() @@ -46,11 +48,35 @@ function summary(id: SessionId, title?: string): SessionSummary { } } +/** One Session's board store, as the registration mints it. */ +type BoardStore = ReturnType['create']> + +/** + * The Session panel's Factories as this suite renders them: the fold control as a button with its state, name, and + * label, and a row's details as one element per part in order. ui-session-panel's own suite owns their markup. + */ +function renderPanelFactory(name: string, input: object) { + if (name === 'conversation.session.panel.details') { + const { title, lines = [], status, facts = [] } = input as PanelDetailsProps + return ( +
+ {title !== undefined &&
{title}
} + {lines.map(line =>
{line}
)} + {status !== undefined &&
{status.label}
} + {facts.length > 0 &&
{facts.map(fact => {fact.label})}
} +
+ ) + } + const fold = input as PanelFoldProps + return +} + function bench(options: { projections?: Projections sessionId?: SessionId byId?: Record value?: TeamProjection + store?: BoardStore } = {}) { const sessionId = options.sessionId ?? SESSION const byId = options.byId ?? { [SESSION]: summary(SESSION) } @@ -63,12 +89,14 @@ function bench(options: { const value = state.projectionsBySession[sessionId]?.values.agentTeam return selector === undefined ? value : selector(value) })) as TeamBoardProps['useProjection'] + const store = options.store ?? createTeamBoardStore().create() const props = { sessionId, useProjection, useSessions: bindSnapshotSelector(sessions), + useStore: bindSnapshotSelector(store), actions: store.actions, renderFactorySlot: renderPanelFactory, t: makeTranslate(zh, commonZh), } as TeamBoardProps - return { props, sessions } + return { props, sessions, store } } function setProjectionSnapshot( @@ -108,14 +136,20 @@ function enableTooltips(): void { vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) } +/** The text the progress beside the section title renders for these props. */ +function progressText(props: TeamBoardProps): string { + const progress: Pick = { useProjection: props.useProjection, t: props.t } + const view = render() + const text = view.container.textContent + view.unmount() + return text +} + describe('TeamBoard', () => { - it('shows a nonclickable Checklist header and compact initially closed rows', () => { + it('leaves the title to the panel and shows compact initially closed rows', () => { const b = bench() render() - const heading = screen.getByRole('heading') - expect(heading.textContent).toBe(`${zh.tasks}${b.props.t('progress.active', { count: 1 })}`) - expect(heading.querySelector('button')).toBeNull() - expect(heading.querySelector('[data-icon="dsw-icon-checklist-outline-regular"]')).toBeTruthy() + expect(screen.queryByRole('heading')).toBeNull() expect(screen.getAllByRole('button')).toEqual([row()]) expect(row().getAttribute('aria-expanded')).toBe('false') expect(row().textContent).toBe(task.subject) @@ -163,7 +197,7 @@ describe('TeamBoard', () => { expect(screen.getAllByRole('button').every(button => button.getAttribute('aria-expanded') === 'false')).toBe(true) }) - it('preserves source order, keeps completed tasks, and excludes deleted tombstones from rows and counts', () => { + it('lists tasks in progress, then pending, then completed, and excludes deleted tombstones from rows and counts', () => { const b = bench({ value: { ...team, tasks: [ { ...task, subject: 'Pending first', status: 'pending', ready: true }, { ...task, id: TASK_2, subject: 'Completed second', status: 'completed' }, @@ -171,10 +205,10 @@ describe('TeamBoard', () => { { ...task, id: 'deleted' as TeamTaskId, subject: 'Deleted task', status: 'deleted' }, ] } }) render() - expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Pending first', 'Completed second', 'Active third']) - expect(screen.getByRole('heading').textContent).toBe(`${zh.tasks}${[ + expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Active third', 'Pending first', 'Completed second']) + expect(progressText(b.props)).toBe([ b.props.t('progress.completed', { count: 1 }), b.props.t('progress.active', { count: 1 }), b.props.t('progress.pending', { count: 1 }), - ].join('\u2002·\u2002')}`) + ].join('\u2002·\u2002')) expect(screen.queryByText('Deleted task')).toBeNull() expect(row('Pending first').querySelector('[data-state="idle"]')).toBeTruthy() expect(row('Completed second').querySelector('[data-state="done"]')).toBeTruthy() @@ -184,6 +218,65 @@ describe('TeamBoard', () => { expect(screen.getByText(task.description)).toBeTruthy() }) + /** A task named by its id. */ + const named = (id: string, status: TeamTask['status']): TeamTask => ({ ...task, id: id as TeamTaskId, subject: id, status, ready: true }) + /** The task rows' names in display order. */ + const shownTasks = (): (string | null)[] => [...document.querySelectorAll('[data-team-task]')].map(item => item.getAttribute('data-team-task')) + const fold = (): HTMLElement | null => document.querySelector('[data-fold]') + + it('keeps source order within the tasks in progress and the pending ones, and lists the latest completed task first', () => { + const b = bench({ value: { ...team, tasks: [ + named('done-1', 'completed'), named('wait-1', 'pending'), named('run-1', 'in_progress'), named('done-2', 'completed'), + named('wait-2', 'pending'), named('run-2', 'in_progress'), + ] } }) + render() + expect(shownTasks()).toEqual(['run-1', 'run-2', 'wait-1', 'wait-2', 'done-2', 'done-1']) + // Six tasks show in full: folding would hold back one task for a control that takes a row itself. + expect(fold()).toBeNull() + }) + + it('holds two tasks back from seven, behind a fold control that shows them and folds again', () => { + const tasks = [ + named('done-1', 'completed'), named('done-2', 'completed'), named('run-1', 'in_progress'), named('wait-1', 'pending'), + named('wait-2', 'pending'), named('wait-3', 'pending'), named('wait-4', 'pending'), + ] + const b = bench({ value: { ...team, tasks } }) + render() + expect(shownTasks()).toEqual(['run-1', 'wait-1', 'wait-2', 'wait-3', 'wait-4']) + const control = fold() as HTMLElement + expect([control.textContent, control.getAttribute('aria-label'), control.getAttribute('aria-expanded')]) + .toEqual(['显示其余 2 个', '显示其余 2 个(共享任务)', 'false']) + // The control follows the list instead of joining it, so the list holds only tasks. + expect(screen.getByRole('list').contains(control)).toBe(false) + fireEvent.click(control) + expect(shownTasks()).toEqual(['run-1', 'wait-1', 'wait-2', 'wait-3', 'wait-4', 'done-2', 'done-1']) + expect([fold()?.textContent, fold()?.getAttribute('aria-label'), fold()?.getAttribute('aria-expanded')]).toEqual(['收起', '收起(共享任务)', 'true']) + fireEvent.click(fold() as HTMLElement) + expect(shownTasks()).toHaveLength(5) + // The progress beside the title counts every task, shown or held back. + expect(progressText(b.props)).toBe([ + b.props.t('progress.completed', { count: 2 }), b.props.t('progress.active', { count: 1 }), b.props.t('progress.pending', { count: 4 }), + ].join('\u2002·\u2002')) + }) + + it('keeps the fold in the Session store while the section is unmounted', () => { + const store = createTeamBoardStore().create() + const tasks = Array.from({ length: 8 }, (_, index) => named(`wait-${index}`, 'pending')) + const first = render() + fireEvent.click(fold() as HTMLElement) + expect(store.getSnapshot()).toEqual({ unfolded: true }) + first.unmount() + render() + expect(shownTasks()).toHaveLength(8) + expect(fold()?.getAttribute('aria-expanded')).toBe('true') + }) + + it.each(Object.entries({ zh, en }))('names the fold control with its visible text first in %s', (_locale, copy) => { + for (const label of [copy['list.more'].replace('{count}', '3'), copy['list.less']]) { + expect(copy['list.foldName'].replace('{label}', label).startsWith(label)).toBe(true) + } + }) + it('announces blocked status without displaying readiness, dependencies, scopes, warnings, or task ids', () => { const { ownerId: _ownerId, ownerName: _ownerName, ...unowned } = task const b = bench({ value: { ...team, tasks: [ @@ -244,6 +337,7 @@ describe('TeamBoard', () => { const b = bench() render() setProjection(b.sessions, SESSION, { ...team, enabled: false }) + expect(progressText(b.props)).toBe('') expect(screen.queryByRole('region')).toBeNull() expect(screen.queryByText(task.subject)).toBeNull() setProjection(b.sessions, SESSION, team) @@ -283,7 +377,6 @@ describe('TeamBoard', () => { const view = render() expect(screen.getByRole('alert').textContent).toBe('任务记录无效:revision is not contiguous') expect(row()).toBeTruthy() - expect(screen.getByRole('heading')).toBeTruthy() for (const tasks of [[], [{ ...task, status: 'deleted' as const }]]) { setProjectionSnapshot(b.sessions, SESSION, { state: 'ready', error: null, values: { agentTeam: { enabled: true, tasks, failure: 'invalid task' }, @@ -293,11 +386,8 @@ describe('TeamBoard', () => { expect(alert.textContent).toBe('任务记录无效:invalid task') expect(screen.getAllByRole('alert')).toHaveLength(1) expect(view.container.textContent).toBe(alert.textContent) - expect(view.container.querySelector('[data-with-members="true"]')).toBeNull() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByRole('region')).toBeNull() expect(screen.queryByText(zh.empty)).toBeNull() - expect(document.querySelector('[data-team-panel]')).toBeNull() + expect(progressText(b.props)).toBe('') } setProjection(b.sessions, SESSION, { enabled: false, tasks: [], failure: 'invalid task' }) expect(view.container.childElementCount).toBe(0) @@ -334,7 +424,7 @@ describe('TeamBoard', () => { it('uses translated English progress and details without Show more or Show less controls', () => { const b = bench() render() - expect(screen.getByRole('heading').textContent).toBe(`${en.tasks}${makeTranslate(en)('progress.active', { count: 1 })}`) + expect(progressText({ ...b.props, t: makeTranslate(en) })).toBe(makeTranslate(en)('progress.active', { count: 1 })) fireEvent.click(row()) expect(ownerValue()).toBe('lead') expect(document.querySelector('[data-team-task-owner]')?.textContent).toBe(`${en.owner}: lead`) @@ -374,36 +464,28 @@ describe('TeamBoard', () => { expect(ownerValue()).toBeNull() }) - it('delays clipped collapsed subject hover by 500ms while keeping keyboard focus immediate', () => { + it('shows the subject, owner, description, and state in a hover card after 500ms, and none while the row is expanded', () => { vi.useFakeTimers() - enableTooltips() - const view = render() + vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' }))) + render() const button = row() - const subject = screen.getByText(task.subject) - const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockReturnValue(80) - vi.spyOn(Element.prototype, 'clientWidth', 'get').mockReturnValue(80) - fireEvent.pointerEnter(button) - act(() => { vi.advanceTimersByTime(500) }) - expect(screen.queryByRole('tooltip')).toBeNull() - fireEvent.pointerLeave(button) - scrollWidth.mockImplementation(function (this: Element) { return this === subject ? 180 : 80 }) - fireEvent.pointerEnter(button) + const anchor = button.parentElement as HTMLElement + const details = (): string[] | null => { + const card = document.querySelector('[data-session-panel-details]') + return card === null ? null : [...card.children].map(child => child.textContent ?? '') + } + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) act(() => { vi.advanceTimersByTime(499) }) - expect(screen.queryByRole('tooltip')).toBeNull() + expect(details()).toBeNull() act(() => { vi.advanceTimersByTime(1) }) - expect(screen.getByRole('tooltip').textContent).toBe(task.subject) - expect(view.container.contains(screen.getByRole('tooltip'))).toBe(false) + expect(details()).toEqual([task.subject, '负责人:lead', task.description, '进行中']) + // Expanding the row shows the same details in place, so the card closes and stays closed. fireEvent.click(button) - expect(row()).toBe(button) - expect(screen.queryByRole('tooltip')).toBeNull() - fireEvent.pointerLeave(button) - fireEvent.pointerEnter(button) + act(() => { vi.advanceTimersByTime(200) }) + expect(details()).toBeNull() + fireEvent.pointerLeave(anchor, { pointerType: 'mouse' }) + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) act(() => { vi.advanceTimersByTime(500) }) - expect(screen.queryByRole('tooltip')).toBeNull() - fireEvent.click(button) - fireEvent.pointerLeave(button) - fireEvent.keyDown(document.body, { key: 'Tab' }) - fireEvent.focus(button) - expect(screen.getByRole('tooltip').textContent).toBe(task.subject) + expect(details()).toBeNull() }) }) diff --git a/packages/client/ui-agent-team/tsconfig.json b/packages/client/ui-agent-team/tsconfig.json index 429b9adac3..b5d6224ca9 100644 --- a/packages/client/ui-agent-team/tsconfig.json +++ b/packages/client/ui-agent-team/tsconfig.json @@ -13,7 +13,7 @@ { "path": "../ui-model-selection" }, { "path": "../ui-layout" }, { "path": "../../core/agent" }, - { "path": "../ui-subagent" }, + { "path": "../ui-session-panel" }, { "path": "../locale/tsconfig.client.json" }, { "path": "../store" }, { "path": "../ui-conversation/tsconfig.client.json" }, diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index a986f761c4..2344d9a693 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -36,11 +36,11 @@ en: 7cc6692b879aa500 zh: e924733c88b526c9 /deepseek-ai-dsh-client-ui-chat/grouped-rendering: - en: f6d8bbae13a1a8f8 - zh: 96c8f400c215e33d + en: 535345a2de07109e + zh: 39580c340f5ae558 /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: 1b12aa6c505dde3b - zh: 88e1654dd63816d7 + en: dd0f7df1af16d9a6 + zh: 5ff892b8c57edabf /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 70921859ae..fabe865fc0 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -137,6 +137,8 @@ The process group uses a stable `div` layout box, a scroll body, and an uncapped Running group titles, reasoning previews, tool and command rows, the active retry line, and the bottom running status use the shared [TextShimmer](../ui-primitives/README.md#component-catalog). Each row’s text shares one left-to-right highlight, including collapsed group titles; icons and hover chevrons retain their base appearance. Ordinary flow rows sit 4px apart, including adjacent reasoning rows of one Assistant message. An expanded group title has 8px before its content, Assistant responses have 12px from adjacent process rows, and completed-Turn duration/status controls have 16px from their input and from a directly following visible row. A reply that follows the control after folded rows keeps the 12px reply gap, so folding never changes its spacing. Hidden and empty rows, including retained empty slot anchors, add no gap. The running “Deep diving” text retains its blue base while its theme-specific highlight sweeps across it. +Closing assistant messages use 16px SVG boxes for copy and branch actions at the default content font size, with fixed 1px strokes and 28px click targets. SVG boxes do not shrink in the flex row; their size and targets follow the content font-size delta. + The running status shows a whale whose APNG mask inherits the text color. CSS selects the static SVG when reduced motion or forced colors are active, or alpha masks are unsupported. The APNG is a [package asset](../AGENTS.md#dependency-declaration) referenced by the plugin stylesheet; React does not pass image data through DOM styles. Scroll-edge fades initialize when `ResizeObserver` reports the open group's layout; opening the group performs no immediate scroll-dimension read in a layout effect. @@ -158,7 +160,9 @@ Chat waits for initial history before automatic content, scroll, or size updates Chat restores semantic anchors across history prepend and renderer remounts, with browser scroll anchoring disabled on its scrollport only while following the tail. Pinned scroll deliveries without reader movement, and reader input that reaches the floor within subpixel rounding, update follow ownership immediately, before subsequent layout changes can invalidate their floor. Other reader movement remains pending until the sampling interval or `scrollend`, even inside the follow threshold, so layout growth cannot erase small scroll gestures. Under completion-time folding, submitting transcript input or steering immediately restores tail following and clears an older pending reader sample. Under next-message folding, transcript input that no fold batch carries lands on one native animation; steering lands at once under either timing, because the running Turn keeps streaming above its echo. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer. -The turn rail and back-to-bottom button sit outside the clipped transcript. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. +The turn rail and back-to-bottom button sit outside the clipped transcript. The 34px back-to-bottom button centers a 16px chevron with a fixed 1px stroke. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail sits at the scrollport's start edge, which leaves the end gutter to the [Session panel](../ui-session-panel/README.md), and its previews open toward the transcript. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. + +The `conversation.chat.aside` slot holds one Session-level occupant beside the transcript, such as the [Session panel](../ui-session-panel/README.md). Every Chat View occurrence, main or embedded, renders it in a zero-height layer at the top of the Chat frame, positioned like the turn rail, so it stays in place while the transcript scrolls and inherits `--dsh-composer-height` and `--dsh-conversation-viewport-height` from the shared scrollport. The layer stacks above the turn rail and the back-to-bottom button and passes pointer events through. The layer measures nothing: its stylesheet publishes the end gutter, the inline space between the centered transcript column and the frame's end edge, as the `--dsh-chat-aside-gutter` custom property, `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`. The percentage resolves against the layer in the inline sizes of an element whose containing block is the layer, so an occupant sizes and places itself in CSS, and the Chat View neither re-renders nor observes sizes for it. The transcript root uses `overflow-x: visible; overflow-y: clip`: vertical overflow is clipped without creating a scroll container. Sticky Markdown code banners and expanded compaction headers therefore retain the actual conversation scrollport as their reference when no nearer scrolling ancestor exists. Capped process groups and terminal sections keep their own scrollports. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index d50ba90f91..813f1d3234 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -137,6 +137,8 @@ Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载的 运行中的分组标题、思考预览、工具与命令行、当前重试行以及底部运行状态使用共享的 [TextShimmer](../ui-primitives/README.zh.md#component-catalog)。每行的文字共用一道从左到右的高光,包括折叠的分组标题;图标和悬停箭头保留底色。普通流程行之间相隔 4px,同一条 Assistant 消息里相邻的推理行也是如此;展开的分组标题与内容之间相隔 8px;Assistant 回复与相邻过程行之间相隔 12px;每轮完成/耗时控件与其输入、以及紧随其后的可见行之间保留 16px。控件与回复之间隔着已收起的行时,回复保持 12px 回复间距,因此折叠不会改变它的间距。隐藏行与空行(包括保留的空 slot 锚点)不产生间距。“深度求索”运行文字保留蓝色底色,并使用主题专用高光扫过文字。 +助手收尾消息的复制与分支操作在默认内容字号下使用 16px SVG 框、固定 1px 描边与 28px 点击区域。SVG 框不会在 flex 行中收缩;图标与点击区域尺寸均跟随内容字号增量。 + 运行状态显示一只鲸鱼,其 APNG 遮罩继承文字颜色。启用减少动态效果或强制颜色模式、或浏览器不支持 alpha 遮罩时,CSS 选择静态 SVG。APNG 是插件样式表引用的[包资源](../AGENTS.md#dependency-declaration);React 不通过 DOM 样式传递图片数据。 滚动边缘渐隐在 `ResizeObserver` 报告已展开组的布局后初始化;展开组时不会在 layout effect 中立即读取滚动尺寸。 @@ -158,7 +160,9 @@ Chat 等待初始历史就绪后,才允许自动内容、滚动或尺寸更新 Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及到达底部(容许小于 1px 的取整误差)的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。采用完成时收起时,提交正文输入或 steering 会立即恢复跟随底部,并清除先前待处理的读者滚动采样。采用下次消息时收起时,没有折叠批次承载的正文输入用一次原生动画落到底部;steering 在两种时机下都立即落到底部,因为运行中的 Turn 仍在其回显上方持续输出。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 -轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 +轮次轨道与回到底部按钮位于正文裁剪层外。34px 的回到底部按钮居中容纳 16px 箭头,描边固定为 1px。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。轮次轨道贴在滚动容器的起始边,把末端留白让给[会话面板](../ui-session-panel/README.zh.md),预览朝正文方向弹出。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 + +`conversation.chat.aside` slot 放一个位于正文旁边、面向整个会话的组件,例如[会话面板](../ui-session-panel/README.zh.md)。每个 Chat 视图实例(主正文区或嵌入的)都会渲染它:它位于 Chat 外框顶部的零高度图层中,定位方式与轮次轨道相同,因此不随正文滚动,并从共享滚动容器继承 `--dsh-composer-height` 与 `--dsh-conversation-viewport-height`。该图层叠在轮次轨道与回到底部按钮之上,自身不拦截指针事件。图层不做任何测量:它的样式表把末端留白(居中的正文列到外框末端边缘之间的行向空间)发布为自定义属性 `--dsh-chat-aside-gutter`,值为 `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`。其中的百分比在以该图层为包含块的元素的行向尺寸里按图层宽度解析,因此占位组件用 CSS 决定自身的尺寸与位置,Chat 视图既不为它重新渲染,也不为它观察尺寸。 正文根节点使用 `overflow-x: visible; overflow-y: clip`:裁剪纵向溢出,但不创建滚动容器。因此,在没有更近的滚动祖先时,Markdown 代码块的 sticky 头栏和展开的压缩摘要头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。 diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 7e4a3a5f01..56bb503a9a 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -245,6 +245,7 @@ export function apply(ctx: Context): void { 'conversation.chat.flow': { kind: 'single', scope: 'session', inject: CHAT_FLOW_INJECT }, 'conversation.chat.text-interaction': { kind: 'keyed', scope: 'session' }, 'conversation.chat.markdown.fence': { kind: 'hoc', scope: 'session' }, + 'conversation.chat.aside': { kind: 'single', scope: 'session' }, }, store: chatStore, inject: (sessionId: SessionId): ChatViewInjected => { diff --git a/packages/client/ui-chat/src/client/chat/ChatAside.tsx b/packages/client/ui-chat/src/client/chat/ChatAside.tsx new file mode 100644 index 0000000000..1e314c8d41 --- /dev/null +++ b/packages/client/ui-chat/src/client/chat/ChatAside.tsx @@ -0,0 +1,15 @@ +/** The Chat View's aside layer: one Session-level occupant beside the transcript, which the layer's stylesheet tells the end gutter. */ +import { memo } from 'react' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import css from './ChatView.module.css' + +/** + * Render the aside layer with its occupant. The Chat View's `renderSlot` is + * stable per registration, so the layer renders once and transcript updates + * do not re-render it; its geometry is CSS only. + * @param props - the Chat View's slot renderer. + * @returns the zero-height aside layer. + */ +export const ChatAside = memo(function ChatAside({ renderSlot }: Pick, 'renderSlot'>) { + return
{renderSlot('conversation.chat.aside', {})}
+}) diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 1f84e97842..520b899f08 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -356,6 +356,30 @@ /* Floating controls sit outside the clipped transcript. A standalone Chat anchors them to its frame; the shared host supplies the sticky scrollport. */ +/* The aside layer: zero height at the frame's top, sticky in a shared + scrollport so its occupant stays put while the transcript scrolls and + inherits the scrollport's --dsh-composer-height and + --dsh-conversation-viewport-height. Above the turn rail (7) and the + back-to-bottom control (8). It publishes the end gutter, the inline space + between the centered transcript column and the frame's end edge, for the + occupant's inline sizes: the percentage resolves against the layer in an + element whose containing block is the layer, as it does in the + back-to-bottom control's padding below. */ +.asideSlot { + position: absolute; + top: 0; + right: 0; + left: 0; + z-index: 9; + height: 0; + pointer-events: none; + --dsh-chat-aside-gutter: max(0px, calc((100% - var(--dsh-chat-content-width, 100%)) / 2)); +} + +:global([data-conversation-scroll]) .asideSlot { + position: sticky; +} + .toBottomSlot { position: absolute; right: 0; diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index c9143248a1..ef055134cf 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -16,6 +16,7 @@ import type { ChatFlowHookContext, ChatViewSlotProps, OpenFileOptions } from '.. import type { ChatSnapshot } from '../contract/snapshot.ts' import { markdownLabels } from '../markdown-labels.ts' import { TurnNavigator } from './TurnNavigator.tsx' +import { ChatAside } from './ChatAside.tsx' import { mergeTurnRailItems } from './turn-rail-items.ts' import { useTextInteraction } from './text-interaction.ts' import { useChatScroll } from './use-chat-scroll.ts' @@ -239,6 +240,7 @@ export function ChatView({ t={t} /> )} +
- +
)} diff --git a/packages/client/ui-chat/src/client/chat/MessageIconActions.module.css b/packages/client/ui-chat/src/client/chat/MessageIconActions.module.css index 9c211ea186..f808722d9e 100644 --- a/packages/client/ui-chat/src/client/chat/MessageIconActions.module.css +++ b/packages/client/ui-chat/src/client/chat/MessageIconActions.module.css @@ -74,16 +74,16 @@ cursor: pointer; } -/* Action glyphs follow the same px delta as the text they serve; the - assistant completion row gives them two extra pixels. */ +/* Action glyphs follow the content font-size delta. */ .action svg { width: calc(15px + var(--dsh-content-font-delta, 0px)); height: calc(15px + var(--dsh-content-font-delta, 0px)); } .actions[data-clock='end'] .action svg { - width: calc(17px + var(--dsh-content-font-delta, 0px)); - height: calc(17px + var(--dsh-content-font-delta, 0px)); + flex: none; + width: calc(16px + var(--dsh-content-font-delta, 0px)); + height: calc(16px + var(--dsh-content-font-delta, 0px)); } @media (hover: hover) { diff --git a/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css b/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css index c4d495b8d6..2d8166ca68 100644 --- a/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css +++ b/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css @@ -30,7 +30,8 @@ position: absolute; top: calc(var(--turn-rail-band) / 2); - right: 12px; + /* The start edge: the end gutter belongs to the Session panel. */ + left: 12px; width: 28px; /* Fixed-pitch marks never compress: a ladder taller than the band scrolls inside this frame instead of pushing marks under the composer or above @@ -97,14 +98,14 @@ .mark::before { position: absolute; top: 50%; - right: 0; + left: 0; width: 20px; height: 2px; border-radius: 2px; background: var(--dsw-alias-border-l4); content: ''; transform: translateY(-50%) scaleX(0.6); - transform-origin: right center; + transform-origin: left center; transition: transform 140ms ease, background-color 140ms ease; } @@ -142,11 +143,11 @@ .mark:focus-visible::after { position: absolute; - inset: 0 0 0 auto; + inset: 0 auto 0 0; width: 20px; border-radius: inherit; outline: 1px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - /* The scroller clips the right edge; keep the marker's ring inside it. */ + /* The scroller clips the left edge; keep the marker's ring inside it. */ outline-offset: -1px; content: ''; } @@ -158,7 +159,7 @@ calc(var(--turn-preview-center) - var(--turn-preview-height) / 2), calc(100% - var(--turn-preview-height)) ); - right: calc(100% + 10px); + left: calc(100% + 10px); box-sizing: border-box; width: min(300px, calc(100cqw - 120px)); max-height: var(--turn-preview-height); @@ -194,7 +195,7 @@ } @keyframes dsh-turn-preview-enter { - from { opacity: 0; transform: translateX(4px); } + from { opacity: 0; transform: translateX(-4px); } to { opacity: 1; transform: translateX(0); } } diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index 1722c82ecd..345756d09e 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -390,7 +390,7 @@ export type ChatFlowSlotProps = /** Full Chat view props. */ export type ChatViewSlotProps = PropsRuntime<'conversation.view'> - & PropsRenderSlots<'conversation.chat.flow' | 'conversation.chat.text-interaction' | 'conversation.chat.markdown.fence'> + & PropsRenderSlots<'conversation.chat.flow' | 'conversation.chat.text-interaction' | 'conversation.chat.markdown.fence' | 'conversation.chat.aside'> & PropsStore & InjectFace & PropsLocale<'chat'> @@ -431,6 +431,20 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { 'conversation.chat.text-interaction': { kind: 'keyed'; scope: 'session'; owner: TextInteractionSurface } /** Language-keyed layers around one Markdown fence in the Chat flow; the content is the plain code block. */ 'conversation.chat.markdown.fence': { kind: 'hoc'; scope: 'session'; owner: MarkdownDelegateFenceInfo } + /** + * One Session-level occupant beside the transcript, such as a summary + * panel. Every Chat View occurrence renders it in a zero-height layer at + * the top of the Chat frame, which stays in place while the transcript + * scrolls and inherits the shared scrollport's composer and viewport + * heights. The layer passes pointer events through; the occupant + * positions itself in it, enables its own pointer events, and keeps + * within the end gutter to stay clear of the transcript column. The + * layer publishes that gutter, the inline space between the transcript + * column and the frame's end edge, as the `--dsh-chat-aside-gutter` + * custom property; its percentage resolves in the inline sizes of an + * element whose containing block is the layer. + */ + 'conversation.chat.aside': { kind: 'single'; scope: 'session' } /** Ordered Chat rows and local echoes with viewport-bound visibility hooks. */ 'conversation.chat.flow': { diff --git a/packages/client/ui-chat/src/client/conversation-nodes/command.ts b/packages/client/ui-chat/src/client/conversation-nodes/command.ts index a52b877552..de407aa354 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/command.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/command.ts @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import type { CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, @@ -105,9 +106,7 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver if (match?.event.type === 'compaction/summary') { const data = match.event.data if (Array.isArray(data.summary)) { - const text = data.summary - .map(block => block.type === 'text' ? block.text : '') - .join('') + const text = extractTextContent(data.summary) summary = text.trim() === '' ? null : text } shadowedItemCount = Array.isArray(data.shadowedSeqs) diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 3d891a9a5f..5efab8c1d9 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -1,3 +1,4 @@ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import type { AssistantNodeInjected } from '../src/client/chat/AssistantNodeView.tsx' import type { MessageId } from '@deepseek-ai/dsh-llm/types' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' @@ -105,12 +106,12 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true, runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'settings.general.item': { kind: 'list', scope: 'root' }, }, (_props: { renderSlot?: unknown }) => null) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const registerGroups = withProcessGroups ? undefined : vi.spyOn(runtime.ctx.uiConversation.groups, 'register').mockImplementation(() => () => {}) const chat = await runtime.mount({ inject: [...injectChat], apply: applyChat }) diff --git a/packages/client/ui-chat/tests/aside-styles.client.spec.ts b/packages/client/ui-chat/tests/aside-styles.client.spec.ts new file mode 100644 index 0000000000..d8e612bd10 --- /dev/null +++ b/packages/client/ui-chat/tests/aside-styles.client.spec.ts @@ -0,0 +1,31 @@ +/** + * The Chat aside layer as CSS text. jsdom has no layout, so the rendering + * spec shows where the layer sits but not what it tells its occupant; this + * reads the declarations an occupant's inline sizes depend on. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/client/chat/ChatView.module.css', import.meta.url)), 'utf8') + +function declarationsOf(selector: string): string[] { + const text = css.replace(/\/\*[\s\S]*?\*\//g, ' ') + const rule = new RegExp(`(?:^|[{}])\\s*${selector.replace(/[.[\]():*+^$\\]/g, '\\$&')}\\s*\\{([^{}]*)\\}`).exec(text) + if (rule === null) throw new Error(`no \`${selector}\` rule`) + return (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean) +} + +describe('Chat aside layer', () => { + it('spans the frame at zero height and passes pointer events through', () => { + expect(declarationsOf('.asideSlot')).toEqual(expect.arrayContaining([ + 'position: absolute', 'right: 0', 'left: 0', 'height: 0', 'pointer-events: none', + ])) + }) + + it('publishes the end gutter as half the frame width the transcript column leaves, never negative', () => { + expect(declarationsOf('.asideSlot')).toContain( + '--dsh-chat-aside-gutter: max(0px, calc((100% - var(--dsh-chat-content-width, 100%)) / 2))', + ) + }) +}) diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index 7a6a7c5bcd..1864682b88 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' @@ -77,7 +78,7 @@ async function bench() { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'shell.overlay': { kind: 'list', scope: 'root' }, @@ -87,7 +88,7 @@ async function bench() { const conversation = await runtime.mount({ inject: [...injectConversation], apply: applyConversation, - }) + }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const provide = vi.spyOn(runtime.ctx.uiSession, 'provide') const chat = await runtime.mount({ inject: [...injectChat], apply: applyChat }) const sourceDescriptor = provide.mock.calls[0]?.[0] diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 311679176c..ed04662097 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -500,12 +500,17 @@ function makeHarness( return renderUserContent(owner as UserContentInput, renderImages, props.t) } const fenceCalls: { owner: MarkdownDelegateFenceInfo; entryKey: string | undefined }[] = [] + const asideRenders = { count: 0 } const renderSlot = ( key: string, owner: ChatFlowOwnerProps | MarkdownDelegateFenceInfo, opts: Parameters[2] & { entryKey?: string; children?: React.ReactNode }, ) => { if (key === 'conversation.chat.text-interaction') return null + if (key === 'conversation.chat.aside') { + asideRenders.count += 1 + return + } if (key === 'conversation.chat.markdown.fence' && 'lang' in owner) { fenceCalls.push({ owner, entryKey: opts.entryKey }) return opts.children ?? null @@ -608,7 +613,7 @@ function makeHarness( setConnection: (state: ConnectionState) => { connection.set(state) }, openFile, openUserFile, loadOlder, consumeOlder, prepareOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, - chatScroll, forkAt, toolOwners, fenceCalls, + chatScroll, forkAt, toolOwners, fenceCalls, asideRenders, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, setGrouped: (value: ConversationGroupedView | undefined) => { grouped = value @@ -763,7 +768,7 @@ describe('Chat node rendering', () => { const { getTriggerProps } = useMarkdownDelegate() return <>{targets.map((target, index) => )} } - const view = render( } />) + const view = render( key === 'conversation.chat.aside' ? null : } />) directory = '/workspace/moved' for (const [index, target] of targets.entries()) { const button = view.getByRole('button', { name: String(index) }) @@ -863,6 +868,26 @@ describe('Chat node rendering', () => { }) describe('ChatView', () => { + it('renders the aside once in a layer at the top of the Chat frame, which observes no sizes', () => { + const observed: Element[] = [] + vi.stubGlobal('ResizeObserver', class { + observe(target: Element): void { observed.push(target) } + unobserve(): void {} + disconnect(): void {} + }) + const h = makeHarness({}, {}, chatSnapshotFixture({ nodes: [user(1, 'hello')] })) + const view = render() + const frame = view.container.firstElementChild as HTMLElement + const layer = frame.querySelector('[data-chat-aside]') as HTMLElement + expect(layer.parentElement).toBe(frame) + expect(layer.querySelector('[data-chat-aside-probe]')).not.toBeNull() + // The layer's stylesheet publishes the gutter; the layer itself measures nothing. + expect(observed).not.toContain(layer) + // Transcript updates do not re-render the aside. + act(() => { h.setSession({ running: true }) }) + expect(h.asideRenders.count).toBe(1) + }) + it('renders only referenced Nodes without deleting unreferenced Node data', () => { const snapshot = chatSnapshotFixture({ nodes: [user(1, 'included'), user(2, 'omitted')] }) const h = makeHarness({}, {}, snapshot) @@ -4922,7 +4947,7 @@ it('formats Portuguese elapsed minutes with numeric units', () => { it('does not infer menu targets from links or data attributes inside a plugin flow slot', () => { const h = makeHarness() const custom = vi.fn() - const view = render( <> + const view = render( key === 'conversation.chat.aside' ? null : <> Plugin link + + }> +

{body}

+ + ) +} + +/** + * The `plugins.bundle.config` entry: the account section on its bundle's page. + * @param props - the bundle's face and the translator. + * @returns the title, status line, buttons, detail, notes, failure, hint, and the confirmation a button asked for, or + * null before the Host lists the account. + */ +export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { + const { useConnectorAccounts, account, resolveText, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const { busy, linked, run } = useAccountCommand(props) + const disabled = busy || !linked + const [confirming, setConfirming] = useState() + if (entry === undefined) return null + const { display } = entry + const button = (item: ConnectorAccountButton): ReactNode => { + const label = resolveText(item.label) + const onClick = item.confirm === undefined ? () => { run(entry, item.command) } : () => { setConfirming(item) } + return + } + const details = display.failure?.details ?? [] + const confirm = confirming?.confirm + return ( +
+

{resolveText(entry.copy.title)}

+
+ + {resolveText(display.status)} +
{display.buttons.map(button)}
+
+ {display.detail === undefined ? null :

{resolveText(display.detail)}

} + {display.notes.map((note) => { + const text = resolveText(note.text) + return ( +
+ {text} + {note.button === undefined ? null :
{button(note.button)}
} +
+ ) + })} + {display.failure === undefined ? null : ( +

+ {resolveText(display.failure.text)} + {details.length === 0 ? null : <> {t('failure.details', { details: details.join(' · ') })}} +

+ )} +

{resolveText(entry.copy.hint)}

+ {confirming === undefined || confirm === undefined ? null : ( + { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> + )} +
+ ) +} + +function accountOf(state: ConnectorAccountsState, packageName: string): ConnectorAccountEntry | undefined { + for (const entry of state.accounts.values()) if (entry.packageName === packageName) return entry + return undefined +} + +/** + * The `plugins.detail.badge` entry shared by every bundle that owns an account. + * @param props - the open detail page's subject and the face. + * @returns the display's tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. + */ +export function ConnectorAccountBadgeEntry(props: FaceProps & Pick, 'subject'>): ReactNode { + const { useConnectorAccounts, resolveText, subject } = props + const packageName = subject.kind === 'item' || !subject.pkg.enabled ? undefined : subject.pkg.name + const entry = useConnectorAccounts(state => packageName === undefined ? undefined : accountOf(state, packageName)) + const badge = entry?.display.badge + return entry === undefined || badge === undefined ? null : {resolveText(badge)} +} + +/** + * The `plugins.bundle.activation` entry: guidance after the user switches a bundle on while its account is not + * connected. Connect opens the bundle page and starts the display's `connect` command. + * @param props - activation callbacks, the bundle's face, and the translator. + * @returns a prompt shown while disconnected, or null before the Host lists the account. It waits while the account is + * checking or connecting, which may still end disconnected, and dismisses itself once the account is connected or + * unavailable. + */ +export function ConnectorAccountActivationEntry( + props: BundleFaceProps & Pick, 'onDismiss' | 'onOpenDetails'>, +): ReactNode { + const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const { linked, run } = useAccountCommand(props) + const phase = entry?.display.phase + useEffect(() => { + if (phase === 'connected' || phase === 'unavailable') onDismiss() + }, [phase, onDismiss]) + if (entry === undefined) return null + const { activation } = entry.copy + const { connect } = entry.display + const onConnect = (): void => { + onOpenDetails() + if (connect !== undefined) run(entry, connect) + } + return ( + + + + }> +

{resolveText(activation.body)}

+
+ ) +} + +/** + * The `shell.overlay` entry: account outcomes reported outside the Plugins panel's lifetime. + * @param props - the face and the translator. + * @returns the toast for the latest notice, or null. + */ +export function ConnectorAccountToastEntry({ useConnectorAccounts, resolveText, dismissNotice, t }: FaceProps): ReactNode { + const notice = useConnectorAccounts(state => state.notice) + if (notice === undefined) return null + return notice.kind === 'action-failed' + ? } onDone={dismissNotice} /> + : +} diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts new file mode 100644 index 0000000000..e0e30d6285 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -0,0 +1,91 @@ +/** + * Connector account surfaces, browser half: follows the accounts CLI app plugins and MCP connectors register on the Host, + * and shows each bundle's section, title tag, and activation prompt on its Plugins page, with the notices of the + * operations this browser started. The surfaces read the shared copy from this package's dictionary and each + * registrant's text from the Host. + */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from './components.tsx' +import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' +import { BrowserAccounts } from './state.ts' +import type { ConnectorAccountFace } from './types.ts' + +export type { ConnectorAccountKey } from './locales.ts' +export type { + ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace, +} from './types.ts' + +/** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ +export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] + +function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { + const bundle = { ...face, account } + const dispose = ctx.effect(function* () { + yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountSectionEntry)) + yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountActivationEntry)) + }, `connector-account: ${packageName}`) + return () => void dispose() +} + +/** + * Show the registered connector accounts for one plugin lifetime: one tag and one notice entry for the page, and a + * section and activation prompt for each bundle that owns an account. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') + const remote = ctx.remote.connectorAccounts + const browser = new BrowserAccounts(ctx, remote) + ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') + const face: ConnectorAccountFace = { + hooks: { connectorAccounts: browser.state }, + start: (key, operation) => remote.start(key, operation), + cancel: (key, id) => remote.cancel(key, id), + resolveText: text => ctx.locale.resolveText(text), + follow: (key, id) => { browser.follow(key, id) }, + failed: () => { browser.failed() }, + dismissNotice: () => { browser.dismissNotice() }, + } + ctx.effect(function* () { + yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: 'connector-account.badge', locale: NS, inject: () => face, + }, ConnectorAccountBadgeEntry)) + yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'connector-account.notice', locale: NS, inject: () => face, + }, ConnectorAccountToastEntry)) + }, 'connector-account: page surfaces') + ctx.effect(() => { + const shown = new Map void }>() + const sync = (): void => { + const owned = new Map() + for (const entry of browser.state.getSnapshot().accounts.values()) { + if (entry.packageName !== undefined) owned.set(entry.packageName, entry.key) + } + for (const [packageName, surfaces] of shown) { + if (owned.get(packageName) === surfaces.account) continue + surfaces.withdraw() + shown.delete(packageName) + } + for (const [packageName, account] of owned) { + if (!shown.has(packageName)) shown.set(packageName, { account, withdraw: registerBundle(ctx, face, packageName, account) }) + } + } + sync() + const stop = browser.state.subscribe(sync) + return () => { + stop() + for (const surfaces of shown.values()) surfaces.withdraw() + } + }, 'connector-account: bundle surfaces') +} diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts new file mode 100644 index 0000000000..c0a30b7555 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -0,0 +1,86 @@ +/** Locale-owned copy the connector account surfaces share; each registrant's own text arrives from the Host. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace of the shared account copy. */ +export const NS = 'connectorAccount' + +/** Chinese dictionary and key source. */ +export const zh = { + close: '关闭', + 'action.cancel': '取消', + 'activation.later': '稍后', + 'failure.details': '排障信息:{details}', + 'notice.action-failed': '操作未完成,请重试', +} + +/** Every key the shared account surfaces translate. */ +export type ConnectorAccountKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + close: 'Close', + 'action.cancel': 'Cancel', + 'activation.later': 'Later', + 'failure.details': 'Diagnostic: {details}', + 'notice.action-failed': 'The action did not finish. Try again.', +} + +/** Japanese dictionary. */ +export const ja: Record = { + close: '閉じる', + 'action.cancel': 'キャンセル', + 'activation.later': '後で', + 'failure.details': '診断情報:{details}', + 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', +} + +/** Spanish dictionary. */ +export const es: Record = { + close: 'Cerrar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Más tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', +} + +/** French dictionary. */ +export const fr: Record = { + close: 'Fermer', + 'action.cancel': 'Annuler', + 'activation.later': 'Plus tard', + 'failure.details': 'Diagnostic : {details}', + 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', +} + +/** German dictionary. */ +export const de: Record = { + close: 'Schließen', + 'action.cancel': 'Abbrechen', + 'activation.later': 'Später', + 'failure.details': 'Diagnose: {details}', + 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', +} + +/** Russian dictionary. */ +export const ru: Record = { + close: 'Закрыть', + 'action.cancel': 'Отмена', + 'activation.later': 'Позже', + 'failure.details': 'Диагностика: {details}', + 'notice.action-failed': 'Действие не завершено. Повторите попытку.', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + close: 'Fechar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Mais tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + connectorAccount: ConnectorAccountKey + } +} diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts new file mode 100644 index 0000000000..7a061d98dc --- /dev/null +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -0,0 +1,142 @@ +/** + * The page's one subscription to the registered accounts, and what only this browser knows about them: the operations + * it started, whose authorization pages open here, and the notice to show. + */ +import type { Context } from '@deepseek-ai/cordis' +import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsState } from './types.ts' + +const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) + +/** + * Open an authorization page in a new tab when it is HTTPS, or HTTP on a loopback address such as a local + * authorization server. + * @param url - the page an operation waits on; other values open nothing. + */ +export function openAuthorizationPage(url: string | undefined): void { + if (url === undefined || !URL.canParse(url)) return + const parsed = new URL(url) + if (parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))) { + window.open(url, '_blank', 'noopener,noreferrer') + } +} + +/** One Host subscription per browser, shared by every account surface on the page. */ +export class BrowserAccounts { + /** The accounts, stream state, and notice every surface on the page reads. */ + readonly state: SnapshotStore = createSnapshotStore({ + accounts: new Map(), linked: true, notice: undefined, + }) + + /** + * The operation each account's latest start in this browser returned, with the pages already opened for it. It lasts + * until the stream delivers its result or the account leaves. + */ + private readonly followed = new Map }>() + private seq = 0 + private disposed = false + private readonly stream: RemoteStream + private readonly observing: Promise + + /** + * @param ctx - the browser context carrying the Remote client. + * @param remote - the `connectorAccounts` Remote. + */ + constructor(private readonly ctx: Context, remote: Pick) { + this.stream = ctx.remote.$stream({ + name: 'Connector accounts', open: signal => remote.watch(signal), + ended: () => new Error('Connector accounts stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe() + } + + /** + * Follow an operation this browser started, replacing the account's previous one. + * @param key - the account key. + * @param id - the operation the Host started. + */ + follow(key: string, id: ConnectorOperationId): void { + if (this.disposed) return + this.followed.set(key, { id, opened: new Set() }) + // The stream may have delivered the operation before the start call answered. + const entry = this.state.getSnapshot().accounts.get(key) + if (entry !== undefined) this.track(entry) + } + + /** Report that a Remote call this browser made did not finish; the Host keeps the diagnostic. */ + failed(): void { + this.notify({ kind: 'action-failed' }) + } + + /** Clear the notice once it has been shown. */ + dismissNotice(): void { + this.patch({ notice: undefined }) + } + + /** + * Stop observing the Host; afterwards the page opens no page and reports nothing more. Host-owned operations keep + * running. + * @returns after the stream closes. + */ + async dispose(): Promise { + this.disposed = true + await this.stream.dispose() + await this.observing + } + + private async observe(): Promise { + try { + for await (const item of this.stream) { + // An item the stream yielded just before disposal must not reach the disposed page. + if (this.disposed) return + this.show(item.value.accounts) + item.accept() + } + } catch (error) { + // A terminal failure, such as a Host without the registry, leaves the buttons disabled until the page reloads. + if (this.disposed) return + this.patch({ linked: false }) + this.ctx.logger.warn('connector accounts stream failed; reload the page to reconnect: %s', error) + } + } + + private show(entries: readonly ConnectorAccountEntry[]): void { + const accounts = new Map(entries.map(entry => [entry.key, entry])) + for (const key of [...this.followed.keys()]) if (!accounts.has(key)) this.followed.delete(key) + this.patch({ accounts, linked: true }) + for (const entry of entries) this.track(entry) + } + + /** Open each new page of the account's followed operation once, and report its success once its result arrives. */ + private track(entry: ConnectorAccountEntry): void { + const followed = this.followed.get(entry.key) + if (followed === undefined) return + const url = entry.operation?.id === followed.id ? entry.operation.authorizationUrl : undefined + if (url !== undefined && !followed.opened.has(url)) { + followed.opened.add(url) + openAuthorizationPage(url) + } + const result = entry.result + if (result?.id !== followed.id) return + this.followed.delete(entry.key) + if (result.notice !== undefined) this.notify({ kind: 'succeeded', text: result.notice }) + } + + private notify( + notice: { readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly kind: 'action-failed' }, + ): void { + if (this.disposed) return + this.seq += 1 + const next: ConnectorAccountNotice = { ...notice, seq: this.seq } + this.patch({ notice: next }) + } + + private patch(change: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...change }) + } +} diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts new file mode 100644 index 0000000000..afff7bc9ad --- /dev/null +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -0,0 +1,44 @@ +/** Browser-side state and face of the accounts the Plugins page shows. */ +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorOperationId } from '../types.ts' + +/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ +export type ConnectorAccountNotice = + | { readonly seq: number; readonly kind: 'succeeded'; readonly text: LocalizedText } + | { readonly seq: number; readonly kind: 'action-failed' } + +/** What this browser shows: the Host's accounts, the stream state, and the latest notice. */ +export interface ConnectorAccountsState { + /** Registered accounts by key, as the Host last published them. */ + readonly accounts: ReadonlyMap + /** Whether the Host stream is delivering. */ + readonly linked: boolean + readonly notice: ConnectorAccountNotice | undefined +} + +/** The face every surface entry injects. */ +export interface ConnectorAccountFace { + hooks: { connectorAccounts: HostObservable } + /** + * Start an operation of an account on the Host. The Remote result carries the operation the Host started, or the + * failure when the Host refuses or the call does not answer. + */ + readonly start: ClientRemote['connectorAccounts']['start'] + /** Cancel an account's operation on the Host; the Remote result carries a failure like `start`. */ + readonly cancel: ClientRemote['connectorAccounts']['cancel'] + /** Pick the active language's entry of a registrant's text. */ + readonly resolveText: (text: LocalizedText) => string + /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ + readonly follow: (key: string, id: ConnectorOperationId) => void + /** Report that a Remote call this browser made did not finish. */ + readonly failed: () => void + readonly dismissNotice: () => void +} + +/** The face of a bundle's own surfaces, which show the bundle's account. */ +export interface ConnectorBundleAccountFace extends ConnectorAccountFace { + /** The key of the account the bundle owns. */ + readonly account: string +} diff --git a/packages/client/ui-connector-account/src/css-modules.d.ts b/packages/client/ui-connector-account/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-connector-account/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts new file mode 100644 index 0000000000..aa7ec1d6d4 --- /dev/null +++ b/packages/client/ui-connector-account/src/index.ts @@ -0,0 +1,163 @@ +/** + * Connector account surfaces, Host half. CLI app plugins and MCP connectors register their accounts with + * `ctx.connectorAccounts`; the Plugins page follows every registered account through the `connectorAccounts` Remote and + * starts or cancels operations through it, so the browser never learns how an account connects. + * @module @deepseek-ai/dsh-client-ui-connector-account + */ + +import type { Context } from '@deepseek-ai/cordis' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { + AnyConnectorAccountView, ConnectorAccountEntry, ConnectorAccountRegistration, ConnectorAccountsView, ConnectorOperationId, +} from './types.ts' + +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Connector accounts on the Plugins page. */ + connectorAccounts: ConnectorAccounts + } +} + +interface Registered { + readonly packageName: string | undefined + readonly entry: () => ConnectorAccountEntry + readonly refresh: () => void + readonly start: (operation: string) => ConnectorOperationId | Promise + readonly cancel: (id: ConnectorOperationId) => Promise +} + +function registeredOf(registration: ConnectorAccountRegistration): Registered { + const { key, packageName, source, operations, copy, present } = registration + return { + packageName, + entry: () => { + const view = source.snapshot() + const { operation, result } = view + const notice = result?.outcome === 'succeeded' ? operations.find(candidate => candidate.kind === result.kind)?.notice : undefined + return { + key, ...packageName === undefined ? {} : { packageName }, copy, display: present(view), + ...operation === undefined ? {} : { + operation: { + id: operation.id, ...operation.authorizationUrl === undefined ? {} : { authorizationUrl: operation.authorizationUrl }, + }, + }, + ...result === undefined ? {} : { result: { id: result.id, ...notice === undefined ? {} : { notice } } }, + } + }, + refresh: () => { source.refresh() }, + start: (operation) => { + const kind = operations.find(candidate => candidate.kind === operation)?.kind + if (kind === undefined) throw new Error(`connectorAccounts: ${key} has no page operation ${operation}`) + return source.start(kind) + }, + cancel: id => source.cancel(id), + } +} + +/** Holds the registered accounts and serves them to the Plugins page. */ +export default class ConnectorAccounts extends TypertRemoteService { + private readonly accounts = new Map() + private readonly listeners = new Set<() => void>() + private readonly lifetime = new AbortController() + private subscribers = 0 + + /** @param ctx - the Host context the registry serves the page from. */ + constructor(ctx: Context) { + super(ctx, 'connectorAccounts') + ctx.effect(() => () => { this.lifetime.abort(new Error('connectorAccounts: registry disposed')) }) + } + + /** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ + register(registration: ConnectorAccountRegistration): () => void { + const { key, packageName } = registration + if (this.accounts.has(key)) throw new Error(`connectorAccounts: ${key} is already registered`) + if (packageName !== undefined && [...this.accounts.values()].some(account => account.packageName === packageName)) { + throw new Error(`connectorAccounts: ${packageName} already has an account`) + } + this.accounts.set(key, registeredOf(registration)) + const stop = registration.source.observe(() => { this.changed() }) + // A page that already follows the accounts checks a newly registered one, as it checks each account it subscribes to. + if (this.subscribers > 0) registration.source.refresh() + this.changed() + let active = true + return () => { + if (!active) return + active = false + stop() + this.accounts.delete(key) + this.changed() + } + } + + /** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + const combined = AbortSignal.any([signal, this.lifetime.signal]) + let wake = Promise.withResolvers() + let changed = true + const notify = (): void => { changed = true; wake.resolve() } + this.listeners.add(notify) + combined.addEventListener('abort', notify, { once: true }) + this.subscribers += 1 + try { + for (const account of this.accounts.values()) account.refresh() + for (;;) { + if (!changed) await wake.promise + if (combined.aborted) break + wake = Promise.withResolvers() + changed = false + yield { accounts: [...this.accounts.values()].map(account => account.entry()) } + } + } finally { + this.subscribers -= 1 + this.listeners.delete(notify) + combined.removeEventListener('abort', notify) + } + } + + /** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ + @Remote + async start(key: string, operation: string): Promise { + return await this.account(key).start(operation) + } + + /** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ + @Remote + cancel(key: string, id: ConnectorOperationId): Promise { + return this.account(key).cancel(id) + } + + private account(key: string): Registered { + const account = this.accounts.get(key) + if (account === undefined) throw new Error(`connectorAccounts: ${key} is not registered`) + return account + } + + private changed(): void { + for (const notify of this.listeners) notify() + } +} diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts new file mode 100644 index 0000000000..debd04d302 --- /dev/null +++ b/packages/client/ui-connector-account/src/types.ts @@ -0,0 +1,164 @@ +/** + * Credential-free account views of connector plugins, and what the Plugins page receives about them. Each registrant + * supplies its own account, operation, phase, and failure types and maps its views to the page's display, so CLI app + * plugins and MCP connectors share one registry and one page. + */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' + +/** Identifies one Host-owned account operation across the browsers that show the account. */ +export type ConnectorOperationId = Branded<'ConnectorOperationId'> + +/** The account operation in progress; `Phase` names the registrant's own steps. */ +export interface ConnectorOperation { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly phase: Phase + /** Whether the source cancels the operation in its current phase. */ + readonly cancellable: boolean + /** The page the user authorizes in, while the operation waits for one; only the browser that started it opens it. */ + readonly authorizationUrl?: string +} + +/** The most recent finished operation, kept until another one starts. */ +export interface ConnectorOperationResult { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly outcome: 'succeeded' | 'cancelled' | 'failed' + /** The registrant's classified failure, for its own presentation; does not imply rollback or a safe retry. */ + readonly failure?: Failure +} + +/** The complete account view; observers reread it after each change. */ +export interface ConnectorAccountView { + /** The account as the source last published it. */ + readonly account: Account + readonly operation?: ConnectorOperation + readonly result?: ConnectorOperationResult +} + +/** Any registrant's account view. */ +export type AnyConnectorAccountView = ConnectorAccountView + +/** The operation kinds a view reports. */ +export type ConnectorOperationKindOf = NonNullable['kind'] + +/** What the Plugins page shows about an account; each registrant maps its own account states onto these phases. */ +export type ConnectorAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' + +/** What a section button does. */ +export type ConnectorAccountCommand = + /** Start one of the operations the account registered as page actions. */ + | { readonly kind: 'start'; readonly operation: string } + /** Cancel the operation in progress when it is cancellable. */ + | { readonly kind: 'cancel' } + /** Open the current operation's authorization page again in this browser. */ + | { readonly kind: 'open' } + +/** The question a button asks before it runs. */ +export interface ConnectorAccountConfirmation { + readonly title: LocalizedText + readonly body: LocalizedText + /** The confirm button's label. */ + readonly label: LocalizedText +} + +/** One button in the section. */ +export interface ConnectorAccountButton { + readonly label: LocalizedText + readonly command: ConnectorAccountCommand + /** Defaults to an outline button. */ + readonly variant?: 'primary' | 'ghost' + /** Ask first, for an action that changes the account outside DSH, such as signing out. */ + readonly confirm?: ConnectorAccountConfirmation +} + +/** One extra row under the status line, such as the linked app, with an optional button. */ +export interface ConnectorAccountNote { + readonly text: LocalizedText + readonly button?: ConnectorAccountButton +} + +/** A failed operation as the section reports it. */ +export interface ConnectorAccountFailure { + /** The registrant's recovery guidance. */ + readonly text: LocalizedText + /** Untranslated diagnostic items shown after the guidance in order. */ + readonly details?: readonly string[] +} + +/** What the section shows for the current view; every text carries each shipped language. */ +export interface ConnectorAccountDisplay { + readonly phase: ConnectorAccountPhase + readonly status: LocalizedText + /** The tag beside the bundle title; absent while nothing is settled. */ + readonly badge?: LocalizedText + readonly buttons: readonly ConnectorAccountButton[] + /** What Connect in the activation prompt starts after opening the bundle page; absent, Connect only opens the page. */ + readonly connect?: Extract + readonly detail?: LocalizedText + readonly notes: readonly ConnectorAccountNote[] + readonly failure?: ConnectorAccountFailure +} + +/** The section's fixed text that names the service or uses its wording. */ +export interface ConnectorAccountCopy { + readonly title: LocalizedText + /** The line under the section, such as where the account is shared or authorized. */ + readonly hint: LocalizedText + /** The prompt after the bundle is switched on while the account is disconnected. */ + readonly activation: { readonly title: LocalizedText; readonly body: LocalizedText; readonly connect: LocalizedText } +} + +/** One registered account as the Plugins page receives it. */ +export interface ConnectorAccountEntry { + /** The registrant's stable account key, which the page passes back to start and cancel operations. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; absent for an account no bundle owns. */ + readonly packageName?: string + readonly copy: ConnectorAccountCopy + readonly display: ConnectorAccountDisplay + /** The operation in progress, which a browser follows when it started it. */ + readonly operation?: { readonly id: ConnectorOperationId; readonly authorizationUrl?: string } + /** The most recent finished operation, with the registrant's text when it succeeded. */ + readonly result?: { readonly id: ConnectorOperationId; readonly notice?: LocalizedText } +} + +/** Every registered account, as each change publishes it. */ +export interface ConnectorAccountsView { + readonly accounts: readonly ConnectorAccountEntry[] +} + +/** The account a registration exposes to the page. */ +export interface ConnectorAccountSource { + snapshot(): View + /** @returns a disposer; the listener runs after each change without starting a check. */ + observe(listener: () => void): () => void + /** Start a check unless an operation runs; a source whose view is always current does nothing. */ + refresh(): void + /** @returns the started operation's identity, at once or after the source has started the operation. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise + /** @returns after the named operation settles, or at once when it is not cancellable. */ + cancel(id: ConnectorOperationId): Promise +} + +/** One operation a page button may start, with the text its success reports in the browser that started it. */ +export interface ConnectorAccountOperation { + readonly kind: Kind + readonly notice?: LocalizedText +} + +/** One connector account, registered with the Host's `ctx.connectorAccounts`. */ +export interface ConnectorAccountRegistration { + /** Stable key, unique among registered accounts, such as the bundle's package name. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; at most one account per package. */ + readonly packageName?: string + readonly source: ConnectorAccountSource + /** The operations a page button may start; the registry rejects any other. */ + readonly operations: readonly ConnectorAccountOperation>[] + readonly copy: ConnectorAccountCopy + /** Map the current view to what the section shows; called on each change for each subscriber. */ + readonly present: (view: View) => ConnectorAccountDisplay +} diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts new file mode 100644 index 0000000000..4dda30bb1c --- /dev/null +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -0,0 +1,163 @@ +/** + * The browser plugin shows one tag and one notice entry for the page, and a section and activation prompt for each bundle + * that owns an account, withdrawing them with the account or the plugin. + */ +import assert from 'node:assert/strict' +import { Context, Service } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { NS } from '../src/client/locales.ts' +import { apply, inject } from '../src/client/index.ts' +import type { ConnectorAccountFace, ConnectorBundleAccountFace } from '../src/client/types.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' +const OP = 'op-1' as ConnectorOperationId + +function isFace(value: Record): asserts value is Record & ConnectorAccountFace { + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function') + assert(typeof value.start === 'function' && typeof value.cancel === 'function') + assert(typeof value.hooks === 'object' && value.hooks !== null) +} + +/** Read the face a slot entry injects. */ +function faceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorAccountFace { + assert(item.inject !== undefined) + const face = item.inject() + isFace(face) + return face +} + +function bundleFaceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorBundleAccountFace { + const face = faceOf(item) + assert('account' in face && typeof face.account === 'string') + return face as ConnectorBundleAccountFace +} + +function entry(key: string, packageName: string | null = key): ConnectorAccountEntry { + return { + key, ...packageName === null ? {} : { packageName }, + copy: { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } }, + display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, + } +} + +async function bench() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, accepted = 0 + const closeStream = vi.fn(async () => { closed = true; wake?.() }) + const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + const cancel = vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ({ ok: true, value: undefined })) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + $stream() { + return { + async *[Symbol.asyncIterator]() { + for (;;) { + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: closeStream, + } + } + } + new Remote() + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel }) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => + ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) + return { + ctx, locale, start, cancel, closeStream, bundles, + mount: () => ctx.plugin({ inject: [...inject], apply }), + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + queue.push({ accounts: entries }) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + } +} + +it('shows one tag and one notice entry for the page and each bundle\'s section and prompt under the shared dictionary', async () => { + const b = await bench() + await b.mount() + expect(b.locale.bind(NS)('action.cancel')).toBe('Cancel') + expect(b.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.badge', ConnectorAccountBadgeEntry], + ]) + expect(b.ctx.slots.entries('shell.overlay').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.notice', ConnectorAccountToastEntry], + ]) + expect(b.bundles('plugins.bundle.config')).toEqual([]) + + // An account no bundle owns gets no bundle surfaces. + await b.publish(entry(FIXTURE), entry(OTHER), entry('mcp:custom', null)) + expect(b.bundles('plugins.bundle.config')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + const [section] = b.ctx.slots.entries('plugins.bundle.config') + assert(section !== undefined) + expect(section).toMatchObject({ locale: NS, component: ConnectorAccountSectionEntry }) + expect(b.ctx.slots.entries('plugins.bundle.activation')[0]).toMatchObject({ locale: NS, component: ConnectorAccountActivationEntry }) + const face = bundleFaceOf(section) + const [badge] = b.ctx.slots.entries('plugins.detail.badge') + assert(badge !== undefined) + const [toast] = b.ctx.slots.entries('shell.overlay') + assert(toast !== undefined) + expect(faceOf(badge).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) + expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') + expect(await face.start(FIXTURE, 'connect')).toEqual({ ok: true, value: OP }) + expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + expect(await face.cancel(FIXTURE, OP)).toEqual({ ok: true, value: undefined }) + expect(b.cancel).toHaveBeenCalledWith(FIXTURE, OP) + // A refusal reaches the buttons as the Remote's result. + const refused: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } + b.start.mockResolvedValueOnce(refused) + expect(await face.start(FIXTURE, 'connect')).toBe(refused) + face.follow(FIXTURE, OP) + face.failed() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) + face.dismissNotice() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toBeUndefined() + + // A dropped account withdraws its bundle's surfaces, and a bundle whose account changed key shows the new one. + await b.publish(entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, OTHER]]) + await b.publish(entry('mcp:other', OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, 'mcp:other']]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[OTHER, 'mcp:other']]) +}) + +it('withdraws every surface, the dictionaries, and the stream when the plugin unloads', async () => { + const b = await bench() + const fiber = b.mount() + await fiber + await b.publish(entry(FIXTURE), entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toHaveLength(2) + await fiber.dispose() + for (const slot of ['plugins.bundle.config', 'plugins.bundle.activation', 'plugins.detail.badge', 'shell.overlay'] as const) { + expect(b.ctx.slots.entries(slot)).toEqual([]) + } + expect(b.locale.bind(NS)('action.cancel')).toBe('action.cancel') + expect(b.closeStream).toHaveBeenCalledOnce() +}) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx new file mode 100644 index 0000000000..8e645a7bc4 --- /dev/null +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -0,0 +1,246 @@ +// @vitest-environment jsdom +/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Host callbacks. */ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { zh } from '../src/client/locales.ts' +import type { ConnectorAccountFace, ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' + +afterEach(cleanup) + +const KEY = '@acme/fixture' +const OP = 'op-1' as ConnectorOperationId +const STARTED: RemoteResult = { ok: true, value: OP } +const REFUSED: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } +const t = makeTranslate(zh) +const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en +const button = (name: string) => screen.getByRole('button', { name }) +const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) +const click = async (name: string) => { await act(async () => { fireEvent.click(button(name)) }) } + +const DISCONNECTED: ConnectorAccountDisplay = { + phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', + buttons: [{ label: '连接演示', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [], +} + +function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}): ConnectorAccountEntry { + return { + key: KEY, packageName: KEY, display, + copy: { title: { en: 'Fixture account', zh: '演示账号' }, hint: '与终端共用。', activation: { title: '连接演示', body: '插件已开启。', connect: '连接演示' } }, + ...extra, + } +} + +function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { + const current: ConnectorAccountsState = { + accounts: new Map(accounts.map(item => [item.key, item])), linked: true, notice: undefined, ...change, + } + return { + useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), + start: vi.fn(async () => STARTED), + cancel: vi.fn(async () => ({ ok: true, value: undefined })), + account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, + } +} + +const sectionOf = (display: ConnectorAccountDisplay, change: Partial = {}) => face(change, [entry(display)]) +const prompt = (props: ReturnType, onDismiss = vi.fn(), onOpenDetails = vi.fn()) => + + +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation on the Host', async () => { + const props = sectionOf({ + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + }) + const { container } = render() + for (const text of ['演示账号', '未连接', '先关联一个应用。', '普通说明', '与终端共用。']) expect(screen.getByText(text)).toBeTruthy() + expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() + await click('连接演示') + await click('更换') + expect(props.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) + expect(props.follow.mock.calls).toEqual([[KEY, OP], [KEY, OP]]) +}) + +it('disables the buttons while a call is pending or the Host stream is down', async () => { + const props = face() + const answer = Promise.withResolvers>() + props.start.mockReturnValueOnce(answer.promise) + render() + fireEvent.click(button('连接演示')) + expect(disabled()).toEqual([true]) + await act(async () => { answer.resolve(STARTED) }) + expect(disabled()).toEqual([false]) + expect(props.failed).not.toHaveBeenCalled() + cleanup() + render() + expect(disabled()).toEqual([true]) +}) + +it('asks before a button that changes the account outside DSH and starts it only after the user accepts', async () => { + const props = sectionOf({ + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + }) + render() + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.click(button('退出登录')) + await click('确认退出') + expect(screen.queryByRole('dialog')).toBeNull() + expect(props.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it('disables an open confirmation and the activation prompt\'s Connect while the Host stream is down', () => { + const display: ConnectorAccountDisplay = { + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + } + const { rerender } = render() + fireEvent.click(button('退出登录')) + // The stream drops while the confirmation is open. + const down = sectionOf(display, { linked: false }) + rerender() + fireEvent.click(button('确认退出')) + expect((button('确认退出') as HTMLButtonElement).disabled).toBe(true) + expect(down.start).not.toHaveBeenCalled() + cleanup() + const offline = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }, { linked: false }) + render(prompt(offline)) + fireEvent.click(button('连接演示')) + expect((button('连接演示') as HTMLButtonElement).disabled).toBe(true) + expect(offline.start).not.toHaveBeenCalled() +}) + +it.each<[string, ConnectorAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], +])('reports %s', (_name, failure, expected) => { + render() + expect(screen.getByRole('alert').textContent).toBe(expected) +}) + +it('reports a start whose result is a failure or whose call rejected, without following it', async () => { + const props = face() + props.start.mockResolvedValueOnce(REFUSED).mockRejectedValueOnce(new Error('Remote method is no longer mounted')) + render() + await click('连接演示') + expect(props.failed).toHaveBeenCalledOnce() + expect(disabled()).toEqual([false]) + await click('连接演示') + expect(props.failed).toHaveBeenCalledTimes(2) + expect(props.follow).not.toHaveBeenCalled() +}) + +it('cancels the operation in progress and opens its authorization page again on request', async () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + const display: ConnectorAccountDisplay = { + phase: 'connecting', status: '等待浏览器', notes: [], + buttons: [{ label: '打开授权页', command: { kind: 'open' } }, { label: '取消', command: { kind: 'cancel' }, variant: 'ghost' }], + } + const props = face({}, [entry(display, { operation: { id: OP, authorizationUrl: 'https://example.com/a' } })]) + render() + fireEvent.click(button('打开授权页')) + expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') + await click('取消') + expect(props.cancel).toHaveBeenCalledWith(KEY, OP) + expect(props.failed).not.toHaveBeenCalled() + props.cancel.mockResolvedValueOnce(REFUSED) + await click('取消') + expect(props.failed).toHaveBeenCalledOnce() + // A cancel button with no operation in progress calls nothing. + cleanup() + const idle = sectionOf(display) + render() + await click('取消') + expect(idle.cancel).not.toHaveBeenCalled() +}) + +it('renders nothing for a bundle whose account the Host has not listed', () => { + render() + render(prompt(face({}, []))) + expect(document.body.textContent).toBe('') +}) + +it('tags only the enabled bundle that owns an account, with the display\'s tag', () => { + const pkg = (name: string, enabled = true) => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] } as const) + const page = (name: string, enabled = true): PluginsSubject => ({ kind: 'bundle', pkg: pkg(name, enabled) }) + const row: PluginsSubject = { kind: 'row', pkg: pkg(KEY), row: { rowId: 'fixture', moduleName: '@acme/fixture-row', enabled: true } } + const tag = (props: ReturnType, subject: PluginsSubject) => + const { rerender } = render(tag(face(), page(KEY))) + expect(screen.getByText('未连接')).toBeTruthy() + rerender(tag(face(), row)) + expect(screen.getByText('未连接')).toBeTruthy() + for (const [props, subject] of [ + [face(), page(KEY, false)], [face(), page('@acme/other')], [face(), { kind: 'item', id: 'fixture-item' }], + [sectionOf({ phase: 'checking', status: '检查中', buttons: [], notes: [] }), page(KEY)], + ] as const) { + rerender(tag(props, subject)) + expect(document.body.textContent).toBe('') + } +}) + +it('prompts to connect only while disconnected, waits while checking or connecting, and dismisses itself once settled', () => { + const onDismiss = vi.fn() + const at = (phase: ConnectorAccountDisplay['phase']) => prompt(sectionOf({ phase, status: phase, buttons: [], notes: [] }), onDismiss) + const { rerender } = render(at('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(at('connecting')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(at('disconnected')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button(zh['activation.later'])) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(at('connected')) + rerender(at('unavailable')) + expect(onDismiss).toHaveBeenCalledTimes(3) +}) + +it('connects from the prompt through the operation the display names, or only opens the page', async () => { + const onOpenDetails = vi.fn() + const named = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } }) + const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) + await click('连接演示') + expect(onOpenDetails).toHaveBeenCalledOnce() + expect(named.start).toHaveBeenCalledWith(KEY, 'link-app') + const bare = face() + rerender(prompt(bare, vi.fn(), onOpenDetails)) + fireEvent.click(button('连接演示')) + expect(onOpenDetails).toHaveBeenCalledTimes(2) + expect(bare.start).not.toHaveBeenCalled() +}) + +it('starts once for a second click before the first call answers', async () => { + const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) + const answer = Promise.withResolvers>() + props.start.mockReturnValueOnce(answer.promise) + render(prompt(props)) + fireEvent.click(button('连接演示')) + fireEvent.click(button('连接演示')) + await act(async () => { answer.resolve(STARTED) }) + expect(props.start).toHaveBeenCalledOnce() + expect(props.follow).toHaveBeenCalledOnce() +}) + +it('shows the latest notice with the registrant text or the shared failure copy', () => { + const toast = (notice: ConnectorAccountsState['notice']) => + const { rerender } = render(toast(undefined)) + expect(document.body.textContent).toBe('') + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) + expect(screen.getByText('演示已连接')).toBeTruthy() + rerender(toast({ seq: 2, kind: 'action-failed' })) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() +}) diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts new file mode 100644 index 0000000000..ee8e24276f --- /dev/null +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -0,0 +1,170 @@ +/** The registry serves every registered account to the Plugins page and routes page operations to the account that owns them. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished, vi } from 'vitest' +import ConnectorAccounts from '../src/index.ts' +import type { + ConnectorAccountDisplay, ConnectorAccountRegistration, ConnectorAccountSource, ConnectorAccountsView, ConnectorAccountView, + ConnectorOperationId, +} from '../src/types.ts' + +type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const COPY = { + title: { en: 'Fixture account', zh: '演示账号' }, + hint: 'Shared with the terminal.', + activation: { title: 'Connect Fixture', body: 'The plugin is on.', connect: 'Connect' }, +} + +function source(initial: View = { account: { state: 'out' } }) { + let view = initial + const listeners = new Set<() => void>() + const fake = { + snapshot: () => view, + observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), + refresh: vi.fn(), + start: vi.fn((_kind: 'check' | 'connect'): ConnectorOperationId | Promise => OP), + cancel: vi.fn(async (_id: ConnectorOperationId) => {}), + } satisfies ConnectorAccountSource + return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } +} + +function display(view: View): ConnectorAccountDisplay { + return view.account.state === 'in' + ? { phase: 'connected', status: 'Connected', badge: 'Connected', buttons: [], notes: [] } + : { phase: 'disconnected', status: 'Not connected', buttons: [{ label: 'Connect', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [] } +} + +/** A registration whose bundle package defaults to its key; `null` registers an account no bundle owns. */ +function registration(key: string, account = source(), packageName: string | null = key): ConnectorAccountRegistration { + return { + key, ...packageName === null ? {} : { packageName }, source: account.fake, copy: COPY, present: display, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Fixture connected', zh: '演示已连接' } }], + } +} + +async function registry() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(ConnectorAccounts) + return ctx +} + +/** Read the stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('stream ended') + if (predicate(next.value)) return next.value + } +} + +it('publishes each account with its key, package, copy, display, operation, and result, and checks it for each new subscriber', async () => { + const ctx = await registry() + const account = source() + const withdraw = ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(account.fake.refresh).not.toHaveBeenCalled() + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + const first = await until(stream, () => true) + expect(account.fake.refresh).toHaveBeenCalledOnce() + expect(first.accounts).toEqual([ + { key: '@acme/fixture', packageName: '@acme/fixture', copy: COPY, display: display({ account: { state: 'out' } }) }, + ]) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://example.com/a' } }) + const waiting = await until(stream, view => view.accounts[0]?.operation !== undefined) + expect(waiting.accounts[0]?.operation).toEqual({ id: OP, authorizationUrl: 'https://example.com/a' }) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: false } }) + const checking = await until(stream, (view) => { + const operation = view.accounts[0]?.operation + return operation !== undefined && operation.authorizationUrl === undefined + }) + expect(checking.accounts[0]?.operation).toEqual({ id: OP }) + + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + const connected = await until(stream, view => view.accounts[0]?.result !== undefined) + expect(connected.accounts[0]).toMatchObject({ + display: { phase: 'connected' }, result: { id: OP, notice: { en: 'Fixture connected', zh: '演示已连接' } }, + }) + + // Only a success reports a notice, and only for an operation that registered one. + account.publish({ account: { state: 'out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'disconnected')).accounts[0]?.result).toEqual({ id: OP }) + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'connected')).accounts[0]?.result).toEqual({ id: OP }) + + withdraw() + expect((await until(stream, view => view.accounts.length === 0)).accounts).toEqual([]) + withdraw() + expect(account.listeners.size).toBe(0) + controller.abort() + expect((await stream.next()).done).toBe(true) +}) + +it('publishes an account that no bundle owns without a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('mcp:custom', source(), null)) + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const [entry] = (await until(stream, () => true)).accounts + expect(entry).toEqual({ key: 'mcp:custom', copy: COPY, display: display({ account: { state: 'out' } }) }) +}) + +it('checks an account registered while the page follows, and none registered while nobody follows', async () => { + const ctx = await registry() + const idle = source() + ctx.connectorAccounts.register(registration('@acme/idle', idle)) + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + await until(stream, view => view.accounts.length === 1) + const late = source() + ctx.connectorAccounts.register(registration('@acme/late', late)) + expect(late.fake.refresh).toHaveBeenCalledOnce() + expect((await until(stream, view => view.accounts.length === 2)).accounts.map(entry => entry.key)).toEqual(['@acme/idle', '@acme/late']) + controller.abort() + await stream.next() + const after = source() + ctx.connectorAccounts.register(registration('@acme/after', after)) + expect(after.fake.refresh).not.toHaveBeenCalled() +}) + +it('starts only the operations an account registered and cancels through its source', async () => { + const ctx = await registry() + const account = source() + ctx.connectorAccounts.register(registration('@acme/fixture', account)) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(OP) + expect(account.fake.start).toHaveBeenCalledWith('connect') + // A source that starts its operation asynchronously answers once it has the identity. + account.fake.start.mockImplementationOnce(async () => NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).rejects.toThrow('@acme/fixture has no page operation sign-out') + await expect(ctx.connectorAccounts.start('@acme/other', 'connect')).rejects.toThrow('@acme/other is not registered') + await ctx.connectorAccounts.cancel('@acme/fixture', OP) + expect(account.fake.cancel).toHaveBeenCalledWith(OP) + expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') +}) + +it('refuses a second account for a key or for a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('@acme/fixture')) + expect(() => ctx.connectorAccounts.register(registration('@acme/fixture'))).toThrow('@acme/fixture is already registered') + expect(() => ctx.connectorAccounts.register(registration('mcp:fixture', source(), '@acme/fixture'))) + .toThrow('@acme/fixture already has an account') + expect(() => ctx.connectorAccounts.register(registration('mcp:custom', source(), null))).not.toThrow() +}) + +it('ends every stream when the registry unloads', async () => { + const ctx = new Context() + const fiber = ctx.plugin(ConnectorAccounts) + await fiber + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + await until(stream, () => true) + const pending = stream.next() + await fiber.dispose() + expect((await pending).done).toBe(true) + await ctx.fiber.dispose() +}) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts new file mode 100644 index 0000000000..4c11668ac2 --- /dev/null +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -0,0 +1,179 @@ +// @vitest-environment jsdom +/** The browser follows every registered account through one Host stream and keeps only what this browser started. */ +import { Context } from '@deepseek-ai/cordis' +import { RemoteStreamCarrierError, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import { expect, it, onTestFinished, vi } from 'vitest' +import { BrowserAccounts, openAuthorizationPage } from '../src/client/state.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const FIXTURE = '@acme/fixture' +const OTHER = 'mcp:other' +const COPY = { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } } + +function entry(key: string, extra: Partial = {}): ConnectorAccountEntry { + return { key, copy: COPY, display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, ...extra } +} + +const waiting = (url?: string, id = OP): Partial => + ({ operation: { id, ...url === undefined ? {} : { authorizationUrl: url } } }) + +function fixture() { + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const open = () => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + // A queued item still arrives after close, as an item the stream yielded just before disposal does. + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + }) + const streams: Array> = [] + const remote = { watch: vi.fn() } + const ctx = new Context() + ctx.provide('remote', { + $stream: (value: typeof options) => { + options = value + closed = false + failure = undefined + streams.push(open()) + return streams.at(-1) + }, + }) + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + const browser = new BrowserAccounts(ctx, remote) + onTestFinished(async () => { await browser.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) + return { + ctx, browser, remote, open: windowOpen, streams, options: () => options, + state: () => browser.state.getSnapshot(), + deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + this.deliver({ accounts: entries }) + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + fail(error: Error) { failure = error; wake?.() }, + } +} + +it('mirrors the Host accounts by key and reports carrier loss until the next item', async () => { + const b = fixture() + expect(b.state()).toEqual({ accounts: new Map(), linked: true, notice: undefined }) + const open = b.options().open(new AbortController().signal) + expect(b.remote.watch).toHaveBeenCalledOnce() + expect(open).toBe(b.remote.watch.mock.results[0]?.value) + await b.publish(entry(FIXTURE), entry(OTHER)) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE, OTHER]) + b.options().carrierFailed?.(new RemoteStreamCarrierError('offline')) + expect(b.state().linked).toBe(false) + await b.publish(entry(FIXTURE)) + expect(b.state().linked).toBe(true) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) + expect(b.options().ended(true).message).toBe('Connector accounts stream ended') +}) + +it('opens each new authorization page of an operation this browser started once, and no other account\'s', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER, waiting('https://example.com/other'))) + expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + await b.publish(entry(FIXTURE, waiting('http://127.0.0.1:8123/authorize'))) + // Another browser's operation on the same account opens nothing here. + await b.publish(entry(FIXTURE, waiting('https://example.com/b', NEXT))) + expect(b.open.mock.calls.map(([url]) => url)).toEqual(['https://example.com/a', 'http://127.0.0.1:8123/authorize']) +}) + +it('opens the page at once when the stream delivered the operation before the start call answered', async () => { + const b = fixture() + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() + b.browser.follow(FIXTURE, OP) + expect(b.open).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') +}) + +it('reports the success of an operation this browser started once, and stops following it', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, { result: { id: NEXT, notice: 'Other browser connected' } })) + expect(b.state().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toEqual({ seq: 1, kind: 'succeeded', text: 'Fixture connected' }) + b.browser.dismissNotice() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toBeUndefined() + + // A result without the registrant's text, or a cancelled or failed one, reports nothing. + b.browser.follow(FIXTURE, NEXT) + await b.publish(entry(FIXTURE, { result: { id: NEXT } })) + expect(b.state().notice).toBeUndefined() +}) + +it('forgets the operation of an account the Host withdrew', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(OTHER)) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() +}) + +it('reports a call that did not finish with a fresh notice each time', () => { + const b = fixture() + b.browser.failed() + b.browser.failed() + expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) +}) + +it('keeps the buttons disabled and logs a terminal stream failure, opening no second stream', async () => { + const b = fixture() + const warn = vi.spyOn(b.ctx.logger, 'warn').mockImplementation(() => {}) + await b.publish(entry(FIXTURE)) + b.fail(new Error('Host without the registry')) + await vi.waitFor(() => { expect(b.state().linked).toBe(false) }) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('connector accounts stream failed'), expect.any(Error)) + expect(b.streams).toHaveLength(1) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) +}) + +it('opens nothing and reports nothing after disposal', async () => { + const b = fixture() + await b.browser.dispose() + b.browser.follow(FIXTURE, OP) + b.browser.failed() + expect(b.state().notice).toBeUndefined() +}) + +it('shows nothing for a stream that fails while the page disposes it', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.fail(new Error('carrier lost')) + await disposing + expect(b.state().linked).toBe(true) +}) + +it('ignores an item the stream yielded just before disposal', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.deliver({ accounts: [entry(FIXTURE)] }) + await disposing + expect(b.state().accounts.size).toBe(0) +}) + +it('opens only HTTPS pages and HTTP pages on loopback addresses', () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + for (const url of [undefined, 'not a url', 'http://example.com/a', 'javascript:alert(1)']) openAuthorizationPage(url) + expect(windowOpen).not.toHaveBeenCalled() + for (const url of ['https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a']) openAuthorizationPage(url) + expect(windowOpen.mock.calls.map(([url]) => url)).toEqual([ + 'https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a', + ]) +}) diff --git a/packages/client/ui-connector-account/tsconfig.client.json b/packages/client/ui-connector-account/tsconfig.client.json new file mode 100644 index 0000000000..115af386fd --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.client.json @@ -0,0 +1,57 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/css-modules.d.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.host.json b/packages/client/ui-connector-account/tsconfig.host.json new file mode 100644 index 0000000000..564ba19f3b --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.host.json @@ -0,0 +1,26 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.json b/packages/client/ui-connector-account/tsconfig.json new file mode 100644 index 0000000000..2eca820546 --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.host.json" + }, + { + "path": "./tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-connector-account/tsdown.config.ts b/packages/client/ui-connector-account/tsdown.config.ts new file mode 100644 index 0000000000..620261533c --- /dev/null +++ b/packages/client/ui-connector-account/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-context-menu/README.i18n.yaml b/packages/client/ui-context-menu/README.i18n.yaml index da161da095..33fc925b51 100644 --- a/packages/client/ui-context-menu/README.i18n.yaml +++ b/packages/client/ui-context-menu/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 725b47765ee8f30b /deepseek-ai-dsh-client-ui-context-menu/use-this-package: - en: 892cfb46cfcddcc0 - zh: c534b44e7ef53522 + en: e07cd4cb97b6c77e + zh: 97bba9f554dce3c7 /deepseek-ai-dsh-client-ui-context-menu/use-this-package/register-actions: en: 11bea09005de2678 zh: d56e25d2d93022aa diff --git a/packages/client/ui-context-menu/README.md b/packages/client/ui-context-menu/README.md index 704d8f5043..40137c1d10 100644 --- a/packages/client/ui-context-menu/README.md +++ b/packages/client/ui-context-menu/README.md @@ -25,7 +25,7 @@ Add actions to right-click menus without importing a React component. Targets re ## Use this package -The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `contextMenus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback. +The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `contextMenus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback. It is a volatile field of the Host entry's Config, so a change in `cordis.yml` reaches open pages without remounting the plugin and applies from the next menu preparation. The plugin injects `useContextMenu` into every Slot scope through `ctx.slots.provideRoot`. Call `const { getTriggerProps } = useContextMenu()` once in the component and spread `getTriggerProps(target, handlers?)` onto each trigger. The factory is an ordinary function and can run in loops. It handles right-click, Shift+F10, the ContextMenu key, viewport coordinates, and focus without scrolling. Existing handlers run first; `preventDefault()` keeps their ownership and prevents duplicate handling by composed or nested bindings. Repeated, composing, and unrelated key events remain untouched. Pass `undefined` to retain native behavior, or a target resolver to read business state when the gesture begins. The resolved object is captured before focus changes. Plain children receive event props or a factory through props or an existing delegate; no additional React Context is needed. Special editors and canvases can call `ctx.contextMenus.open()` directly. diff --git a/packages/client/ui-context-menu/README.zh.md b/packages/client/ui-context-menu/README.zh.md index 1fc68c3a1e..952d5896d2 100644 --- a/packages/client/ui-context-menu/README.zh.md +++ b/packages/client/ui-context-menu/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `contextMenus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。 +Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `contextMenus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。它是 Host 条目 Config 中的 volatile 字段,因此在 `cordis.yml` 中修改后,已打开的页面无需重新挂载插件,从下一次准备菜单起生效。 插件通过 `ctx.slots.provideRoot` 向每个 Slot 作用域注入 `useContextMenu`。组件调用一次 `const { getTriggerProps } = useContextMenu()`,再将 `getTriggerProps(target, handlers?)` 展开到各个触发元素上。该工厂是普通函数,可以在循环中调用;它统一处理右键、Shift+F10、ContextMenu 键、视口坐标及无滚动聚焦。已有处理器先运行,`preventDefault()` 保留其处理权,并防止组合或嵌套绑定重复处理。重复、输入法组合及无关按键保持原状。传入 `undefined` 保留原生行为,也可传入目标解析函数,在手势开始时读取业务状态。解析后的对象会在焦点变化前捕获。普通子组件通过 props 或现有 delegate 接收事件 props 或工厂,无需额外 React Context。特殊编辑器和 Canvas 可直接调用 `ctx.contextMenus.open()`。 diff --git a/packages/client/ui-context-menu/package.json b/packages/client/ui-context-menu/package.json index e9c383ed59..9f56f52474 100644 --- a/packages/client/ui-context-menu/package.json +++ b/packages/client/ui-context-menu/package.json @@ -44,8 +44,10 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + }, "devDependencies": { - "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", @@ -59,7 +61,8 @@ "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-client-ui-dockkit": "workspace:*", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*" + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-context-menu/src/client/index.ts b/packages/client/ui-context-menu/src/client/index.ts index b4244c4153..8d5f16a5f3 100644 --- a/packages/client/ui-context-menu/src/client/index.ts +++ b/packages/client/ui-context-menu/src/client/index.ts @@ -4,7 +4,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-locale/client' -import z from '@deepseek-ai/schemastery' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { ContextMenuConfig } from '../types.ts' import { MENU_TRANSITION_MS } from '@deepseek-ai/dsh-client-ui-primitives' import { menuTargetKey } from './target-key.ts' import { MenuRegistry } from './registry.ts' @@ -44,15 +45,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { /** Menu operation feedback. */ contextMenu: 'failed' | 'back' } } -/** Maximum time to prepare each contribution before omitting its pending actions. */ -export interface Config { resolutionTimeoutMs?: number } -/** Validated Client menu preparation budget. */ -export const Config: z = z.object({ resolutionTimeoutMs: z.natural().min(1).default(1000) }) +/** Preparation budget while the Host sends none; the value the Client used before the field moved to the Host. */ +const ABSENT_RESOLUTION_TIMEOUT_MS = 1000 /** Required overlay and localization services. */ export const inject = ['slots', 'locale', 'shortcuts'] -/** @param ctx - plugin-owned Client context. @param config - validated preparation budget. */ -export function apply(ctx: Context, config: Config = Config({})): void { +/** @param ctx - plugin-owned Client context. @param config - Host-synced preparation budget, read when each menu prepares. */ +export function apply(ctx: Context, config: SyncedConfig): void { ctx.effect(() => ctx.locale.register('contextMenu', dictionaries), 'context menu: locale') const t = ctx.locale.bind('contextMenu') const handle = createMenuStore() @@ -81,7 +80,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, } } }) } - const registry = new MenuRegistry((message) => { notify(message ?? t('failed')) }, config.resolutionTimeoutMs) + const registry = new MenuRegistry((message) => { notify(message ?? t('failed')) }, () => config.resolutionTimeoutMs.get() ?? ABSENT_RESOLUTION_TIMEOUT_MS) const cancelOpening = (): void => { clearTimeout(openingTimer); finishOpening?.(); finishOpening = undefined active?.unsubscribe(); active?.resolution.dispose(); active = undefined diff --git a/packages/client/ui-context-menu/src/client/registry.ts b/packages/client/ui-context-menu/src/client/registry.ts index af89692538..b4d580dd3a 100644 --- a/packages/client/ui-context-menu/src/client/registry.ts +++ b/packages/client/ui-context-menu/src/client/registry.ts @@ -20,7 +20,10 @@ export class MenuRegistry { private readonly providers = new Map() private readonly occurrences = new Set<() => void>() private disposed = false - constructor(private readonly failed: (message?: string) => void, private readonly timeoutMs?: number) {} + constructor( + private readonly failed: (message?: string) => void, + private readonly timeoutMs: () => number | undefined = () => undefined, + ) {} /** * Register actions for subsequent openings. @@ -110,9 +113,10 @@ export class MenuRegistry { const result = provider.resolve(target, signal) if (result instanceof Promise) clear() preparing = result instanceof Promise ? new Promise((settle) => { - const timer = this.timeoutMs === undefined ? undefined : setTimeout(() => { + const timeoutMs = this.timeoutMs() + const timer = timeoutMs === undefined ? undefined : setTimeout(() => { deadline.abort(); this.failed() - }, this.timeoutMs) + }, timeoutMs) const finish = (): void => { clearTimeout(timer); signal.removeEventListener('abort', finish); settle() } signal.addEventListener('abort', finish, { once: true }) void result.then(accept).catch(() => { if (!signal.aborted) this.failed() }).finally(finish) diff --git a/packages/client/ui-context-menu/src/index.ts b/packages/client/ui-context-menu/src/index.ts index 77258040c7..c639cbcea8 100644 --- a/packages/client/ui-context-menu/src/index.ts +++ b/packages/client/ui-context-menu/src/index.ts @@ -1,4 +1,14 @@ -/** Host Loader entry; menus belong to the Client. */ +/** Host Loader entry declaring the browser menu preparation budget; menus belong to the Client. */ +import z from '@deepseek-ai/schemastery' +import type { ContextMenuConfig } from './types.ts' + +/** Live preparation budget; the browser receives it through its synced Config. */ +export type Config = ContextMenuConfig + +/** Live preparation budget synced to the browser. */ +export const Config = z.object({ + resolutionTimeoutMs: z.natural().min(1).default(1000).volatile(), +}) /** Register the browser plugin without Host behavior. */ export function apply(): void {} diff --git a/packages/client/ui-context-menu/src/types.ts b/packages/client/ui-context-menu/src/types.ts new file mode 100644 index 0000000000..20e045cfeb --- /dev/null +++ b/packages/client/ui-context-menu/src/types.ts @@ -0,0 +1,8 @@ +/** Context-menu plugin configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' + +/** Live preparation budget; the browser receives it through its synced Config. */ +export interface ContextMenuConfig { + /** Maximum time in milliseconds to prepare each contribution before omitting its pending actions. */ + resolutionTimeoutMs: Volatile +} diff --git a/packages/client/ui-context-menu/tests/button.client.spec.tsx b/packages/client/ui-context-menu/tests/button.client.spec.tsx index 9b381ff29b..7c4c46d9c5 100644 --- a/packages/client/ui-context-menu/tests/button.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/button.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, fireEvent } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' @@ -35,7 +36,7 @@ it('shows late registered kinds without preparing actions and withdraws them wit ) const view = runtime.renderRoot() expect(view.queryByRole('button')).toBeNull() - const plugin = await runtime.mount({ inject, apply }) + const plugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) expect(view.queryByRole('button')).toBeNull() const resolve = vi.fn(() => new Promise(() => {})) const row = await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ @@ -67,7 +68,7 @@ it('shows the label tooltip on the compact toolbar button but not on row buttons {renderFactorySlot('contextMenu.button', { target: target('header'), label: 'Header menu', size: 'sm' })} {renderFactorySlot('contextMenu.button', { target: target('row'), label: 'Row menu' })} ) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'header', target: 'header', order: 0, resolve: () => [], })) } }) @@ -99,7 +100,7 @@ it('toggles moved buttons by target identity, replaces other targets, and preser {renderSlot('shell.overlay', {})}
}) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'header', target: 'header', order: 0, resolve: () => [{ id: 'open', label: 'Open' }], })) } }) @@ -170,7 +171,7 @@ it('keeps an open button expanded after its owner updates display metadata in th update = setCurrent return renderFactorySlot('contextMenu.button', { target: current, label: 'Entity menu' }) }) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'entity', target: 'entity', order: 0, resolve: () => [], })) } }) diff --git a/packages/client/ui-context-menu/tests/overlay.client.spec.tsx b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx index b84e470bbe..718d3edad6 100644 --- a/packages/client/ui-context-menu/tests/overlay.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { bindSnapshotSelector, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' @@ -97,7 +98,7 @@ it('dispatches captured icon keys in rows, submenus and footers and retires rend runtime.slots.installLocale(locale) await runtime.root.declare({ 'shell.overlay': { kind: 'list', scope: 'root' } }, ({ renderSlot }) => <>{renderSlot('shell.overlay', {})}) - const menuPlugin = await runtime.mount({ inject, apply }) + const menuPlugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) const run = vi.fn() const contribution = await runtime.mount({ inject: ['contextMenus'], apply(ctx) { ctx.effect(() => ctx.contextMenus.register({ id: 'icons', target: 'session', order: 0, resolve: () => [ diff --git a/packages/client/ui-context-menu/tests/plugin.client.spec.ts b/packages/client/ui-context-menu/tests/plugin.client.spec.ts index 4d2ab784ba..81d8ebc835 100644 --- a/packages/client/ui-context-menu/tests/plugin.client.spec.ts +++ b/packages/client/ui-context-menu/tests/plugin.client.spec.ts @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import type { MenuAction } from '../src/client/types.ts' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { Context } from '@deepseek-ai/cordis' @@ -28,7 +29,7 @@ it('lets an external contribution open another menu and withdraws its actions wh }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const menuFiber = ctx.plugin({ inject, apply }) + const menuFiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await menuFiber.await() expect(hostApply).not.toThrow() const run = vi.fn() @@ -101,7 +102,8 @@ it('waits for metadata, toggles nearby repeated gestures, replaces occurrences, register: (entry: { store: ReturnType }) => { store = entry.store.create(); return () => {} }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + // No budget from the Host: preparation uses the 1000ms the Client used before the field moved to the Host. + const fiber = ctx.plugin({ inject, apply }, syncedConfig({})) await fiber.await() let finish!: (actions: readonly MenuAction[]) => void ctx.contextMenus.register({ target: 'pluginDocument', id: 'slow', order: 0, @@ -148,7 +150,7 @@ it('keeps trigger focus through replacement and ignores non-dismissal events and register: (entry: { inject: () => MenuOverlayInjected }) => { overlay = entry.inject(); return () => {} }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + const fiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await fiber.await() const notify = ctx.contextMenus.notify.bind(ctx.contextMenus) ctx.contextMenus.register({ target: 'pluginDocument', id: 'plain', order: 0, resolve: () => [{ id: 'copy', label: 'Copy' }] }) @@ -194,7 +196,7 @@ it('leaves unbound keyboard gestures native', async () => { inject: () => () => {}, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + const fiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await fiber.await() try { const event = new KeyboardEvent('keydown', { key: 'ContextMenu', bubbles: true, cancelable: true }) diff --git a/packages/client/ui-context-menu/tests/registry.client.spec.ts b/packages/client/ui-context-menu/tests/registry.client.spec.ts index 20f77e808b..ea7c2ea7d0 100644 --- a/packages/client/ui-context-menu/tests/registry.client.spec.ts +++ b/packages/client/ui-context-menu/tests/registry.client.spec.ts @@ -175,7 +175,7 @@ describe('menu contribution lifecycle', () => { it('omits a provider that misses its deadline and ignores its late result', async () => { vi.useFakeTimers() - const failed = vi.fn(), registry = new MenuRegistry(failed, 50) + const failed = vi.fn(), registry = new MenuRegistry(failed, () => 50) const waiting = deferred() let signal!: AbortSignal registry.register({ id: 'slow', target: 'extension', order: 0, resolve: (_target, value) => { signal = value; return waiting.promise } }) diff --git a/packages/client/ui-context-menu/tests/trigger.client.spec.tsx b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx index 507911379f..2af1690b61 100644 --- a/packages/client/ui-context-menu/tests/trigger.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, createEvent, fireEvent, render } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { createPortal } from 'react-dom' @@ -85,7 +86,7 @@ it('injects the hook through the root Slot and withdraws both its prop and retai retained = useContextMenu().getTriggerProps(target('injected')) return }) - const plugin = await runtime.mount({ inject, apply }) + const plugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) const view = runtime.renderRoot() expect(received).toBe(true) act(() => { fireEvent.contextMenu(view.getByRole('button')) }) diff --git a/packages/client/ui-context-menu/tsconfig.json b/packages/client/ui-context-menu/tsconfig.json index e12f61a4c8..572b52f447 100644 --- a/packages/client/ui-context-menu/tsconfig.json +++ b/packages/client/ui-context-menu/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../config" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index df79f7d1a9..578e4e9188 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,11 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 1ac182250ac0a6c3 - zh: e00ad4457648ebe2 + en: 1ef2a3b18c8cd023 + zh: f646e719c1397894 +/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: + en: 876be274c65b56d9 + zh: c3adbf5a16e0e38e /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -42,8 +45,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: c8323c1986c1be46 - zh: 6151492c67d4cb88 + en: c65789c64093eb47 + zh: b58cccbeea767849 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index e123be46fd..cd71641498 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,13 +100,13 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addReferences` inserts references after the retained selection in one undo step without replacing selected text. `SessionInput.canInsertReferences()` reads the current precondition without notifying changes: it is false after disposal, during submission, for removed or non-continuable subagent Sessions, and while a composer block is set, and `addReferences` rechecks it. Quote insertion shares the Session and block conditions. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft content, including structured references, and attachments move in its synchronous preparation callback only while that request is current and no submission is in flight; later navigation, owner disposal, or a submission in flight leaves the original draft in its Session. -The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. An embedded occurrence may also pass `onWorkspaceSession`: it receives the blank Session of a Workspace the Hero's picker chose, retains it, and shows it, and the draft moves to that Session without it opening as the main Session. The handover runs in one synchronous step once the Workspace connects, and only for the latest pick of an occurrence that is still mounted, so a pick that connects after another pick or after the owner left changes nothing; the Session the draft leaves stays retained through the step, so the owner may release it there. A pick whose Workspace cannot connect shows a transient notice over the conversation and keeps the draft. An embedded occurrence may also pass `headline`, which replaces the Hero headline and preview badge. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. +The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. Every occurrence passes `onWorkspaceSelected`, which decides what a Workspace picked in the Hero does. It receives the Workspace and an `adopt` function, resolves that Workspace's blank Session, shows it in place of the Session shown before, and calls `adopt` with it in the same step while it retains both Sessions; `adopt` moves the draft. The main occurrence opens the blank as the main Session, and an embedded owner may show it itself. A pick the owner no longer wants resolves without calling `adopt`; a failed pick rejects, its owner reports the failure, and the Hero returns to the Workspace it showed. An embedded occurrence may also pass `headline`, which replaces the Hero headline and preview badge. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. A blank Session retains the header's leading and corner controls, including the right-sidebar opener, while hiding its title, actions, utilities, and View tabs. Selecting a Workspace creates the Session needed by these controls; the first message is not required. Without a selected Session, the strict header is absent; the resident header keeps the blank-Session 40px row on every platform, so the Hero input card sits at the same height before and after a Workspace is bound; on macOS desktop that row is also the window drag row. Sidebar entries retain their own data and execution prerequisites. A started Session header uses one row when fewer than two Views are available; the tab row reserves space only while rendered. When the title and actions do not fit, the title area clips them and fades its trailing edge before the utilities, which stay fully visible and clickable; overlays in the title and actions slots portal to stay outside that clip. @@ -116,6 +116,8 @@ View selection is deterministic: a registered persisted selection wins, otherwis The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated. +Until the user drags a width, the main transcript is 64% of the Conversation body wide, from 680px up to 880px; an embedded transcript is the body width less 32px, up to 880px. Beside the main transcript, the composer card is 32px wider than the transcript. + Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The handle scrolls the first `[data-conversation-scroll]` element inside the body, which is the body's own scroll element even when frame layers wrap it. The sticky composer owns its full footer band, which is not a resize target; a captured drag continues under the band and under gutter tables, which cover its indicator. In an active transcript the composer rests at the scrollport floor even when no View fills the column, keeps one stacking rank in every state, above transcript sticky headers and the back-to-bottom control, so menus it opens upward cover that control, and never serves as a scroll-anchoring target. It keeps its own compositor layer whatever lies beneath it, which makes it the containing block for fixed-position descendants: contributions to `conversation.composer`, `conversation.composer.bar`, `conversation.composer.dock`, `conversation.input.dock`, and the other `conversation.input.*` slots must portal fixed overlays to the document body, for example with `Tooltip` or `Menu` `portal` or `createPortal` ([handle and composer styles](src/client/skeleton/ConversationRoot.module.css)). The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged. @@ -130,7 +132,7 @@ Clicking unused space inside an editable composer preserves its current caret or Each composer attempt carries its original occurrence time, gesture, delivery intent, and Session model/run-state snapshot through asynchronous command arbitration. The snapshot also records whether the Session is still blank and the Agent preset id the Session records. The ordinary-message notification fires once before reference serialization, including attachment-only submissions; handled or claimed commands do not notify. Snapshot and notification failures cannot block sending. On Desktop, the notification reports `send_button_click`, which carries `is_new_session` (true while the Session is blank) and `agent_preset`, the preset category: `creator` for `cordis`; `ptc`, `minimal`, and `standard` under their own ids; `other` for any other preset. `agent_preset` is omitted while the Session records no preset. Custom preset ids are not sent. -A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. +A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads`, a volatile field of the Host entry's Config, defaults to two active Worker transports and a raised value starts queued transfers at once, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. Every mounted composer, including a subagent conversation open in the right Sidebar, joins one document-level paste route. A paste whose clipboard carries files, while focus is outside any input, text area, or editable element, enters the composer that most recently held focus, or the main Conversation's composer before any other composer has held focus or while the focused one cannot accept files; a paste inside a focused editor stays with that editor, and clipboard text without files is never inserted this way. A composer in a hidden or inert subtree, such as a collapsed Sidebar or an unselected tab, is never addressed, and while a modal dialog or menu is open only a composer inside it can be. When no addressable composer can accept files, the paste keeps the browser's default handling. @@ -144,6 +146,12 @@ When another writer owns the Session, the send-error toast asks the user to quit Two independent Escape presses in the focused Chat or Composer stop its current running turn and preserve queued messages. The interval comes from the shortcuts plugin’s `stopSequenceMs` configuration (500 ms by default). A menu, approval, modal, terminal, embedded webpage, composition, repeated key, changed input region, Session or turn breaks the sequence. The shortcut uses the same scoped cancellation as the Stop button. The plugin registers Stop as a fixed action in the `input` display group. Its registration reserves plain Escape against editable shortcuts and supplies the `Esc Esc` sequence shown in the Stop button’s hover and keyboard-focus tooltip. +### Control geometry + +The attachment and send controls share a 32px diameter and the toolbar center line in both the initial composer and the docked composer. + +The task panel keeps its heading and task text on one column, using equal leading slots without changing the icon artwork. + ## Temporary composer entries @@ -223,6 +231,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **Factory occurrences inherit their render-position Session** — `conversation.content` does not accept an independently addressed Session; that requires a separate Session-provider capability. - **Manual continuation uses a fixed product allowlist** — the supported failure codes are independent of the provider's configurable `retryableCodes`; changing automatic retry policy does not expand or reduce this action. `STREAM_CLOSED` permits an explicit new user turn even when the default policy does not retry it. That code can also identify a protocol violation, so another request is not guaranteed to recover. - **Composer backdrop blur is verified only in Chromium** — with `will-change: transform` on the docked composer, descendant `backdrop-filter` still samples the transcript in Chromium; WebKit behavior has not been verified. +- **A reload discards draft attachments** — only switching between Sessions keeps them; after a reload the reopened composer reports the loss and asks the user to add them again, and a crash leaves no notice. While a Session is not shown, a pasted image keeps its bytes in memory ([decision](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md)). - **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index f14691a81d..38cf1e48f6 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,13 +100,13 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addReferences` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字。`SessionInput.canInsertReferences()` 读取当前的前置条件,不通知变化:输入模型释放后、提交期间、Session 已移除或为不可继续的子智能体、存在输入框阻塞时为 false,`addReferences` 执行时会再次检查。引文(quote)插入共用其中的 Session 和阻塞条件。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿内容(包括结构化引用)和附件仅在该请求仍为当前请求、且没有在途提交时,通过它的同步准备回调搬移;后续导航、所有者释放或在途提交都会把原草稿留在它的 Session 中。 -本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。嵌入式 occurrence 还可以传入 `onWorkspaceSession`:它接收 Hero 选择器所选工作区的空白 Session,由它保留并显示该 Session;草稿随之移过去,该 Session 不作为主 Session 打开。工作区连接完成后,交接在一个同步步骤内完成,并且只对仍挂载的 occurrence 的最后一次选择进行,因此在另一次选择之后、或 owner 离开之后才连接完成的选择不改变任何状态;草稿所在的 Session 在这一步期间保持保留,owner 可以在其中释放它。工作区无法连接时,在对话上方显示短暂提示,草稿保持不动。嵌入式 occurrence 也可以传入 `headline`,用来替换 Hero 的标题与预览徽标。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 +本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。每个 occurrence 都传入 `onWorkspaceSelected`,由它决定在 Hero 中选择工作区后做什么。它接收工作区和一个 `adopt` 函数:解析该工作区的空白 Session,用它替换此前显示的 Session,并在同一步、仍保留两个 Session 时以它调用 `adopt`;`adopt` 负责移动草稿。主 occurrence 把这个空白 Session 打开为主 Session,嵌入方可以自己显示它。属主不再需要的选择在不调用 `adopt` 的情况下完成;失败的选择会 reject,由属主报告失败,Hero 回到此前显示的工作区。嵌入式 occurrence 也可以传入 `headline`,用来替换 Hero 的标题与预览徽标。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 blank Session 保留 header 的 leading 与 corner 控件,包括右侧栏展开入口,同时隐藏标题、actions、utilities 和 View tabs。选择 Workspace 会创建这些控件所需的 Session,无需先发送消息。没有选中 Session 时,strict header 不挂载;常驻 header 在所有平台都保留与 blank Session 相同的 40px 行,因此绑定 Workspace 前后 Hero 输入卡片的高度位置不变;在 macOS 桌面上,这一行同时是窗口拖拽行。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。标题与 actions 放不下时,标题区域会裁剪它们,并在 utilities 之前渐隐其末端;utilities 始终完整可见且可点击;标题与 actions slot 中的浮层通过 portal 渲染,不受该裁剪影响。 @@ -116,6 +116,8 @@ View 选择规则固定:有效且已注册的持久化选择优先,其次是 Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。 +用户拖动调整宽度之前,主 transcript 宽度为 Conversation 主体宽度的 64%,范围 680px 到 880px;嵌入式 transcript 为主体宽度减 32px,最多 880px。主 transcript 下方的输入框卡片比 transcript 宽 32px。 + 主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。拖拽条滚动的是 body 内第一个 `[data-conversation-scroll]` 元素;即使有 frame 层包在外面,它也是 body 自己的滚动区。粘滞 composer 拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会在该区带和沟槽中的表格下方继续,此时指示线被它们遮住。在活跃 transcript 中,即使没有 View 撑满整列,composer 也停在滚动区底部;它在所有状态下保持同一层级,高于 transcript 的吸顶标题与“回到底部”按钮,因此它向上打开的菜单会盖住该按钮;它也从不作为滚动锚定目标。无论下方是什么内容,它都保持自己的合成层,因此成为 fixed 定位后代的包含块:向 `conversation.composer`、`conversation.composer.bar`、`conversation.composer.dock`、`conversation.input.dock` 以及其他 `conversation.input.*` slot 贡献的内容,必须把 fixed 浮层 portal 到 document body,例如使用 `Tooltip` 或 `Menu` 的 `portal`,或 `createPortal`([拖动手柄与 composer 样式](src/client/skeleton/ConversationRoot.module.css))。 宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。 @@ -130,7 +132,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 每次输入框提交都携带原始发生时间、操作来源、投递意图以及会话模型和运行状态快照,贯穿异步命令裁决。快照还记录会话是否仍为空白,以及会话记录的 Agent preset id。普通消息通知在引用序列化前发出一次,纯附件提交也遵循这一规则;已处理或认领的命令不发出通知。快照读取与通知消费异常不能阻断发送。在桌面端,该通知报告 `send_button_click`,携带 `is_new_session`(会话为空白时为 true)和表示 preset 类别的 `agent_preset`:`cordis` 记为 `creator`;`ptc`、`minimal` 与 `standard` 沿用各自的 id;其他 preset 记为 `other`。会话未记录 preset 时省略 `agent_preset`。不发送自定义 preset 的 id。 -默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 +默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 是 Host 条目 Config 中的 volatile 字段,默认允许两个 Worker transport 同时运行,调高后立即启动排队中的传输,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 每个已挂载的 composer(包括在右侧栏打开的子代理对话)都加入同一条文档级粘贴路由。焦点不在任何输入框、文本区域或可编辑元素内时,剪贴板带有文件的粘贴会进入最近一次获得焦点的 composer;在其他 composer 获得焦点之前,或最近聚焦的 composer 当前无法接收文件时,则进入主 Conversation 的 composer。已聚焦编辑器内的粘贴仍由该编辑器处理,不含文件的剪贴板文字不会经此插入。位于隐藏或 inert 子树中的 composer(例如折叠的侧栏或未选中的标签页)不会成为目标;打开模态对话框或菜单时,只有其中的 composer 可以成为目标。没有可作为目标的 composer 能接收文件时,粘贴保留浏览器的默认处理。 @@ -144,6 +146,12 @@ Send 和 Stop 按钮禁用时不显示提示气泡,轮次结束后由 Stop 切 在获得焦点的 Chat 或 Composer 中连续独立按下两次 Esc,可停止当前运行轮次并保留排队消息。间隔由 shortcuts 插件的 `stopSequenceMs` 配置决定,默认 500 ms。菜单、审批、模态层、终端、内嵌网页、输入法、重复按键,以及输入区域、Session 或轮次变化会清空序列。快捷键与 Stop 按钮调用同一作用域取消操作。插件将 Stop 注册为 `input` 展示分组中的固定操作。该注册使普通 Esc 不能分配给可编辑快捷键,并为 Stop 按钮的悬停和键盘聚焦提示提供 `Esc Esc` 序列。 +### 控件布局 + +初始输入区与底部输入区的附件、发送控件共用 32px 直径及工具栏中心线。 + +任务面板的标题和任务文字共用一列,通过相同的前导槽对齐,不改变图标绘制。 + ## 临时 composer entry @@ -223,6 +231,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **Factory occurrence 继承渲染位置的 Session**——`conversation.content` 不接受独立寻址的 Session;该能力需要单独的 Session provider。 - **手动继续使用固定产品白名单**——支持的失败码独立于提供方可配置的 `retryableCodes`;修改自动重试策略不会扩展或缩小此操作的范围。即使默认策略不重试 `STREAM_CLOSED`,用户仍可明确发起新轮次。该错误码也可能表示协议违规,因此再次请求不保证能够恢复。 - **composer 内的毛玻璃只在 Chromium 中验证过**——docked composer 设置 `will-change: transform` 后,Chromium 中后代的 `backdrop-filter` 仍会采样背后的 transcript;WebKit 中的表现尚未验证。 +- **刷新会丢弃草稿附件**——只有在 Session 之间切换时附件才会保留;刷新后重新打开的输入框会提示丢失并请用户重新添加,崩溃时不会有提示。Session 未显示期间,粘贴的图片会把字节保留在内存中([决策](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md))。 - **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index abfcd2fdab..737e3aa960 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -102,7 +102,8 @@ "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "zod": "4.6.6", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index cadc779974..2ed062b42f 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -2,7 +2,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Registers the target-neutral Conversation assembly, shell, input, and docks. */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { Context } from '@deepseek-ai/cordis' -import z from '@deepseek-ai/schemastery' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { ConversationConfig } from '../types.ts' import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' import { IconPaperclipOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' @@ -21,7 +22,7 @@ import { sessionReferenceRule } from './user-text/session-reference-rule.ts' import { collapseWhitespaceRule, trimWhitespaceRule } from './user-text/whitespace-rules.ts' import type { ViewTab } from './contract/views.ts' import type { - ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, + ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationShellInjected, ConversationSessionInjected, DraftFileUploads, UserTextInjected, } from './contract/slots.ts' import type { InputNotice } from './contract/input.ts' @@ -67,16 +68,6 @@ export const inject = [ 'slots', 'sessions', 'fileUpload', 'uiSession', 'uiSession.sessionStatus', 'uiWorkspace', 'locale', 'configForms', ] -/** Conversation runtime configuration. */ -export interface Config { - /** Maximum generic-file uploads allowed to run concurrently in browser Workers. */ - maxConcurrentFileUploads?: number -} - -/** Validated Conversation runtime configuration. */ -export const Config: z = z.object({ - maxConcurrentFileUploads: z.natural().min(1).default(2), -}) // Stable no-session sources keep the renderer's observable-hook cache and // hook order unchanged across current-Session transitions. @@ -121,10 +112,9 @@ function hostPathBridge(): HostPathBridge | undefined { interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( - workspaceId: Parameters[0], + workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise - connectWorkspace(workspaceId: Parameters[0]): Promise } /** Action registration used by the composer without importing its command-UI consumer. */ @@ -159,12 +149,12 @@ function concreteConversation(ctx: Context): ConversationController { /** * Mount the Conversation core and target-neutral presentation. * @param ctx - Client root context. + * @param config - Host-synced live configuration. */ -export function apply(ctx: Context, config: Config = Config({})): void { +export function apply(ctx: Context, config: SyncedConfig): void { const sessions = ctx.sessions const slots = ctx.slots - // Schemastery's field default is materialized before Cordis calls apply. - const maxConcurrentFileUploads = config.maxConcurrentFileUploads as number + const fileUploadLimit = config.maxConcurrentFileUploads const workspaceNavigation = ctx.get('uiWorkspace') as WorkspaceNavigation const uiConversation = new UiConversation(ctx, sessions) uiConversation.userText.register(sessionReferenceRule) @@ -339,6 +329,10 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, }) + const shellInjected: ConversationShellInjected = { + openWorkspace: (workspaceId, adopt) => workspaceNavigation.openWorkspace(workspaceId, adopt), + } + const registerConversationRoot = () => slots.register({ name: 'main.conversation', children: { @@ -369,46 +363,31 @@ export function apply(ctx: Context, config: Config = Config({})): void { hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), }, - selectWorkspace: (workspaceId, report) => { - const moveDraft = (nextId: SessionId): void => { - if (sessionId !== undefined && nextId !== sessionId) { - const from = inputHub.shell(sessionId) - // A draft with a submission in flight stays with the Session that is admitting it. - if (from.snapshot.phase !== 'plain' && from.snapshot.phase !== 'claimed') return - const draft = from.draftSnapshot - const attachmentIds = from.snapshot.attachmentIds - const next = inputHub.shell(nextId) - if (attachmentIds.length === 0 || next.addAttachments(attachmentIds)) { - const binding = sessions.binding(nextId) - if (binding === undefined) { - throw new Error(`ui-conversation: session "${nextId}" resolved no binding`) - } - // The same rule as intake: only an ordinary Session stages image uploads. - const ordinary = binding.session.getSnapshot().subagent === null - concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds, ordinary) - if (draft.text !== '') { - next.setDraft(draft) - from.setDraft('') - } - if (attachmentIds.length > 0) { - for (const id of attachmentIds) from.removeAttachment(id) - } + moveDraft: (nextId) => { + if (sessionId !== undefined && nextId !== sessionId) { + const from = inputHub.shell(sessionId) + // A draft with a submission in flight stays with the Session that is admitting it. + if (from.snapshot.phase !== 'plain' && from.snapshot.phase !== 'claimed') return + const draft = from.draftSnapshot + const attachmentIds = from.snapshot.attachmentIds + const next = inputHub.shell(nextId) + if (attachmentIds.length === 0 || next.addAttachments(attachmentIds)) { + const binding = sessions.binding(nextId) + if (binding === undefined) { + throw new Error(`ui-conversation: session "${nextId}" resolved no binding`) + } + // The same rule as intake: only an ordinary Session stages image uploads. + const ordinary = binding.session.getSnapshot().subagent === null + concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds, ordinary) + if (draft.text !== '') { + next.setDraft(draft) + from.setDraft('') + } + if (attachmentIds.length > 0) { + for (const id of attachmentIds) from.removeAttachment(id) } } } - if (report === undefined) return workspaceNavigation.openWorkspace(workspaceId, moveDraft) - return workspaceNavigation.connectWorkspace(workspaceId).then((nextId) => { - // No await from here on, so nothing interleaves with the handover. The Session the draft leaves stays - // retained through it: `report` may release its own reference when it switches to `nextId`. - const source = sessionId === undefined || sessions.binding(sessionId) === undefined - ? undefined - : sessions.retain(sessionId, { source: 'controllerOperation' }) - try { - if (report(nextId)) moveDraft(nextId) - } finally { - source?.release() - } - }) }, }), }, ConversationContent) @@ -605,7 +584,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { yield slots.register({ name: 'main', key: 'conversation', - children: { 'main.conversation': { kind: 'single', scope: 'session-maybe' } }, + children: { 'main.conversation': { kind: 'single', scope: 'session-maybe', inject: shellInjected } }, }, ConversationPanel) yield registerConversationRoot() yield registerConversationContent() @@ -618,7 +597,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { ctx.plugin(ConversationController, { input: inputHub, blocks: composerBlocks, - maxConcurrentFileUploads, + maxConcurrentFileUploads: fileUploadLimit, }) ctx.plugin(todoDockEntry) ctx.plugin(queueDockEntry) diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index 3d8ebd6d6a..b93838c26f 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -1,10 +1,10 @@ /** - * Frozen input-machine contract. Types - * only. Three-tier visibility: business packages see InputState via the - * InputZone currency; the scoped input events carry the mutation verbs; the - * conversation wiring layer alone sees the full SessionInput. The draft text - * and its reference chips live in the shell's Lexical editor; the machine - * here is the submit plane (phase, claim, attempt) alone. + * Input-machine types and Session-addressed draft operations. Business packages + * read InputState through InputZone and use scoped input events for guarded + * mutations. Conversation wiring and direct draft consumers resolve SessionInput + * through conversation.input.for(), including reference insertion through addReferences. + * Draft text and reference chips live in the shell's Lexical editor; the machine + * here owns submission state (phase, claim, attempt). */ import type { Context } from '@deepseek-ai/cordis' import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' @@ -195,6 +195,19 @@ export interface SessionInput extends InputTarget { setDraft(text: string): void /** Append ordered browser-owned attachment ids; busy admission phases refuse. */ addAttachments(ids: readonly DraftAttachmentId[]): boolean + /** + * Insert file references after the retained selection in one undo step without replacing text. + * @param references - validated reference chips in source order. + * @returns false while {@link canInsertReferences} is false or when the editor refuses insertion. + */ + addReferences(references: readonly ReferenceInsert[]): boolean + /** + * Read whether {@link addReferences} can currently edit the draft. Callers read it when they + * present the operation; the answer does not notify changes, and addReferences rechecks it. + * @returns false after disposal, during submission, for removed or non-continuable subagent Sessions, + * and while a composer block is set. + */ + canInsertReferences(): boolean /** Remove one browser-owned attachment id; busy admission phases refuse. @returns whether the id was removed. */ removeAttachment(id: DraftAttachmentId): boolean /** Drop ids whose browser-owned objects no longer exist. */ diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 3d6f0e1943..4efcee6601 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -226,7 +226,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { keyProps: { [Id in UserTextId]: { node: UserTextNode } } } /** Conversation shell beneath its root-scoped main-panel entry. */ - 'main.conversation': { kind: 'single'; scope: 'session-maybe' } + 'main.conversation': { kind: 'single'; scope: 'session-maybe'; inject: ConversationShellInjected } /** Strict per-Session Conversation body. */ 'conversation.session': { kind: 'single' @@ -466,16 +466,32 @@ export interface ConvViewOwnerProps { /** Base props of one target-owned Conversation View entry. */ export type ConvViewProps = PropsRuntime<'conversation.view'> -/** Business callbacks injected into the resident Conversation shell. */ +/** + * Moves the draft of the Session a Hero shows to the Session that replaces it. The occurrence owner calls it at most + * once per pick, synchronously with the step that shows the new Session, while it still retains both Sessions. + */ +export type WorkspaceSessionAdopter = (sessionId: SessionId) => void + +/** + * Handles a Workspace the Hero's picker chose: resolves that Workspace's blank Session, shows it in place of the + * Session shown before, and calls `adopt` with it in the same step. A pick the owner no longer wants resolves + * without calling `adopt`; a pick that failed rejects, and the owner reports the failure. + */ +export type WorkspaceSelectedHandler = (workspaceId: WorkspaceId, adopt: WorkspaceSessionAdopter) => Promise + +/** Business callbacks injected into the main Conversation shell. */ +export interface ConversationShellInjected { + /** Open the Workspace's blank Session as the main Session. */ + openWorkspace: WorkspaceSelectedHandler +} + +/** Business callbacks injected into the shared Conversation content. */ export interface ConversationInjected { /** - * Connect a blank Session in the selected Workspace and move the draft to it. Without `report` it opens as the main - * Session. With `report`, the connected Session is offered to it in one synchronous step: `report` returns whether - * the pick is still wanted and, when it is, retains the Session before it returns; the Session the draft comes from - * stays retained until the draft has moved, so `report` may release it. A declined pick changes nothing. A failed - * connection rejects; with `report`, the caller shows the failure. + * Move this occurrence's draft text and attachments to another Session. Both Sessions must be retained; a draft + * with a submission in flight stays where it is. */ - selectWorkspace: (workspaceId: WorkspaceId, report?: (sessionId: SessionId) => boolean) => Promise + moveDraft: WorkspaceSessionAdopter /** Session-addressed composer block source, or the stable absent source. */ hooks: { composerBlock: ObservableSnapshot } } @@ -689,15 +705,8 @@ export interface ConversationContentInputProps { variant: 'main' | 'embedded' phase: 'settling' | 'hero' | 'active' hero: boolean - /** - * Receives the blank Session of a Workspace the Hero's picker chose instead of that blank opening as the main - * Session; an embedded occurrence that sets it shows the reported Session itself. It is called only for the latest - * pick, and only while the occurrence still shows the Session the pick started from; a pick that completes later - * changes nothing. It must retain the reported Session before it returns and may release the one shown before: - * the draft moves to the reported Session once it returns. A pick whose Workspace cannot connect shows a transient - * notice and keeps the draft where it is. - */ - onWorkspaceSession?: ((sessionId: SessionId) => void) | undefined + /** What a Workspace picked in the Hero does in this occurrence; the main occurrence opens it as the main Session. */ + onWorkspaceSelected: WorkspaceSelectedHandler /** Text the blank-session Hero shows instead of its default headline and preview badge. */ headline?: string | undefined } diff --git a/packages/client/ui-conversation/src/client/contract/system-prompt.ts b/packages/client/ui-conversation/src/client/contract/system-prompt.ts index e61b35d81b..3ac1fadcc7 100644 --- a/packages/client/ui-conversation/src/client/contract/system-prompt.ts +++ b/packages/client/ui-conversation/src/client/contract/system-prompt.ts @@ -1,4 +1,5 @@ /** Immutable system-only interpretation of the loaded Session surface. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { isSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { SystemPromptNode } from './request-inspection.ts' @@ -61,7 +62,7 @@ export function inspectSystemPrompt(previous: SystemPromptState | undefined, eve time: event.time, turn: event.data.turn, step: event.data.step, - text: event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''), + text: extractTextContent(event.data.message.content), update: op === 'append' && previous?.nodes.some(item => item.node.text !== '') === true, } : undefined diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 8a1b95e941..2aa335183b 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -24,8 +24,7 @@ export type { UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode, UserTextRule, UserTextTransformContext, } from './contract/user-text.ts' export type { UserTextRegistry } from './conversation/user-text-registry.ts' -export { apply, Config, inject } from './apply.ts' -export type { Config as ConversationConfig } from './apply.ts' +export { apply, inject } from './apply.ts' export { UiConversation } from './conversation/assembly.ts' export type { ConversationBinding } from './conversation/assembly.ts' export type { ConversationGroupRegistry } from './conversation/group-registry.ts' @@ -87,7 +86,7 @@ export type { ComposerBarInjected, ComposerBarOwnerProps, ComposerBarProps, ComposerChainProps, ConversationHeaderActionOwnerProps, ConversationHeaderCornerOwnerProps, ConversationHeaderLineageOwnerProps, ConversationContentInputProps, ConversationContentProps, - ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, + ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, ConversationShellInjected, ConversationSessionInjected, ConversationSessionSlotProps, ConversationSlotProps, ConversationViewActionEntry, ConversationViewActionsOwnerProps, ConversationViewsProps, ConversationWidthControlsInputProps, ConversationWidthControlsProps, @@ -95,6 +94,7 @@ export type { HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, HeroFrameOwnerProps, InputControlOwnerProps, InputZone, MessageImageLabels, MessageImageLoader, MessageImageSource, MessageImagesContentInput, MessageImagesOwnerProps, UseConversation, UserTextInput, UserTextInjected, UserTextNodeOwnerProps, UserTextNodeProps, + WorkspaceSelectedHandler, WorkspaceSessionAdopter, UseConversationViews, } from './contract/slots.ts' export type { diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 1fd208b6f7..393c88944c 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -10,6 +10,7 @@ */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' +import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore, } from '@deepseek-ai/dsh-client-store' @@ -24,6 +25,7 @@ import type { ArbitrateKey, ArbitrateOutcome, ComposerKeyboard, DraftInput, DraftSnapshot, ReferenceInsert, TokenSpan, } from '../contract/draft-editor.ts' import type { InputSubmitMode, MessageSubmission, MessageSubmissionState } from '../contract/composer-submission.ts' +import type { ComposerBlock } from '../contract/composer-blocks.ts' import { serializeDraftPrompt } from './prompt.ts' import { SubmitMachine } from './machine.ts' import { resolveDraftInput, snapshotDraft } from '../draft.ts' @@ -71,8 +73,10 @@ export interface SessionInputDeps { signal: AbortSignal, accept: () => void, ): Promise - /** Live Session and composer-block policy for transcript insertion. */ - quoteInsertionAllowed?: () => boolean + /** Read the Session facts whose removal and subagent mode gate quote and reference insertion; absent permits both. */ + session?: (() => Pick) | undefined + /** Read the Session's current composer block; absent means never blocked. */ + composerBlock?: (() => ComposerBlock | undefined) | undefined /** Current localized quote removal copy. */ quoteRemoveLabel?: () => string /** Command-plane attachment plumbing (the hub owns the conversation face and the copy). */ @@ -242,7 +246,7 @@ export class SessionInputShell implements SessionInput { * @returns whether the editable draft accepted the quote. */ insertQuote(text: string, summary?: QuoteSummary): boolean { - if (this.disposed || this.snapshot.phase !== 'plain' || this.deps.quoteInsertionAllowed?.() === false || text.trim() === '') return false + if (this.disposed || this.snapshot.phase !== 'plain' || !this.sessionAcceptsInsertion() || text.trim() === '') return false const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }, summary) if (inserted) this.focus() return inserted @@ -331,6 +335,14 @@ export class SessionInputShell implements SessionInput { return this.disposed || frozen(this.core.state.phase) } + /** Whether the Session lets features outside the composer insert quotes or references. */ + private sessionAcceptsInsertion(): boolean { + const session = this.deps.session?.() + if (session !== undefined && (session.removed + || (session.subagent !== null && session.subagent.address.mode !== 'continuable'))) return false + return this.deps.composerBlock?.() === undefined + } + /** Append ordered attachment ids unless an admission transaction is locked. */ addAttachments(ids: readonly DraftAttachmentId[]): boolean { if (frozen(this.snapshot.phase)) return false @@ -342,18 +354,33 @@ export class SessionInputShell implements SessionInput { /** * Add validated file references and attachment ids while admission is editable. + * Drop and paste use this wiring-layer method; other packages use {@link addReferences}. * @param references - reference chips in source order. * @param ids - newly allocated attachment ids. - * @returns false when admission is locked or the editor refuses the insertion. + * @returns false after disposal, when admission is locked, or when the editor refuses insertion. */ addFiles(references: readonly ReferenceInsert[], ids: readonly DraftAttachmentId[]): boolean { - if (frozen(this.snapshot.phase)) return false + if (this.disposed || frozen(this.snapshot.phase)) return false if (!this.draftEditor.insertFileReferences(references)) return false this.attachmentIds = [...this.attachmentIds, ...ids] this.publish() return true } + /** + * @param references - validated reference chips in source order. + * @returns whether the draft accepted the references. + */ + addReferences(references: readonly ReferenceInsert[]): boolean { + if (!this.canInsertReferences()) return false + return this.addFiles(references, []) + } + + /** @inheritdoc */ + canInsertReferences(): boolean { + return !this.disposed && !frozen(this.snapshot.phase) && this.sessionAcceptsInsertion() + } + /** * Remove one attachment id from this draft. Busy admission phases refuse, like * {@link addAttachments}: a removal landing while a send serializes would diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index f6e9ce4183..7844495e2e 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -52,11 +52,41 @@ interface ConversationAttachmentFace { ): Promise serializeDraftAttachments(attachmentIds: readonly DraftAttachmentId[]): Promise releaseDraftAttachment(id: DraftAttachmentId): void + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] + draftAttachmentSessions(): readonly SessionId[] + releaseDraftSession(sessionId: SessionId): void +} + +/** Per-Session marker that a page unload discarded the draft's browser-owned attachments. */ +const UNLOAD_MARK_PREFIX = 'dsh.composer-draft-attachments-unloaded' + +/** Record that an unloading page held draft attachments for these Sessions. */ +function writeUnloadMarks(sessionIds: readonly SessionId[]): void { + try { + for (const sessionId of sessionIds) localStorage.setItem(`${UNLOAD_MARK_PREFIX}.${sessionId}`, '1') + } catch (error) { + console.error('conversation draft attachment unload marks could not be saved; a reload cannot report the loss', error) + } +} + +/** Remove one Session's unload marker. @returns whether the marker was present. */ +function takeUnloadMark(sessionId: SessionId): boolean { + try { + const key = `${UNLOAD_MARK_PREFIX}.${sessionId}` + const marked = localStorage.getItem(key) !== null + localStorage.removeItem(key) + return marked + } catch (error) { + console.error('conversation draft attachment unload mark could not be read', error) + return false + } } /** Session-addressed input facade registry (SessionInputResolver face + composer-layer extras). */ export class InputHub implements SessionInputResolver { private readonly shells = new WeakMap() + private knownSessionIds: Set | undefined + private lifecycleWatchInstalled = false /** * @param ctx - client root context (services resolved lazily per call — boot order stays free). @@ -127,12 +157,8 @@ export class InputHub implements SessionInputResolver { inbox: session.projections.faceOf('inbox') as ObservableSnapshot, defaultSink: (text, attachmentIds, mode, signal, accept) => this.sink(session, text, attachmentIds, mode, signal, accept), quoteRemoveLabel: () => this.t('quote.remove'), - quoteInsertionAllowed: () => { - const state = session.getSnapshot() - return !state.removed && (state.subagent === null - || state.subagent.address.mode === 'continuable') - && this.conversation().blocks.storeFor(session.sessionId).getSnapshot() === undefined - }, + session: () => session.getSnapshot(), + composerBlock: () => this.conversation().blocks.storeFor(session.sessionId).getSnapshot(), steerQueue: () => { void this.steerQueue(session, shell) }, commandAttachments: { serialize: async (ids) => { @@ -168,10 +194,24 @@ export class InputHub implements SessionInputResolver { ] return () => { for (const off of offs) off() + // Snapshot the phase before dispose resets the machine. + const phaseAtTeardown = shell.snapshot.phase const drafts = shell.dispose() this.shells.delete(binding) const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - for (const attachmentId of drafts) conversation?.releaseDraftAttachment(attachmentId) + if (conversation === undefined) return + if (binding.session.getSnapshot().removed) { + conversation.releaseDraftSession(binding.sessionId) + return + } + // Teardown aborts adjudication before any message leaves, so those attachments stay with the draft. + // A message or command already submitted cannot settle through its retirement path after teardown, + // and the Client cannot tell whether a submitted command consumed its attachments, so both release + // here rather than risk a duplicate submission; every other draft attachment stays registered for + // the Session's next composer. + if (phaseAtTeardown === 'sending' || phaseAtTeardown === 'submitting') { + for (const attachmentId of drafts) conversation.releaseDraftAttachment(attachmentId) + } } }, 'conversation.input: session shell') actx.inject(['inputTriggers'], (scope) => { @@ -181,9 +221,64 @@ export class InputHub implements SessionInputResolver { }, 'conversation.input: reference catalogs') }) shell.setDraft(readConversationDraft(binding.sessionId)) + this.ensureLifecycleWatch() + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const retained = conversation?.draftAttachmentIds(binding.sessionId) ?? [] + // A Session switch keeps the draft's attachments registered; this composer re-adopts them. + if (retained.length > 0) shell.addAttachments(retained) + // A reload discarded the browser-owned attachments; say so instead of dropping them silently. + if (takeUnloadMark(binding.sessionId) && retained.length === 0) shell.notify('error', this.t('attachments.unavailable')) return shell } + /** + * Install the root-lifetime watchers once: a Session removed while no composer + * is mounted releases its draft attachments, and an unloading page marks the + * Sessions whose attachments it discards. + */ + private ensureLifecycleWatch(): void { + if (this.lifecycleWatchInstalled) return + this.lifecycleWatchInstalled = true + const sessions = this.sessions() + this.knownSessionIds = new Set(sessions.list.getSnapshot().ids) + this.rootCtx.effect(() => { + const stop = sessions.list.subscribe(() => { this.cleanupRemovedSessions() }) + const conversation = (): ConversationAttachmentFace | undefined => + this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const onHide = (): void => { writeUnloadMarks(conversation()?.draftAttachmentSessions() ?? []) } + // A back-forward cache restore keeps the registry, so the marks just written are stale. + const onShow = (event: PageTransitionEvent): void => { + if (!event.persisted) return + for (const sessionId of conversation()?.draftAttachmentSessions() ?? []) takeUnloadMark(sessionId) + } + window.addEventListener('pagehide', onHide) + window.addEventListener('pageshow', onShow) + return () => { + stop() + window.removeEventListener('pagehide', onHide) + window.removeEventListener('pageshow', onShow) + this.knownSessionIds = undefined + this.lifecycleWatchInstalled = false + } + }, 'conversation.input: draft attachment lifecycle') + } + + /** Release draft attachments and unload marks for every Session removed from the catalog. */ + private cleanupRemovedSessions(): void { + const known = this.knownSessionIds + /* v8 ignore next -- the catalog subscription is stopped before the known set is cleared. */ + if (known === undefined) return + const liveIds = new Set(this.sessions().list.getSnapshot().ids) + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + for (const id of [...known]) { + if (liveIds.has(id)) continue + known.delete(id) + conversation?.releaseDraftSession(id) + takeUnloadMark(id) + } + for (const id of liveIds) known.add(id) + } + /** * Resident shell by session id (service-face path; the provide channel has * normally created it already — this covers direct id-addressed access). diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 74a5f4466a..2186b0e80c 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -41,6 +41,7 @@ export const zh = { 'attachment.pathUnavailable': '无法获取文件夹路径,请重新拖入', 'attachment.pathUnsupported': '路径含有无法引用的字符,请改名后再试', 'image.pending': '待发送图片', + 'attachments.unavailable': '部分草稿附件已失效,请重新添加', 'image.openOriginal': '查看原图', 'image.openOriginalLabel': '{label},点击查看原图', 'image.remove': '移除图片 {name}', @@ -392,7 +393,6 @@ export const zh = { 'queue.steer': '插话发送', 'queue.steer.unavailable': '仅运行中可插话发送', 'error.sessionInUse': '当前会话已被占用,可能是其他正在运行的 DSH 导致的(如其他 dsh web、桌面端),请退出其他正在运行的 DSH 后重试。', - 'error.workspaceConnectFailed': '没能打开这个工作区:{message}', 'queue.editFailed': '编辑失败:这条消息可能已经开始发送。', 'queue.removeFailed': '删除失败:这条消息可能已经开始发送。', 'queue.steerFailed': '插话发送失败,请重试。', @@ -448,6 +448,7 @@ export const en = { 'attachment.pathUnavailable': 'Could not obtain the folder path; drag it in again', 'attachment.pathUnsupported': 'The path contains characters a reference cannot carry; rename it and try again', 'image.pending': 'Pending images', + 'attachments.unavailable': 'Some draft attachments are no longer available; add them again', 'image.openOriginal': 'View original', 'image.openOriginalLabel': '{label}, click to view original', 'image.remove': 'Remove image {name}', @@ -799,7 +800,6 @@ export const en = { 'queue.steer': 'Steer queued message', 'queue.steer.unavailable': 'Steering is available only while the agent is running', 'error.sessionInUse': 'This session is already in use, possibly by another running DSH instance (such as dsh web or the desktop app). Quit other running DSH instances and try again.', - 'error.workspaceConnectFailed': "Couldn't open this workspace: {message}", 'queue.editFailed': 'Edit failed: this message may have already started sending.', 'queue.removeFailed': 'Removal failed: this message may have already started sending.', 'queue.steerFailed': 'Steering failed. Try again.', @@ -854,6 +854,7 @@ export const ja = { 'attachment.pathUnavailable': 'フォルダのパスを取得できませんでした。もう一度ドラッグしてください', 'attachment.pathUnsupported': 'パスに参照できない文字が含まれています。名前を変更して再試行してください', 'image.pending': '保留中の画像', + 'attachments.unavailable': '一部の下書き添付ファイルは利用できなくなりました。再度追加してください', 'image.openOriginal': '元の画像を表示', 'image.openOriginalLabel': '{label}、クリックで元の画像を表示', 'image.remove': '画像{name}を削除', @@ -1205,7 +1206,6 @@ export const ja = { 'queue.steer': 'キュー内のメッセージを実行中の指示に追加', 'queue.steer.unavailable': '指示の変更はエージェントの実行中のみ利用できます', 'error.sessionInUse': 'このセッションはすでに使用中です。別の実行中のDSHインスタンス(dsh webやデスクトップアプリなど)が使用している可能性があります。他のDSHインスタンスを終了して再試行してください。', - 'error.workspaceConnectFailed': 'このワークスペースを開けませんでした:{message}', 'queue.editFailed': '編集に失敗しました。このメッセージはすでに送信が開始されている可能性があります。', 'queue.removeFailed': '削除に失敗しました。このメッセージはすでに送信が開始されている可能性があります。', 'queue.steerFailed': '指示の変更に失敗しました。再試行してください。', @@ -1258,6 +1258,7 @@ export const es = { 'attachment.pathUnavailable': 'No se pudo obtener la ruta de la carpeta; arrástralo de nuevo', 'attachment.pathUnsupported': 'La ruta contiene caracteres que una referencia no puede contener; cámbiale el nombre y vuelve a intentarlo.', 'image.pending': 'Imágenes pendientes', + 'attachments.unavailable': 'Algunos adjuntos del borrador ya no están disponibles; vuelve a añadirlos', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, haga clic para ver el original', 'image.remove': 'Eliminar imagen {name}', @@ -1604,7 +1605,6 @@ export const es = { 'queue.steer': 'Redirigir mensaje en cola', 'queue.steer.unavailable': 'La dirección solo está disponible mientras el agente está en ejecución', 'error.sessionInUse': 'Esta sesión ya está en uso, posiblemente por otra instancia de DSH en ejecución (como la web dsh o la aplicación de escritorio). Salga de otras instancias de DSH en ejecución y vuelva a intentarlo.', - 'error.workspaceConnectFailed': 'No se pudo abrir este espacio de trabajo: {message}', 'queue.editFailed': 'Error de edición: es posible que este mensaje ya haya comenzado a enviarse.', 'queue.removeFailed': 'Error al eliminar: es posible que este mensaje ya haya comenzado a enviarse.', 'queue.steerFailed': 'La dirección falló. Intentar otra vez.', @@ -1664,6 +1664,7 @@ export const fr = { 'attachment.pathUnavailable': "Impossible d'obtenir le chemin du dossier ; fais-le glisser à nouveau", 'attachment.pathUnsupported': "Le chemin contient des caractères qu'une référence ne peut pas transporter ; renommez-le et réessayez", 'image.pending': 'Images en attente', + 'attachments.unavailable': 'Certaines pièces jointes du brouillon ne sont plus disponibles ; ajoutez-les à nouveau', 'image.openOriginal': "Voir l'original", 'image.openOriginalLabel': "{label}, cliquez pour voir l'original", 'image.remove': "Supprimer l'image {name}", @@ -2010,7 +2011,6 @@ export const fr = { 'queue.steer': 'Guider avec le message en attente', 'queue.steer.unavailable': "Le pilotage est disponible uniquement lorsque l'agent est en cours d'exécution", 'error.sessionInUse': "Cette session est déjà utilisée, éventuellement par une autre instance DSH en cours d'exécution (telle que le Web dsh ou l'application de bureau). Quittez les autres instances DSH en cours d'exécution et réessayez.", - 'error.workspaceConnectFailed': "Impossible d'ouvrir cet espace de travail : {message}", 'queue.editFailed': "Échec de la modification : l'envoi de ce message a peut-être déjà commencé.", 'queue.removeFailed': "Échec de la suppression : l'envoi de ce message a peut-être déjà commencé.", 'queue.steerFailed': 'La direction a échoué. Essayer à nouveau.', @@ -2070,6 +2070,7 @@ export const de = { 'attachment.pathUnavailable': 'Der Ordnerpfad konnte nicht abgerufen werden; Ziehen Sie es erneut hinein', 'attachment.pathUnsupported': 'Der Pfad enthält Zeichen, die eine Referenz nicht enthalten kann; Benennen Sie es um und versuchen Sie es erneut', 'image.pending': 'Ausstehende Bilder', + 'attachments.unavailable': 'Einige Entwurfsanhänge sind nicht mehr verfügbar; füge sie erneut hinzu', 'image.openOriginal': 'Original ansehen', 'image.openOriginalLabel': '{label}, klicken Sie, um das Original anzuzeigen', 'image.remove': 'Bild {name} entfernen', @@ -2416,7 +2417,6 @@ export const de = { 'queue.steer': 'Mit vorgemerkter Nachricht lenken', 'queue.steer.unavailable': 'Die Steuerung ist nur verfügbar, während der Agent ausgeführt wird', 'error.sessionInUse': 'Diese Sitzung wird bereits verwendet, möglicherweise von einer anderen laufenden DSH-Instanz (z. B. dsh Web oder der Desktop-App). Beenden Sie andere laufende DSH-Instanzen und versuchen Sie es erneut.', - 'error.workspaceConnectFailed': 'Dieser Arbeitsbereich konnte nicht geöffnet werden: {message}', 'queue.editFailed': 'Bearbeitung fehlgeschlagen: Der Versand dieser Nachricht wurde möglicherweise bereits gestartet.', 'queue.removeFailed': 'Fehler beim Entfernen: Der Versand dieser Nachricht wurde möglicherweise bereits gestartet.', 'queue.steerFailed': 'Lenkung versagt. Versuchen Sie es erneut.', @@ -2476,6 +2476,7 @@ export const ru = { 'attachment.pathUnavailable': 'Не удалось получить путь к папке; перетащите это снова', 'attachment.pathUnsupported': 'Путь содержит символы, которые не может содержать ссылка; переименуй его и попробуй еще раз', 'image.pending': 'Ожидающие изображения', + 'attachments.unavailable': 'Некоторые вложения черновика больше недоступны; добавьте их снова', 'image.openOriginal': 'Посмотреть оригинал', 'image.openOriginalLabel': '{label}, нажмите, чтобы посмотреть оригинал', 'image.remove': 'Удалить изображение {name}', @@ -2822,7 +2823,6 @@ export const ru = { 'queue.steer': 'Направить сообщение из очереди', 'queue.steer.unavailable': 'Управление доступно только во время работы агента.', 'error.sessionInUse': 'Этот сеанс уже используется, возможно, другим работающим экземпляром DSH (например, веб-сайтом dsh или настольным приложением). Закройте другие работающие экземпляры DSH и повторите попытку.', - 'error.workspaceConnectFailed': 'Не удалось открыть это рабочее пространство: {message}', 'queue.editFailed': 'Не удалось изменить: возможно, это сообщение уже начало отправляться.', 'queue.removeFailed': 'Удаление не удалось: возможно, это сообщение уже начало отправляться.', 'queue.steerFailed': 'Рулевое управление не удалось. Попробуйте еще раз.', @@ -2882,6 +2882,7 @@ export const pt = { 'attachment.pathUnavailable': 'Não foi possível obter o caminho da pasta; arraste-o novamente', 'attachment.pathUnsupported': 'O caminho contém caracteres que uma referência não pode transportar; renomeie-o e tente novamente', 'image.pending': 'Imagens pendentes', + 'attachments.unavailable': 'Alguns anexos do rascunho não estão mais disponíveis; adicione-os novamente', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, clique para ver o original', 'image.remove': 'Remover imagem {name}', @@ -3228,7 +3229,6 @@ export const pt = { 'queue.steer': 'Orientar com mensagem da fila', 'queue.steer.unavailable': 'A direção está disponível apenas enquanto o agente está em execução', 'error.sessionInUse': 'Esta sessão já está em uso, possivelmente por outra instância DSH em execução (como dsh web ou aplicativo de desktop). Saia de outras instâncias DSH em execução e tente novamente.', - 'error.workspaceConnectFailed': 'Não foi possível abrir este espaço de trabalho: {message}', 'queue.editFailed': 'Falha na edição: esta mensagem pode já ter começado a ser enviada.', 'queue.removeFailed': 'Falha na remoção: esta mensagem pode já ter começado a ser enviada.', 'queue.steerFailed': 'A direção falhou. Tente novamente.', diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index b0907447c6..efbf311ef6 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import { useEffect, useId, useMemo, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -23,7 +24,7 @@ const QUEUE_TEXT_FACTS: Readonly> = { function textOf(content: InboxState['next-turn'][number]['content']): string | null { if (!content.every(block => block.type === 'text')) return null - return content.map(block => block.text).join('') + return extractTextContent(content) } /** Queue operations injected by the session-scoped registration. */ @@ -228,7 +229,7 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load )} {renderFactorySlot('conversation.user.text', { - text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''), + text: extractTextContent(row.content), facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, })} diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 27cae036db..e4eb324030 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -20,7 +20,7 @@ import type {} from '@deepseek-ai/dsh-client-file-upload/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { FileAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ComposerAttachment, ComposerFileAttachment, ComposerImageAttachment, DraftFileUpload, } from './contract/slots.ts' @@ -149,6 +149,9 @@ export class UnsupportedImageMediaTypeError extends Error { } } +/** Upload concurrency while the Host sends no limit; the value the Client used before the field moved to the Host. */ +const ABSENT_UPLOAD_LIMIT = 2 + /** Scope-addressed conversation service (root singleton, provided as `conversation`). */ export class ConversationController extends Service implements IConversation { /** The per-session input machine registry (SessionInputResolver face). */ @@ -158,6 +161,10 @@ export class ConversationController extends Service implements IConversation { /** Live upload state per draft that uploads when added: every file draft and every uploaded image draft. */ readonly fileUploads: SnapshotStore> = createSnapshotStore>({}) private readonly draftAttachments = new Map() + /** Draft attachment ids per owning Session; they outlive that Session's composer so a return re-adopts them. */ + private readonly sessionDraftIds = new Map>() + /** Reverse ownership lookup for release and Workspace rebinding. */ + private readonly draftAttachmentSession = new Map() private readonly fileUploadOperations = new Map @@ -168,7 +175,7 @@ export class ConversationController extends Service implements IConversation { readonly settle: () => void }> = [] private activeFileUploads = 0 - private readonly maxConcurrentFileUploads: number + private readonly maxConcurrentFileUploads: ObservableSnapshot /** * @param ctx - owning root context (the plugin apply context; the service @@ -180,12 +187,14 @@ export class ConversationController extends Service implements IConversation { constructor(ctx: Context, config: { input: SessionInputResolver blocks: ComposerBlocks - maxConcurrentFileUploads: number + /** Live upload concurrency limit, absent until the Host sends one; a raised limit starts queued uploads at once. */ + maxConcurrentFileUploads: ObservableSnapshot }) { super(ctx, 'conversation') this.input = config.input this.blocks = config.blocks this.maxConcurrentFileUploads = config.maxConcurrentFileUploads + ctx.effect(() => config.maxConcurrentFileUploads.subscribe(() => { this.pumpFileUploads() }), 'conversation: upload concurrency') ctx.effect(() => async () => { const operations = [...this.fileUploadOperations.values()] for (const operation of operations) operation.controller.abort() @@ -196,6 +205,8 @@ export class ConversationController extends Service implements IConversation { if (attachment.kind === 'image') revokePreview(attachment.previewUrl) } this.draftAttachments.clear() + this.sessionDraftIds.clear() + this.draftAttachmentSession.clear() this.fileUploads.set({}) }, 'conversation draft attachments') } @@ -279,6 +290,11 @@ export class ConversationController extends Service implements IConversation { ) // The composer owns the attachments until the Host accepts the prompt. const ownership = { accepted: false, retiredUnobserved: false } + // An accepted message's attachments leave the draft: a later composer must not re-adopt them, while + // the registry keeps them until the echo settles their previews or an unobserved retirement releases them. + const disownAccepted = (): void => { + for (const attachment of attachments) this.forgetDraftAttachment(attachment.id) + } const acceptance = Promise.withResolvers() const submission = session.beginSubmission({ mode, @@ -286,6 +302,7 @@ export class ConversationController extends Service implements IConversation { attachments: pendingAttachments, onAccept: () => { ownership.accepted = true + disownAccepted() accept?.() acceptance.resolve(undefined) }, @@ -309,6 +326,7 @@ export class ConversationController extends Service implements IConversation { const result = await Promise.race([session.prompt(content, mode, signal, submission.requestId), acceptance.promise]) if (result !== undefined && !result.ok) return { kind: 'error' } ownership.accepted = true + disownAccepted() // An accepted prompt whose echo already retired unobserved, as when its queue entry was removed. if (ownership.retiredUnobserved) this.releaseDraftAttachments(attachments) return { kind: 'success' } @@ -332,6 +350,7 @@ export class ConversationController extends Service implements IConversation { if (isImageMediaType(file.type)) { const attachment = browserDraftAttachment(file) this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) probeDimensions(attachment) if (uploadImages) this.beginFileUpload(sessionId, attachment) return attachment @@ -342,6 +361,7 @@ export class ConversationController extends Service implements IConversation { file, } this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) this.beginFileUpload(sessionId, attachment) return attachment }) @@ -369,6 +389,7 @@ export class ConversationController extends Service implements IConversation { for (const id of ids) { const attachment = this.draftAttachments.get(id) if (attachment === undefined) continue + this.ownDraftAttachment(sessionId, id) if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id) else this.beginFileUpload(sessionId, attachment) } @@ -442,7 +463,7 @@ export class ConversationController extends Service implements IConversation { /** Start queued upload Workers until the configured concurrency is occupied. */ private pumpFileUploads(): void { - while (this.activeFileUploads < this.maxConcurrentFileUploads) { + while (this.activeFileUploads < (this.maxConcurrentFileUploads.getSnapshot() ?? ABSENT_UPLOAD_LIMIT)) { const task = this.fileUploadQueue.shift() if (task === undefined) return this.activeFileUploads += 1 @@ -504,11 +525,59 @@ export class ConversationController extends Service implements IConversation { const attachment = this.draftAttachments.get(id) if (attachment === undefined) return this.draftAttachments.delete(id) + this.forgetDraftAttachment(id) if (attachment.kind === 'image') revokePreview(attachment.previewUrl) // The stored Host object stays durable; only the draft's upload state ends. this.dropUpload(id) } + /** + * Draft attachment ids a Session still owns after its composer retired. + * @param sessionId - owning Session identity. + * @returns registered ids in registration order. + */ + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] { + return [...this.sessionDraftIds.get(sessionId) ?? []] + } + + /** + * Sessions that still own registered draft attachments. + * @returns Session identities with at least one registered attachment. + */ + draftAttachmentSessions(): readonly SessionId[] { + return [...this.sessionDraftIds.keys()] + } + + /** + * Release every draft attachment one removed Session owns. + * @param sessionId - removed Session identity. + */ + releaseDraftSession(sessionId: SessionId): void { + for (const id of this.draftAttachmentIds(sessionId)) this.releaseDraftAttachment(id) + } + + /** Record, or move after a Workspace rebind, one draft attachment's owning Session. */ + private ownDraftAttachment(sessionId: SessionId, id: DraftAttachmentId): void { + this.forgetDraftAttachment(id) + this.draftAttachmentSession.set(id, sessionId) + let ids = this.sessionDraftIds.get(sessionId) + if (ids === undefined) { + ids = new Set() + this.sessionDraftIds.set(sessionId, ids) + } + ids.add(id) + } + + /** Forget one draft attachment's owning Session. */ + private forgetDraftAttachment(id: DraftAttachmentId): void { + const sessionId = this.draftAttachmentSession.get(id) + if (sessionId === undefined) return + this.draftAttachmentSession.delete(id) + const ids = this.sessionDraftIds.get(sessionId) + ids?.delete(id) + if (ids?.size === 0) this.sessionDraftIds.delete(sessionId) + } + /** Abort one draft's active upload and drop its upload state. */ private dropUpload(id: DraftAttachmentId): void { const operation = this.fileUploadOperations.get(id) @@ -605,6 +674,7 @@ export class ConversationController extends Service implements IConversation { continue } this.draftAttachments.delete(attachment.id) + this.forgetDraftAttachment(attachment.id) this.forgetUpload(attachment.id) if (ref !== undefined && 'mediaType' in ref && uiConversation?.seedImageUrl(sessionId, ref, attachment.previewUrl) === true) continue diff --git a/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css b/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css index 6d50c03311..1071b79956 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css @@ -17,7 +17,8 @@ background: transparent; color: var(--dsw-alias-label-tertiary); font-family: inherit; - font-size: var(--dsh-content-font-size-secondary, 13px); + font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px); + font-weight: 400; font-variant-numeric: tabular-nums; line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px)); white-space: nowrap; diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 236c1761cf..17ab15294e 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -1,6 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' -import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import { workspaceDisplayTitle } from '@deepseek-ai/dsh-api-workspace-controller/default-workspace' import type { ConversationContentProps, ConversationViewsProps, InputZone } from '../contract/slots.ts' @@ -24,7 +23,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, t, useFactorySlot, + moveDraft, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -41,15 +40,6 @@ export function ConversationContent(props: ConversationContentProps) { const [pickerOpen, setPickerOpen] = useState(false) const [pendingWorkspaceId, setPendingWorkspaceId] = useState() - // An embedded pick is handed to its owner only while it is the latest pick of a mounted occurrence. The content - // remounts for another Session, so a mounted occurrence still shows the Session the pick started from. - const mounted = useRef(false) - const pickSeq = useRef(0) - useEffect(() => { - mounted.current = true - return () => { mounted.current = false } - }, []) - const [pickFailure, setPickFailure] = useState<{ readonly seq: number; readonly text: string } | null>(null) const pickerAnchor = useRef(null) // Publishes the two live measurements floating View chrome reads off the @@ -133,19 +123,8 @@ export function ConversationContent(props: ConversationContentProps) { onPick: (workspaceId) => { setPickerOpen(false) setPendingWorkspaceId(workspaceId) - const handOver = props.onWorkspaceSession - pickSeq.current += 1 - const seq = pickSeq.current - const latest = (): boolean => mounted.current && seq === pickSeq.current - void selectWorkspace(workspaceId, handOver === undefined ? undefined : (nextId) => { - if (!latest()) return false - handOver(nextId) - return true - }).catch((error: unknown) => { + void props.onWorkspaceSelected(workspaceId, moveDraft).catch(() => { setPendingWorkspaceId(current => current === workspaceId ? undefined : current) - // Workspace navigation reports a failed pick of the main occurrence; an embedded one reports its own. - if (handOver === undefined || !latest()) return - setPickFailure({ seq, text: t('error.workspaceConnectFailed', { message: error instanceof Error ? error.message : String(error) }) }) }) }, onClose: () => { setPickerOpen(false) }, @@ -185,10 +164,6 @@ export function ConversationContent(props: ConversationContentProps) { const composerBar = (
- {pickFailure !== null && ( - } anchor={body} - onDone={() => { setPickFailure(null) }} /> - )} {hero && } {hero && heroWorkspaceRow} {zone !== undefined && renderSlot('conversation.input.dock', zone)} diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx index dc82d99775..ef0f2ad583 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx @@ -11,7 +11,7 @@ const CONTENT_SLOTS = { widthControls: ConversationWidthControls } * @returns the unchanged root, Header, content, and width-control subtree. */ export function ConversationMainPanel(props: ConversationSlotProps) { - const { sessionId, useSession, useSessions, useConversation, renderSlot, renderFactorySlot } = props + const { sessionId, useSession, useSessions, useConversation, renderSlot, renderFactorySlot, openWorkspace } = props const session = useSession(s => s) const conversation = useConversation(s => s) const shellPhase = session === undefined || conversation === undefined @@ -41,6 +41,7 @@ export function ConversationMainPanel(props: ConversationSlotProps) { variant: 'main', phase, hero, + onWorkspaceSelected: openWorkspace, }, { slots: CONTENT_SLOTS, })} diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css index 39d6f62fef..7f69a48eb0 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css @@ -467,7 +467,7 @@ preference; embedded occurrences override this adaptive axis below. */ --dsh-chat-content-width: var( --dsh-chat-user-width, - clamp(680px, calc(var(--dsh-conversation-column-width, 0px) * 0.64), 920px) + clamp(680px, calc(var(--dsh-conversation-column-width, 0px) * 0.64), 880px) ); --dsh-composer-card-max-width: calc(var(--dsh-chat-content-width) + 32px); --dsh-composer-side-clearance: 16px; @@ -476,8 +476,8 @@ .embeddedBody { overflow: hidden; - --dsh-chat-content-width: min(calc(100% - 32px), 920px); - --dsh-composer-card-max-width: min(calc(100% - 16px), 952px); + --dsh-chat-content-width: min(calc(100% - 32px), 880px); + --dsh-composer-card-max-width: min(calc(100% - 16px), 912px); --dsh-composer-side-clearance: 8px; --dsh-composer-dock-inset: 8px; } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx index 53f42c199f..ab38156233 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx @@ -24,7 +24,7 @@ function readWidthPreference(): number | null { function resolveContentWidth(columnWidth: number, preference: number | null): number { const max = Math.max(CONTENT_MIN, columnWidth - CONTENT_EDGE_BUDGET) if (preference !== null) return Math.min(Math.max(preference, CONTENT_MIN), max) - return Math.max(680, Math.min(columnWidth * 0.64, 920)) + return Math.max(680, Math.min(columnWidth * 0.64, 880)) } /** Convert a wheel event's vertical delta to scrollport pixels. */ diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css index 04c44e252f..fc64245a0a 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css @@ -276,10 +276,7 @@ align-items: center; justify-content: space-between; gap: 12px; - /* 2px moved from the bottom pad to the top: the whole control row sits 2px - lower in the card (it read too high against the textarea) while the - controls' own centering stays untouched. */ - padding: 2px 8px 6px; + padding: 4px 8px 8px; min-width: 0; /* Size container so the chips inside can collapse to icon-only when the card runs out of row width (PermissionSelect @container rule). Anonymous @@ -332,13 +329,13 @@ } } -/* Attach circle (figma + control): 28px, selector fill, primary glyph. */ +/* The attachment and send controls share a diameter and vertical center. */ .add { display: grid; place-items: center; flex: none; - width: 28px; - height: 28px; + width: 32px; + height: 32px; border: none; border-radius: 999px; corner-shape: round; @@ -392,15 +389,13 @@ cursor: default; } -/* Primary send (figma IconButton 34:10465): 34px circle, #3964FE light / - #679EFE dark — the info-fill pair (500→400), NOT button-primary (ink); - white glyph; empty text = 0.4 opacity. */ +/* The send control keeps its semantic primary fill in both palettes. */ .primary { display: grid; place-items: center; flex: none; - width: 34px; - height: 34px; + width: 32px; + height: 32px; border: none; border-radius: 999px; corner-shape: round; @@ -410,10 +405,6 @@ color: var(--dsw-alias-label-on-color); cursor: pointer; transition: background-color 100ms ease; - /* Opts out of the row's 2px downward shift (.row top pad): the send circle - keeps its original seat while the smaller chips sit lower. Transform, not - margin, so flex centering math is untouched. */ - transform: translateY(-2px); } /* Solid artwork uses a smaller footprint than the thin send arrow. */ diff --git a/packages/client/ui-conversation/src/client/skeleton/TodoPanel.module.css b/packages/client/ui-conversation/src/client/skeleton/TodoPanel.module.css index 04b537dad1..46b5826c81 100644 --- a/packages/client/ui-conversation/src/client/skeleton/TodoPanel.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/TodoPanel.module.css @@ -52,6 +52,8 @@ } .lead { + width: 16px; + height: 16px; display: grid; flex: none; place-items: center; diff --git a/packages/client/ui-conversation/src/index.ts b/packages/client/ui-conversation/src/index.ts index 90c4366a1a..23b557467b 100644 --- a/packages/client/ui-conversation/src/index.ts +++ b/packages/client/ui-conversation/src/index.ts @@ -1,9 +1,9 @@ /** Browser conversation preferences. */ import type {} from '@deepseek-ai/dsh-settings' -import type { Volatile, Context } from '@deepseek-ai/cordis' -import type { BusyEnterBehavior } from './submission-settings.ts' +import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' +import type { ConversationConfig } from './types.ts' import { BUSY_ENTER_FIELD } from './submission-settings.ts' import { ConversationSettingsFields } from './submission-settings.ts' @@ -13,15 +13,13 @@ export { DEFAULT_BUSY_ENTER_BEHAVIOR, type BusyEnterBehavior, type ConversationSettings, } from './submission-settings.ts' -/** Runtime preferences projected to the browser. */ -export interface Config { - /** Enter key behavior while a turn is running. */ - busyEnter: Volatile -} +/** Live preferences; the browser receives every field through its synced Config. */ +export type Config = ConversationConfig /** Live preferences projected to the browser. */ export const Config = z.object({ [BUSY_ENTER_FIELD]: ConversationSettingsFields[BUSY_ENTER_FIELD].volatile(), + maxConcurrentFileUploads: z.natural().min(1).default(2).volatile(), }) /** Register browser conversation preferences. diff --git a/packages/client/ui-conversation/src/types.ts b/packages/client/ui-conversation/src/types.ts new file mode 100644 index 0000000000..e7138d1959 --- /dev/null +++ b/packages/client/ui-conversation/src/types.ts @@ -0,0 +1,11 @@ +/** Conversation plugin configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' +import type { BusyEnterBehavior } from './submission-settings.ts' + +/** Live preferences; the browser receives every field through its synced Config. */ +export interface ConversationConfig { + /** Enter key behavior while a turn is running. */ + busyEnter: Volatile + /** Maximum generic-file uploads allowed to run concurrently in browser Workers. */ + maxConcurrentFileUploads: Volatile +} diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index b230602a57..5c11102f96 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { render, cleanup } from '@testing-library/react' import { $getRoot, $isTextNode, PASTE_COMMAND } from 'lexical' @@ -17,7 +18,7 @@ import { } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionBehaviorOverrides } from '@deepseek-ai/dsh-client-test-runtime' import { - apply, inject, type ComposerBarInjected, type ConversationInjected, + apply, inject, type ComposerBarInjected, type ConversationInjected, type ConversationShellInjected, type ConversationSessionHeaderInjected, type ConversationSessionInjected, type ViewTab, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -96,7 +97,6 @@ async function bench(renderQuote = false) { const id = await connectWorkspace() replaceMain(id, beforeOpen) }, - connectWorkspace: async () => await connectWorkspace(), openSession, } as never) const sessionFake = sessionFakeFor() @@ -111,7 +111,7 @@ async function bench(renderQuote = false) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'quote-probe': { kind: 'single', scope: 'session' }, @@ -121,7 +121,7 @@ async function bench(renderQuote = false) { ) : null) - const feature = await runtime.mount({ inject: [...inject], apply }) + const feature = await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) if (renderQuote) await runtime.mount(messageQuotes) runtime.renderRoot() const entryOf = (key: 'main.conversation' | 'conversation.session' | 'conversation.session.header' | 'conversation.composer.bar') => @@ -141,6 +141,11 @@ async function bench(renderQuote = false) { sessionId: SessionId | undefined, ) => ConversationInjected)(id) } + /** Pick a Workspace as the main occurrence does: the shell opens it and adopts the draft of the Session shown. */ + const selectWorkspace = (id: SessionId | undefined, workspaceId: WorkspaceId): Promise => { + const shell = runtime.slots.spec('main.conversation') as { inject: ConversationShellInjected } + return shell.inject.openWorkspace(workspaceId, residentApi(id).moveDraft) + } const headerApi = (id: SessionId) => { const entry = entryOf('conversation.session.header') const instance = runtime.storeOf('conversation.session.header', references.get(id)) as ConversationInstance @@ -161,7 +166,7 @@ async function bench(renderQuote = false) { const viewSource = (id: SessionId): ObservableSnapshot => conversationApi(id).injected.hooks.conversationViews return { - runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, + runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, selectWorkspace, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, } } @@ -666,7 +671,6 @@ describe('Conversation inject API', () => { it('moves a draft only when Workspace navigation changes Session', async () => { const b = await bench() - const resident = b.residentApi(ROOT) const { state, actions } = b.inputApi(ROOT) actions.setDraft('carry me') expect(b.composerApi(ROOT).addFiles?.([ @@ -675,7 +679,7 @@ describe('Conversation inject API', () => { await vi.waitFor(() => { expect(b.rootUpload).toHaveBeenCalledOnce() }) b.connectWorkspace.mockResolvedValueOnce(ROOT) - await resident.selectWorkspace('workspace-1' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-1' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(ROOT) expect(state.getSnapshot().draft).toBe('carry me') @@ -690,7 +694,7 @@ describe('Conversation inject API', () => { b.uploads.set(other, targetUpload) await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await resident.selectWorkspace('workspace-2' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-2' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(other) expect(state.getSnapshot().draft).toBe('') expect(b.inputApi(other).state.getSnapshot().draft).toBe('carry me') @@ -699,98 +703,6 @@ describe('Conversation inject API', () => { await b.runtime.dispose() }) - it('reports the blank of a picked Workspace to an embedding owner, which retains it, and moves the draft without opening it', async () => { - const b = await bench() - const resident = b.residentApi(ROOT) - b.inputApi(ROOT).actions.setDraft('review this') - const other = 'other-2' as SessionId - await b.runtime.sessions.add({ id: other, session: {} }) - b.connectWorkspace.mockResolvedValueOnce(other) - const held: SessionReference[] = [] - const report = vi.fn((id: SessionId) => { - held.push(b.runtime.sessions.retain(id, { source: 'mainView' })) - return true - }) - await resident.selectWorkspace('workspace-3' as WorkspaceId, report) - expect(report).toHaveBeenCalledWith(other) - expect(b.opened).not.toHaveBeenCalledWith(other) - expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('') - expect(b.inputApi(other).state.getSnapshot().draft).toBe('review this') - for (const reference of held) reference.release() - await b.runtime.dispose() - }) - - it('moves the draft although the owner releases the Session it showed before while it takes the picked blank', async () => { - const b = await bench() - const source = 'handover-source' as SessionId - const target = 'handover-target' as SessionId - await b.runtime.sessions.add({ id: source, session: {} }) - await b.runtime.sessions.add({ id: target, session: {} }) - const shown = b.runtime.sessions.retain(source, { source: 'mainView' }) - b.inputApi(source).actions.setDraft('carry over') - b.connectWorkspace.mockResolvedValueOnce(target) - const taken: SessionReference[] = [] - await b.residentApi(source).selectWorkspace('workspace-5' as WorkspaceId, (id) => { - taken.push(b.runtime.sessions.retain(id, { source: 'mainView' })) - shown.release() - return true - }) - expect(b.inputApi(target).state.getSnapshot().draft).toBe('carry over') - // The handover's own hold on the source ended with it. - expect(b.runtime.sessions.binding(source)).toBeUndefined() - for (const reference of taken) reference.release() - await b.runtime.dispose() - }) - - it('changes nothing when the owner declines the picked blank', async () => { - const b = await bench() - b.inputApi(ROOT).actions.setDraft('stay here') - const other = 'declined-target' as SessionId - await b.runtime.sessions.add({ id: other, session: {} }) - b.connectWorkspace.mockResolvedValueOnce(other) - const report = vi.fn((_id: SessionId) => false) - await b.residentApi(ROOT).selectWorkspace('workspace-6' as WorkspaceId, report) - expect(report).toHaveBeenCalledWith(other) - expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('stay here') - expect(b.runtime.sessions.binding(other)).toBeUndefined() - expect(b.opened).not.toHaveBeenCalledWith(other) - await b.runtime.dispose() - }) - - it('offers the picked blank without retaining a source when no Session, or one no longer retained, started the pick', async () => { - const b = await bench() - const gone = 'released-source' as SessionId - const other = 'late-target' as SessionId - await b.runtime.sessions.add({ id: gone, session: {} }) - await b.runtime.sessions.add({ id: other, session: {} }) - b.connectWorkspace.mockResolvedValue(other) - const declined = vi.fn((_id: SessionId) => false) - await b.residentApi(gone).selectWorkspace('workspace-7' as WorkspaceId, declined) - expect(declined).toHaveBeenCalledWith(other) - expect(b.runtime.sessions.binding(gone)).toBeUndefined() - - const taken: SessionReference[] = [] - await b.residentApi(undefined).selectWorkspace('workspace-7' as WorkspaceId, (id) => { - taken.push(b.runtime.sessions.retain(id, { source: 'mainView' })) - return true - }) - expect(taken.map(reference => reference.sessionId)).toEqual([other]) - expect(b.opened).not.toHaveBeenCalledWith(other) - for (const reference of taken) reference.release() - await b.runtime.dispose() - }) - - it('rejects an embedded pick whose Workspace cannot connect without offering a Session', async () => { - const b = await bench() - b.inputApi(ROOT).actions.setDraft('kept') - b.connectWorkspace.mockRejectedValueOnce(new Error('preset missing')) - const report = vi.fn((_id: SessionId) => true) - await expect(b.residentApi(ROOT).selectWorkspace('workspace-8' as WorkspaceId, report)).rejects.toThrow('preset missing') - expect(report).not.toHaveBeenCalled() - expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('kept') - await b.runtime.dispose() - }) - it('leaves a draft whose message is still being sent with its Session', async () => { const b = await bench() const pending = Promise.withResolvers>>() @@ -803,7 +715,7 @@ describe('Conversation inject API', () => { const other = 'sending-target' as SessionId await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await b.residentApi(ROOT).selectWorkspace('workspace-sending' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-sending' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(other) expect(b.inputApi(other).state.getSnapshot().draft).toBe('') expect(state.getSnapshot().draft).toBe('in flight') @@ -824,7 +736,7 @@ describe('Conversation inject API', () => { const other = 'structured-target' as SessionId await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await b.residentApi(ROOT).selectWorkspace('workspace-structured' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-structured' as WorkspaceId) expect(b.inputApi(other).state.getSnapshot().draft).toBe(draft.text) expect(b.inputApi(other).state.getSnapshot().occurrences).toMatchObject(draft.references) expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('') @@ -835,12 +747,12 @@ describe('Conversation inject API', () => { it('supports no-Session navigation and propagates Workspace connection failure', async () => { const b = await bench() b.connectWorkspace.mockResolvedValueOnce(ROOT) - await b.residentApi(undefined).selectWorkspace('workspace-0' as WorkspaceId) + await b.selectWorkspace(undefined, 'workspace-0' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(ROOT) const opens = b.opened.mock.calls.length b.connectWorkspace.mockRejectedValueOnce(new Error('offline')) - await expect(b.residentApi(ROOT).selectWorkspace('workspace-4' as WorkspaceId)) + await expect(b.selectWorkspace(ROOT, 'workspace-4' as WorkspaceId)) .rejects.toThrow('offline') expect(b.opened).toHaveBeenCalledTimes(opens) await b.runtime.dispose() diff --git a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx index 154d31ec9f..5a0adbffb0 100644 --- a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { describe, expect, it, vi } from 'vitest' import { @@ -7,7 +8,7 @@ import { import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { apply, inject, type ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { apply, inject, type ConversationShellInjected, type ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' usePinnedBrowserLanguages('zh-CN') @@ -27,14 +28,14 @@ async function bench(options: { declareConversation?: boolean } = {}) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) if (options.declareConversation !== false) { await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'settings.general.item': { kind: 'list', scope: 'root' }, }, (_props: { renderSlot?: unknown }) => null) } - const feature = await runtime.mount({ inject: [...inject], apply }) + const feature = await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) if (options.declareConversation !== false) runtime.renderRoot() return { runtime, feature, developerTools } } @@ -102,8 +103,9 @@ describe('target-neutral Conversation apply wiring', () => { b.runtime.renderRoot() expect(b.runtime.slots.entries('main').map(row => row.options.key)).toEqual(['conversation']) expect(b.runtime.slots.entries('main.conversation')).toHaveLength(1) - expect(b.runtime.slots.spec('main.conversation')) - .toEqual({ kind: 'single', scope: 'session-maybe' }) + const shell = b.runtime.slots.spec('main.conversation') as { inject: ConversationShellInjected } + expect(shell.inject.openWorkspace).toBeTypeOf('function') + expect(shell).toEqual({ kind: 'single', scope: 'session-maybe', inject: shell.inject }) expect(b.runtime.factoryOf('conversation.content').slots) .toMatchObject({ views: { scope: 'session' } }) expect(b.runtime.slots.entries('conversation.session')).toHaveLength(1) diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index c8e96efdbc..b2506a1eab 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Conversation assembly acceptance independent of Tool presentation. */ import './control-row-dom.ts' @@ -88,7 +89,7 @@ async function bench(opts?: { blank?: boolean }) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/proj' }, @@ -100,7 +101,7 @@ async function bench(opts?: { blank?: boolean }) { }) openSession(SID) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) return runtime } @@ -113,9 +114,9 @@ describe('resident composer', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) runtime.slots.register({ name: 'conversation.hero.workspace' }, WorkspaceProbe) const view = runtime.renderRoot() const textarea = view.container.querySelector('[data-composer-input]') @@ -142,12 +143,12 @@ describe('resident composer', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.workspaces.update((draft) => { draft.items = [{ workspaceId: 'w1', title: 'Proj', path: '/proj', sessionIds: [SID] }] as never }) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) runtime.slots.register({ name: 'conversation.hero.workspace' }, WorkspaceProbe) const view = runtime.renderRoot() @@ -211,7 +212,7 @@ describe('prompt rejection through the assembled composer', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) const prompt = vi.fn(async () => ({ ok: false, error: new RemoteError('session/agent-busy', 'prompt rejected before acceptance', { reason: 'busy' }), @@ -223,7 +224,7 @@ describe('prompt rejection through the assembled composer', () => { }) openSession(SID) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const view = runtime.renderRoot() const composer = view.container.querySelector('[data-composer-input]')! diff --git a/packages/client/ui-conversation/tests/config.host.spec.ts b/packages/client/ui-conversation/tests/config.host.spec.ts index 25420eff00..5eb8088838 100644 --- a/packages/client/ui-conversation/tests/config.host.spec.ts +++ b/packages/client/ui-conversation/tests/config.host.spec.ts @@ -18,9 +18,11 @@ describe('ui-conversation host', () => { await ctx.plugin(SessionProjectionRegistry) const configuration = await liveConfig(ctx, HostPlugin) const { fiber } = configuration - expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ + busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR, maxConcurrentFileUploads: 2, + }) await configuration.update({ busyEnter: 'steer' }) - expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer', maxConcurrentFileUploads: 2 }) await expect(configuration.update({ busyEnter: 'invalid' })).rejects.toThrow() await fiber.dispose() }) diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts new file mode 100644 index 0000000000..df098003bb --- /dev/null +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -0,0 +1,313 @@ +// @vitest-environment jsdom +// Draft attachments outlive their Session's composer: a switch keeps them registered, +// a removed Session releases them, and a page unload reports what it discarded. +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { brandString } from '@deepseek-ai/dsh-brand' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { FileUploadValue } from '@deepseek-ai/dsh-client-file-upload/client' +import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ComposerBlockRegistry } from '../src/client/input/blocks.ts' +import { InputHub } from '../src/client/input/hub.ts' +import { ConversationController } from '../src/client/service.ts' +import { zh } from '../src/client/locales.ts' + +const SESSION = 's1' +const UNLOAD_MARK = `dsh.composer-draft-attachments-unloaded.${SESSION}` + +function sessionId(): SessionId { + return brandString(SESSION) +} + +function uploadValue(name: string): FileUploadValue { + return { + receiptId: brandString(`receipt-${name}`), + file: { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), name, bytes: 3 }, + } +} + +interface UploadBehavior { + uploadFile?: (...input: unknown[]) => Promise +} + +/** One retained Session with the production Conversation service and its input hub. */ +async function bench(prepare?: () => void) { + const runtime = await SlotTestRuntime.create() + const upload = vi.fn((id: SessionId, ...args: unknown[]) => { + const behavior = runtime.sessions.behavior(id) as UploadBehavior + if (behavior.uploadFile === undefined) throw new Error('test file upload has no Session override') + return behavior.uploadFile(...args) + }) + runtime.fileUpload.upload = upload + runtime.fileUpload.uploadImage = vi.fn(() => Promise.resolve({ ok: true as const, value: { + receiptId: brandString('receipt-image'), + image: { attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 }, + } })) + await runtime.sessions.add({ + id: SESSION, + session: { + prompt: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + updateQueue: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + cancel: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + loadOlder: vi.fn(() => Promise.resolve()), + }, + }) + prepare?.() + let reference = runtime.sessions.retain(sessionId()) + await reference.ready + const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) + await runtime.ctx.plugin(ConversationController, { + input: hub, + blocks: new ComposerBlockRegistry(), + maxConcurrentFileUploads: createSnapshotStore(2), + }).await() + const root = runtime.ctx.get('conversation') as ConversationController + const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) + const shell = shellNow() + const behavior = () => runtime.sessions.behavior(SESSION) as UploadBehavior + /** Retire the Session's composer, as a switch to another Session does. */ + const switchAway = async (): Promise => { + reference.release() + await runtime.flush() + expect(runtime.sessions.binding(SESSION)).toBeUndefined() + } + /** Mount a fresh composer for the Session again. */ + const switchBack = async () => { + reference = runtime.sessions.retain(sessionId()) + await reference.ready + return shellNow() + } + return { runtime, hub, root, shell, upload, behavior, switchAway, switchBack } +} + +function draftFile(name = 'notes.txt'): File { + return new File([new Uint8Array([1, 2, 3])], name, { type: 'text/plain' }) +} + +beforeEach(() => { localStorage.clear() }) +afterEach(() => { vi.restoreAllMocks() }) + +describe('draft attachments across a Session switch', () => { + it('re-adopts settled files and images without uploading them again', async () => { + const b = await bench() + const revoked = vi.spyOn(URL, 'revokeObjectURL') + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const drafts = b.root.createDrafts(sessionId(), [draftFile(), new File([Uint8Array.of(9)], 'pic.png', { type: 'image/png' })], true) + expect(b.shell.addAttachments(drafts.map(draft => draft.id))).toBe(true) + await vi.waitFor(() => { + for (const draft of drafts) expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') + }) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual(drafts.map(draft => draft.id)) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual(drafts.map(draft => draft.id)) + expect(b.root.resolveDraftAttachments(back.snapshot.attachmentIds)).toEqual(drafts) + expect(b.upload).toHaveBeenCalledOnce() + expect(revoked).not.toHaveBeenCalled() + expect(back.notices.getSnapshot()).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps an upload running while the Session is switched away', async () => { + const b = await bench() + try { + let finish!: (value: unknown) => void + b.behavior().uploadFile = vi.fn((...args: unknown[]) => new Promise((resolve) => { + finish = resolve + ;(args[2] as AbortSignal).addEventListener('abort', () => { resolve({ ok: false, error: new Error('aborted') }) }) + })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('uploading') }) + await b.switchAway() + finish({ ok: true, value: uploadValue('big.bin') }) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(b.upload).toHaveBeenCalledOnce() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps a failed upload so it can be retried in place after returning', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.reject(new Error('network lost'))) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('error') }) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('big.bin') })) + b.root.retryFileUpload(sessionId(), draft.id) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('removed Sessions', () => { + it('releases the draft attachments of a Session removed while no composer is mounted', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.switchAway() + localStorage.setItem(UNLOAD_MARK, '1') + await b.runtime.sessions.remove(SESSION) + await vi.waitFor(() => { expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) }) + expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('releases the draft attachments when the mounted composer of a removed Session retires', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.runtime.sessions.remove(SESSION) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('page unload report', () => { + it('marks Sessions whose attachments an unload discards, and reports them on the next page', async () => { + const first = await bench() + try { + first.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = first.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + first.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + } finally { + await first.runtime.dispose() + } + // A reload starts with an empty registry; the saved mark survives in browser storage. + const second = await bench(() => { localStorage.setItem(UNLOAD_MARK, '1') }) + try { + expect(second.shell.notices.getSnapshot()).toMatchObject({ level: 'error', text: zh['attachments.unavailable'] }) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await second.runtime.dispose() + } + }) + + it('does not report attachments a switch kept, and drops marks a back-forward restore made stale', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + const restore = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(restore, 'persisted', { value: false }) + window.dispatchEvent(restore) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + const cached = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(cached, 'persisted', { value: true }) + window.dispatchEvent(cached) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + localStorage.setItem(UNLOAD_MARK, '1') + await b.switchAway() + const back = await b.switchBack() + expect(back.notices.getSnapshot()).toBeNull() + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps working when browser storage refuses the marks', async () => { + const b = await bench() + const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + window.dispatchEvent(new Event('pagehide')) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(errors).toHaveBeenCalledTimes(2) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('submitted attachments', () => { + it('does not re-adopt or report attachments of an accepted message whose echo has not retired', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + b.shell.setDraft('send with file') + b.shell.submit('queue', 'click') + await vi.waitFor(() => { expect(b.shell.snapshot.phase).toBe('plain') }) + await b.runtime.flush() + // The registry still holds the attachment for the echo; the draft no longer owns it. + expect(b.root.resolveDraftAttachments([draft.id])).toHaveLength(1) + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + expect(b.root.draftAttachmentSessions()).toEqual([]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) + + it('keeps the attachments of a slash line whose adjudication a switch aborted', async () => { + const adjudicate = vi.fn(() => new Promise(() => undefined)) + const b = await bench() + try { + const lexicon = { getSnapshot: () => new Map<'/' | '@', readonly string[]>(), subscribe: () => () => undefined } + const triggers = { adjudicate, lexicon, track: vi.fn() } + b.runtime.ctx.provide('inputTriggers', { sessionOf: () => triggers } as never) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + b.shell.setDraft('/review this file') + b.shell.submit('queue', 'enter') + expect(b.shell.snapshot.phase).toBe('adjudicating') + expect(adjudicate).toHaveBeenCalledOnce() + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([draft.id]) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + } finally { + await b.runtime.dispose() + } + }) +}) diff --git a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx index 8582f67e55..2235dae9bb 100644 --- a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { fireEvent, render } from '@testing-library/react' import type { Context } from '@deepseek-ai/cordis' +import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts' import { KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, REDO_COMMAND, UNDO_COMMAND, $getRoot, $getSelection, $isRangeSelection, $nodesOfType, @@ -16,7 +17,7 @@ import { $selectDetectSpan } from '../src/client/input/editor/span-map.ts' const quote = 'selected source text' -function bench(quoteInsertionAllowed?: () => boolean) { +function bench(composerBlock?: () => ComposerBlock | undefined) { const sink = vi.fn(() => Promise.resolve({ kind: 'success' })) const shell = new SessionInputShell({ actx: {} as Context, @@ -27,7 +28,7 @@ function bench(quoteInsertionAllowed?: () => boolean) { unsupportedNotice: () => 'unsupported', }, quoteRemoveLabel: () => 'Remove quote', - ...(quoteInsertionAllowed === undefined ? {} : { quoteInsertionAllowed }), + ...(composerBlock === undefined ? {} : { composerBlock }), }) return { shell, sink } } @@ -38,13 +39,13 @@ function quoteKeys(shell: SessionInputShell): string[] { describe('QuoteNode composer lifecycle', () => { it('preserves the draft when its Session cannot accept an inserted quote', () => { - let allowed = false - const { shell } = bench(() => allowed) + let block: ComposerBlock | undefined = { reason: 'Unavailable' } + const { shell } = bench(() => block) shell.setDraft('base ') const before = shell.draftSnapshot expect(shell.insertQuote(quote)).toBe(false) expect(shell.draftSnapshot).toBe(before) - allowed = true + block = undefined expect(shell.insertQuote(quote)).toBe(true) }) diff --git a/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts new file mode 100644 index 0000000000..c35507a9d5 --- /dev/null +++ b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts @@ -0,0 +1,83 @@ +// @vitest-environment jsdom +/** Reference insertion from outside the composer follows Session, submission, and disposal state. */ +import { expect, it, onTestFinished, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts' +import type { ReferenceInsert } from '../src/client/contract/draft-editor.ts' +import type { SubmitOutcome } from '../src/client/contract/input.ts' +import { SessionInputShell } from '../src/client/input/facade.ts' + +const reference: ReferenceInsert = { + source: 'reference', ref: '@"/work/a b.md"', label: 'a b.md', appearance: 'file', clipboardText: '@"/work/a b.md"', +} + +type SessionGate = Pick + +function bench() { + const pending = Promise.withResolvers() + const sink = vi.fn(() => pending.promise) + const sources: { session: SessionGate; block: ComposerBlock | undefined } = { + session: { removed: false, subagent: null }, block: undefined, + } + const shell = new SessionInputShell({ + actx: {} as Context, + defaultSink: sink, + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, + session: () => sources.session, + composerBlock: () => sources.block, + }) + onTestFinished(() => { shell.dispose() }) + return { shell, sink, pending, sources } +} + +const child = (mode: 'one-shot' | 'continuable'): SessionGate['subagent'] => ({ + address: { parentSessionId: 'parent' as SessionId, childSessionId: 'child' as SessionId, mode }, +}) + +it('inserts references without attachments and refuses while a submission owns the draft', async () => { + const { shell, pending } = bench() + expect(shell.canInsertReferences()).toBe(true) + shell.setDraft('Review') + expect(shell.addReferences([reference])).toBe(true) + expect(shell.snapshot.draft).toBe('Review @"/work/a b.md" ') + expect(shell.snapshot.attachmentIds).toEqual([]) + shell.submit() + expect(shell.canInsertReferences()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) + pending.resolve({ kind: 'success' }) + await vi.waitFor(() => { expect(shell.canInsertReferences()).toBe(true) }) +}) + +it('reads Session removal, subagent mode, and composer blocks at each call', () => { + const { shell, sources } = bench() + sources.session = { removed: true, subagent: null } + expect(shell.canInsertReferences()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) + expect(shell.snapshot.draft).toBe('') + sources.session = { removed: false, subagent: child('one-shot') } + expect(shell.canInsertReferences()).toBe(false) + sources.session = { removed: false, subagent: child('continuable') } + expect(shell.canInsertReferences()).toBe(true) + sources.block = { reason: 'Unavailable' } + expect(shell.canInsertReferences()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) + sources.block = undefined + expect(shell.addReferences([reference])).toBe(true) +}) + +it('refuses after disposal and permits insertion without Session sources', () => { + const { shell } = bench() + shell.dispose() + expect(shell.canInsertReferences()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) + const bare = new SessionInputShell({ + actx: {} as Context, + defaultSink: async () => ({ kind: 'success' }), + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, + }) + onTestFinished(() => { bare.dispose() }) + expect(bare.canInsertReferences()).toBe(true) + expect(bare.addReferences([reference])).toBe(true) +}) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index e29bf0a8e0..51f14c108a 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -3,6 +3,7 @@ // TestSessions mints tagged scopes through the production createScope, so the // service's scopeOf/binding path runs against production resolution (no local // tag probe). +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { UserMessage } from '@deepseek-ai/dsh-llm/types' import type { MessageId } from '@deepseek-ai/dsh-llm/types' import { Context } from '@deepseek-ai/cordis' @@ -31,7 +32,7 @@ const UPLOAD_IMAGES = true /** `createDrafts` mode of a draft whose images travel inline, as a subagent continuation's do. */ const INLINE_IMAGES = false -async function bench(maxConcurrentFileUploads = 2) { +async function bench(maxConcurrentFileUploads: number | 'absent' = 2) { const runtime = await SlotTestRuntime.create() runtime.fileUpload.upload = (sessionId: SessionId, ...args: unknown[]) => { const session = runtime.sessions.behavior(sessionId) as { @@ -62,16 +63,17 @@ async function bench(maxConcurrentFileUploads = 2) { // config.input is required (the apply shares its hub with the inject // factories); the bench passes its own instance explicitly. const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) + const uploadLimit = createSnapshotStore(maxConcurrentFileUploads === 'absent' ? undefined : maxConcurrentFileUploads) const fiber = runtime.ctx.plugin(ConversationController, { input: hub, blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads, + maxConcurrentFileUploads: uploadLimit, }) await fiber.await() const root = runtime.ctx.get('conversation') as ConversationController const scoped = runtime.sessions.scope('s1')!.get('conversation') as ConversationController const shell = hub.shellFor(runtime.sessions.binding('s1')!) - return { runtime, fiber, root, scoped, hub, shell, prompt, updateQueue, cancel, loadOlder, reference } + return { runtime, fiber, root, scoped, hub, shell, prompt, updateQueue, cancel, loadOlder, reference, uploadLimit } } describe('ConversationController', () => { @@ -138,7 +140,7 @@ describe('ConversationController', () => { await b.runtime.dispose() }) - it('releases draft previews when their session scope is disposed', async () => { + it('keeps draft previews registered when their session scope is disposed and re-adopts them on return', async () => { const b = await bench() const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:draft-1') const revoked = vi.spyOn(URL, 'revokeObjectURL').mockReturnValue(undefined) @@ -150,8 +152,11 @@ describe('ConversationController', () => { b.root.input.for(b.runtime.sessions.scope('s1')!).addAttachments([attachment.id]) b.reference.release() await b.runtime.flush() - expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([]) - expect(revoked).toHaveBeenCalledWith('blob:draft-1') + expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([attachment]) + expect(revoked).not.toHaveBeenCalled() + const again = b.runtime.sessions.retain('s1' as SessionId) + await again.ready + expect(b.hub.shellFor(b.runtime.sessions.binding('s1')!).snapshot.attachmentIds).toEqual([attachment.id]) } finally { created.mockRestore() revoked.mockRestore() @@ -317,7 +322,8 @@ describe('ConversationController', () => { }) it('bounds upload Workers, advances on settlement, and skips a queued file removed by the user', async () => { - const b = await bench(2) + // With no limit from the Host, two uploads run at once, as before the limit moved to the Host. + const b = await bench('absent') const session = b.runtime.sessions.binding('s1')!.session type UploadResult = { ok: true @@ -366,6 +372,21 @@ describe('ConversationController', () => { await b.runtime.dispose() }) + it('starts a queued upload at once when the Host raises the upload limit', async () => { + const b = await bench(2) + const session = b.runtime.sessions.binding('s1')!.session + const uploadFile = vi.fn((_data: Uint8Array, _name?: string, signal?: AbortSignal) => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) + })) + ;(session as { uploadFile?: unknown }).uploadFile = uploadFile + b.root.createDrafts(session.sessionId, ['one', 'two', 'three'].map(name => + new File([Uint8Array.of(1)], `${name}.txt`, { type: 'text/plain' })), UPLOAD_IMAGES) + await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledTimes(2) }) + b.uploadLimit.set(3) + await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledTimes(3) }) + await b.runtime.dispose() + }) + it('keeps one upload alive and observable while another Session is open', async () => { const b = await bench() const session = b.runtime.sessions.binding('s1')!.session @@ -603,7 +624,7 @@ describe('ConversationController', () => { await bare.plugin(ConversationController, { input: new InputHub(bare, makeTranslate(zh, {})), blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads: 2, + maxConcurrentFileUploads: createSnapshotStore(2), }).await() const orphan = bare.get('conversation') as ConversationController await expect(orphan.send('x')).rejects.toThrow(/sessions service unavailable/) diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 55a9c935e4..41c2c9ea9a 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import type { GlobalStandardProps, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createContext, useContext, type ReactNode } from 'react' import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import type { Context } from '@deepseek-ai/cordis' @@ -32,6 +32,7 @@ import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import type { ComposerBarOwnerProps, ConversationContentInputProps, ConversationContentProps, + WorkspaceSelectedHandler, WorkspaceSessionAdopter, ConversationHeaderLineageOwnerProps, ConversationSessionHeaderSlotProps, ConversationSessionSlotProps, ConversationSlotProps, ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps, } from '../src/client/contract/slots.ts' @@ -124,7 +125,7 @@ function sessionSnapshotOf(overrides: Partial = {}): SessionSna function mount( snapshot: SessionSnapshot, workspaceRows: WorkspaceView[] = [{ ...workspace('one'), sessionIds: [SID] }], - retargetWorkspace = vi.fn(async (_workspaceId: WorkspaceId) => {}), + retargetWorkspace = vi.fn(async () => {}), options: { /** Explicit undefined exercises the shell before a Session is selected. */ sessionId?: SessionId | undefined @@ -148,8 +149,6 @@ function mount( entryActions?: boolean /** Isolate header capability checks from the composer's required layout observers. */ headerOnly?: boolean - /** Inputs an embedding owner adds to the content occurrence. */ - contentInput?: Pick } = {}, ) { const sessionId = 'sessionId' in options ? options.sessionId : SID @@ -353,6 +352,7 @@ function mount( : (opts?.fallback ?? null) )) as ConversationContentProps['renderSlotChain'] const SessionProvider: ConversationContentProps['SessionProvider'] = ({ children }) => children + const moveDraft = vi.fn() const renderFactorySlot = ((_name: string, input: ConversationContentInputProps, factoryOptions?: { slots?: Record ReactNode> }) => { @@ -379,7 +379,7 @@ function mount( renderSlot, renderSlotChain, renderFactorySlot, - selectWorkspace: retargetWorkspace, + moveDraft, t, } const useFactorySlot = ((name: string, fallback: (props: never) => ReactNode) => ( @@ -387,7 +387,7 @@ function mount( )) as ConversationContentProps['useFactorySlot'] return ( - + ) }) as ConversationSlotProps['renderFactorySlot'] @@ -395,6 +395,7 @@ function mount( usePanelInfo: selector => selector({ activePanelId: null }), sessionId, SessionProvider, + openWorkspace: retargetWorkspace, useSession: sessionId === undefined ? () => undefined : useSession, useConversation: sessionId === undefined ? () => undefined : useConversation, useSessions: bindSnapshotSelector(sessions), @@ -411,7 +412,8 @@ function mount( const props: ConversationSlotProps = { ...runtimeProps, renderSlot, renderFactorySlot } const view = render() return { - view, store, wiring, sink, retargetWorkspace, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, open, + view, store, wiring, sink, retargetWorkspace, moveDraft, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, + open, pickerOwner: () => pickerOwner, frameOwner: () => frameOwners.at(-1), setPinned, @@ -620,7 +622,7 @@ describe('ConversationRoot resident composer', () => { const owner = b.pickerOwner() as { open: boolean; onPick(id: WorkspaceId): void } expect(owner.open).toBe(true) act(() => { owner.onPick(wid('second')) }) - expect(b.retargetWorkspace).toHaveBeenCalledWith(wid('second'), undefined) + expect(b.retargetWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.getByText('Selected Folder')).toBeTruthy() }) @@ -901,7 +903,7 @@ describe('ConversationRoot resident composer', () => { }) it('rolls the pending workspace label back when switching fails', async () => { - const selectWorkspace = vi.fn(async () => { throw new Error('connect failed') }) + const selectWorkspace = vi.fn(async () => { throw new Error('connect failed') }) const b = mount( sessionSnapshotOf({ blank: true }), [ @@ -913,87 +915,9 @@ describe('ConversationRoot resident composer', () => { fireEvent.click(b.view.getByRole('button', { name: '选择工作区' })) const owner = b.pickerOwner() as { onPick(id: WorkspaceId): void } await act(async () => { owner.onPick(wid('second')); await Promise.resolve() }) - expect(selectWorkspace).toHaveBeenCalledWith(wid('second'), undefined) + expect(selectWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.queryByText('Selected Folder')).toBeNull() expect(b.view.getByText('one')).toBeTruthy() - // Workspace navigation reports this failure; the content adds no notice of its own. - expect(screen.queryByText(/没能打开这个工作区/)).toBeNull() - }) - - describe('embedded Workspace pick', () => { - /** One pick in flight: the handover the content gave `selectWorkspace`, and how the connection settles. */ - interface Pick { - readonly handOver: ((sessionId: SessionId) => boolean) | undefined - readonly fail: (error: unknown) => void - } - - /** Mount a blank embedded occurrence whose picks settle when the test says. */ - function embedded() { - const picks: Pick[] = [] - const selectWorkspace = vi.fn((_workspaceId: WorkspaceId, handOver?: (sessionId: SessionId) => boolean) => - new Promise((_resolve, reject) => { picks.push({ handOver, fail: reject }) })) - const owner = vi.fn<(sessionId: SessionId) => void>() - const b = mount( - sessionSnapshotOf({ blank: true }), - [ - { ...workspace('one'), sessionIds: [SID] }, - { ...workspace('second'), title: 'Second Folder' }, - { ...workspace('third'), title: 'Third Folder' }, - ], - selectWorkspace, - { contentInput: { onWorkspaceSession: owner } }, - ) - const pick = (id: string): void => { - act(() => { (b.pickerOwner() as { onPick(id: WorkspaceId): void }).onPick(wid(id)) }) - } - return { b, picks, owner, pick } - } - - it('hands only the latest pick to the owner', () => { - const { picks, owner, pick } = embedded() - pick('second') - pick('third') - expect(picks[0]?.handOver?.(sid('second-blank'))).toBe(false) - expect(owner).not.toHaveBeenCalled() - expect(picks[1]?.handOver?.(sid('third-blank'))).toBe(true) - expect(owner.mock.calls).toEqual([[sid('third-blank')]]) - }) - - it('declines a pick that connects after the occurrence unmounted', () => { - const { b, picks, owner, pick } = embedded() - pick('second') - b.view.unmount() - expect(picks[0]?.handOver?.(sid('second-blank'))).toBe(false) - expect(owner).not.toHaveBeenCalled() - }) - - it('shows why the latest pick failed for a while and returns to the Workspace it showed', async () => { - vi.useFakeTimers() - onTestFinished(() => { vi.useRealTimers() }) - const { b, picks, pick } = embedded() - pick('second') - expect(b.view.getByText('Second Folder')).toBeTruthy() - await act(async () => { picks[0]?.fail(new Error('preset missing')); await Promise.resolve() }) - expect(screen.getByText('没能打开这个工作区:preset missing')).toBeTruthy() - expect(b.view.queryByText('Second Folder')).toBeNull() - expect(b.view.getByText('one')).toBeTruthy() - - pick('third') - await act(async () => { picks[1]?.fail('offline'); await Promise.resolve() }) - expect(screen.queryByText('没能打开这个工作区:preset missing')).toBeNull() - expect(screen.getByText('没能打开这个工作区:offline')).toBeTruthy() - act(() => { vi.advanceTimersByTime(5_000) }) - expect(screen.queryByText('没能打开这个工作区:offline')).toBeNull() - }) - - it('reports no failure for a pick that another pick replaced', async () => { - const { b, picks, pick } = embedded() - pick('second') - pick('third') - await act(async () => { picks[0]?.fail(new Error('too late')); await Promise.resolve() }) - expect(screen.queryByText(/没能打开这个工作区/)).toBeNull() - expect(b.view.getByText('Third Folder')).toBeTruthy() - }) }) it('blank session keeps the interactive picker chip (workspace switchable until the first message)', () => { @@ -1059,32 +983,32 @@ describe('ConversationRoot resident composer', () => { Element.prototype.releasePointerCapture = function () { captured.delete(this) } Element.prototype.hasPointerCapture = function () { return captured.has(this) } try { - // Base resolves from the adaptive clamp: min(1600*0.64, 920) = 920. - // Dragging the right handle outward by 25px widens by 2×25 = 50 → 970, + // Base resolves from the adaptive clamp: min(1600*0.64, 880) = 880. + // Dragging the right handle outward by 25px widens by 2×25 = 50 → 930, // inside both bounds (max = 1600 − 176 = 1424 keeps the handles on-column). fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 }) fireEvent.pointerMove(handle, { pointerId: 1, clientX: 825, clientY: 300 }) expect(handle.style.getPropertyValue('--dsh-width-handle-pointer-y')).toBe('300px') fireEvent.pointerUp(handle, { pointerId: 1, clientX: 825, clientY: 300 }) expect(handle.hasAttribute('data-dragging')).toBe(false) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('970px') - expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970') + expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px') + expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') // Window shrinks: the displayed width re-clamps (900 − 176 = 724) but the // preference stays. Object.defineProperty(content, 'offsetWidth', { value: 900, configurable: true }) act(() => { fireResize(content) }) expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') - expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970') + expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') // A press without travel (a real double-click delivers two such // press/release rounds) must not commit the clamped display value over // the stored preference. fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 }) fireEvent.pointerUp(handle, { pointerId: 1, clientX: 800, clientY: 300 }) - expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970') + expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') // No reset affordance on the handle: double-click leaves the preference alone. fireEvent.doubleClick(handle) - expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970') + expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') } finally { for (const [name, descriptor] of originals) { if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name) diff --git a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts index f1f93856f1..4bb28dc0c1 100644 --- a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts +++ b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it, vi } from 'vitest' import type { SessionPendingInteractionBase } from '@deepseek-ai/dsh-client-ui-session/client' import type { Shortcuts, ShortcutContext, ShortcutGesture } from '@deepseek-ai/dsh-client-shortcuts/client' @@ -30,7 +31,7 @@ async function bench() { await reference.ready const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) const fiber = runtime.ctx.plugin(ConversationController, { - input: hub, blocks: new ComposerBlockRegistry(), maxConcurrentFileUploads: 2, + input: hub, blocks: new ComposerBlockRegistry(), maxConcurrentFileUploads: createSnapshotStore(2), }) await fiber.await() const conversation = new UiConversation(runtime.ctx, runtime.sessions) diff --git a/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx index c5383f3091..116f68f039 100644 --- a/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx +++ b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx @@ -53,6 +53,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in const openFile = actions.openFile ?? (() => { throw new Error('This fixture has no file navigation action') }) const openSkill = actions.openSkill ?? (() => { throw new Error('This fixture has no skill navigation action') }) const t = makeTranslate(referenceZh, commonZh) + // Composition units treat every path mention as Host-confirmed; ui-reference owns presence coverage. + const usePathPresence = () => 'present' as const const renderSlot: UserTextProps['renderSlot'] = (name: string, input: object, options?: { fallback?: ReactNode }) => { if (name !== 'conversation.user.text.node') throw new Error(`Unexpected UserText Slot: ${name}`) const owner = input as UserTextNodeOwnerProps & { node: UserTextNode } @@ -62,8 +64,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in case 'secret': return createElement(SecretText, { ...owner, t } as ComponentProps) case 'text': return createElement(PlainUserText, owner as ComponentProps) case 'session': return createElement(SessionReference, owner as ComponentProps) - case 'file': return createElement(FileReference, { ...owner, openFile, t, useContextMenu: contextMenuHook(), resolveFilePath: (path: string) => path } as ComponentProps) - case 'folder': return createElement(FolderReference, owner as ComponentProps) + case 'file': return createElement(FileReference, { ...owner, openFile, usePathPresence, t, useContextMenu: contextMenuHook(), resolveFilePath: (path: string) => path } as ComponentProps) + case 'folder': return createElement(FolderReference, { ...owner, usePathPresence } as ComponentProps) case 'skill': return createElement(SkillReference, { ...owner, openSkill } as ComponentProps) case 'command': return createElement(GoalCommandReference, owner as ComponentProps) default: return options?.fallback ?? null diff --git a/packages/client/ui-conversation/tsconfig.client.json b/packages/client/ui-conversation/tsconfig.client.json index 759d52d183..dcac12eda3 100644 --- a/packages/client/ui-conversation/tsconfig.client.json +++ b/packages/client/ui-conversation/tsconfig.client.json @@ -9,6 +9,9 @@ "src" ], "references": [ + { + "path": "../config" + }, { "path": "../../../vendor/schemastery" }, diff --git a/packages/client/ui-conversation/tsconfig.host.json b/packages/client/ui-conversation/tsconfig.host.json index ec30b21bfe..aed18a8dc9 100644 --- a/packages/client/ui-conversation/tsconfig.host.json +++ b/packages/client/ui-conversation/tsconfig.host.json @@ -7,6 +7,7 @@ }, "files": [ "src/submission-settings.ts", + "src/types.ts", "src/index.ts" ], "references": [ diff --git a/packages/client/ui-dockkit/README.i18n.yaml b/packages/client/ui-dockkit/README.i18n.yaml index de5d3d26e3..73075677d1 100644 --- a/packages/client/ui-dockkit/README.i18n.yaml +++ b/packages/client/ui-dockkit/README.i18n.yaml @@ -18,8 +18,8 @@ en: 718f52cfce426009 zh: e8282e2e3713d242 /deepseek-ai-dsh-client-ui-dockkit/embedding-it: - en: 53bbabeb910c6f77 - zh: 51fb4f8fb78cfd02 + en: 5e025290e8881fa8 + zh: 2bc9c3ff83914241 /deepseek-ai-dsh-client-ui-dockkit/interaction-rules-worth-keeping: en: cf2d00ce2b7d5719 zh: 5510420f8872e23a @@ -33,8 +33,8 @@ en: ca75c51c89c2c9b0 zh: f57cc48a1b5cbfa9 /deepseek-ai-dsh-client-ui-dockkit/known-limitations-and-deferred-work: - en: 4323810ca5a87e6c - zh: 3a24af2ea4467ab7 + en: eb44edbaf45e1b62 + zh: 3fcfb01054ceacc7 /deepseek-ai-dsh-client-ui-dockkit/known-limitations-and-deferred-work/dev-note: en: 45680a19e42f401a zh: 5500de88331c8a59 diff --git a/packages/client/ui-dockkit/README.md b/packages/client/ui-dockkit/README.md index f12010307a..a8d99c1568 100644 --- a/packages/client/ui-dockkit/README.md +++ b/packages/client/ui-dockkit/README.md @@ -48,6 +48,8 @@ Tab context menus show the close action name without a shortcut hint: they act o ## Embedding it +Strip chrome continues the adjacent control spacing, so embedder actions and the split action form one consistent trailing group. + Everything host-specific arrives through props: | Contract | Carries | @@ -101,6 +103,8 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work +Dock-zone menu glyphs retain a 16px layout box with an inset painted frame, matching the neighboring split action. + - **Size semantics are deliberately small**: fractional weights with one minimum-size clamp. No snap, priority, or preferred size, so the cascading-squeeze behaviour of a full splitview is absent. diff --git a/packages/client/ui-dockkit/README.zh.md b/packages/client/ui-dockkit/README.zh.md index 810a6d3ede..6fbacf6dd5 100644 --- a/packages/client/ui-dockkit/README.zh.md +++ b/packages/client/ui-dockkit/README.zh.md @@ -48,6 +48,8 @@ kind: "package-reference" ## 如何嵌入 +标签栏尾部控件沿用相邻控件的间距,使嵌入方操作与分栏操作组成一致的尾部操作组。 + 一切宿主相关的东西都通过 props 进入: | 约定 | 承载内容 | @@ -101,6 +103,8 @@ Sidebar 使用的 `DockLayout` 在选中项变化、跨格移动与浮动期间 ## 已知限制与延期工作 +停靠区域菜单图标保留 16px 布局框,实际绘制的边框向内缩进,与相邻分栏操作保持视觉比例。 + - **尺寸语义刻意保持精简**:比例权重加一处最小尺寸夹取。没有吸附、优先级或首选尺寸,因此完整 splitview 的级联挤压行为不存在。 diff --git a/packages/client/ui-dockkit/src/components/TabPanel.tsx b/packages/client/ui-dockkit/src/components/TabPanel.tsx index 51ea45b6e6..390efe5006 100644 --- a/packages/client/ui-dockkit/src/components/TabPanel.tsx +++ b/packages/client/ui-dockkit/src/components/TabPanel.tsx @@ -70,7 +70,7 @@ const ZONE_FILL: Record = { /** The drop hint's glyph: the panel frame with the zone's fill drawn solid. */ function ZoneGlyph({ zone }: { readonly zone: DockZone }): ReactNode { return ( - - {duration} - - ) - const body = live - ? ( - <> - - - - {job.label} - - - {job.kind} - {detail !== undefined ? {detail} : null} - {durationCell} - - - {/* A live row is always observable: its output may still arrive. */} - - - - - ) - : ( - <> - - {job.kind} - {job.label} - {detail ?? status} - {durationCell} - {observable - ? ( - - - - ) - : null} - - ) - const killTitle = kill === undefined - ? undefined - : kill.state === 'armed' - ? t('kill.confirm') - : kill.state === 'failed' ? t('kill.failed') : t('kill.stop', { label: job.label }) - return ( -
  • -
    - {observable - ? ( - - ) - : ( - - {body} - - )} - {kill !== undefined - ? ( - - ) - : null} -
    - {expanded && view !== undefined - ? ( -
    - {view.gapBefore ?
    {t('output.gap')}
    : null} - {view.error !== undefined - ?
    {t('output.error', { error: view.error })}
    - : null} - -
    - ) - : null} -
  • - ) -} - -/** - * Session-header entry point for this session's background jobs. Mounting it - * keeps the session's roster stream open; it renders nothing at all until the - * session can see at least one job. Expanding an observable row (a live job, - * or a settled one with retained output) starts its observation stream, and - * collapsing (or closing the popover) stops it — output only flows while - * someone is watching. A running row carries a two-press stop button that - * requests a human kill through the job controller. Non-touch hover on a - * text-visible trigger opens after 150ms and closes after 120ms outside both - * trigger and portal. Compact triggers toggle on click; ArrowDown opens and - * pins either layout. Interacting inside also pins the menu until explicit - * dismissal; timers and the pin are local to the mounted session. - * @param props - runtime slot currency, the jobs snapshot hook, the roster, - * observation, and kill controls, and the namespace translator. - * @returns the trigger and its popover list, or null when there is nothing to show. - */ -export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, t }: JobListActionProps) { - const activityId = useId() - const jobs = useJobs(state => state.rows[sessionId]) ?? NO_JOBS - const observedViews = useJobs(state => state.observed) - const [menuState, setMenuState] = useState<{ sessionId: SessionId; mode: 'closed' | 'hover' | 'pinned' }>( - { sessionId, mode: 'closed' }, - ) - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - if (menuState.sessionId !== sessionId) setMenuState({ sessionId, mode: 'closed' }) - const [expandedKey, setExpandedKey] = useState(undefined) - const [now, setNow] = useState(() => Date.now()) - // Settled-section fold: an explicit user toggle wins; before one, the tail - // folds only while live work exists (a settled-only list opens expanded). - const [settledOpen, setSettledOpen] = useState(undefined) - // Rows the user cleared from the settled tail (client-side hide only; the - // registry keeps its records and a later settlement reappears normally). - const [clearedKeys, setClearedKeys] = useState>(() => new Set()) - // One kill affordance advances at a time: arming a row disarms any other. - const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude } | undefined>(undefined) - const rootRef = useRef(null) - const triggerRef = useRef(null) - const countRef = useRef(null) - const menuRef = useRef(null) - - const rows = useMemo(() => ordered(jobs), [jobs]) - const liveRows = useMemo(() => rows.filter(isLive), [rows]) - const settledRows = useMemo( - () => rows.filter(job => !isLive(job) && !clearedKeys.has(String(job.id))), - [rows, clearedKeys], - ) - const settledExpanded = settledOpen ?? liveRows.length === 0 - const visibleCount = liveRows.length + settledRows.length - const hasJobs = visibleCount > 0 - const open = hasJobs && menuState.sessionId === sessionId && menuState.mode !== 'closed' - - const cancelHover = useCallback((): void => { - clearTimeout(hoverOpenTimer.current) - clearTimeout(hoverCloseTimer.current) - hoverOpenTimer.current = undefined - hoverCloseTimer.current = undefined - }, []) - - const changeOpen = useCallback((next: boolean): void => { - cancelHover() - if (next) setNow(Date.now()) - setMenuState({ sessionId, mode: next ? 'pinned' : 'closed' }) - }, [cancelHover, sessionId]) - - // CSS owns the compact breakpoint; read its result only for pointer gestures. - const allowsHoverOpen = (): boolean => countRef.current !== null - && getComputedStyle(countRef.current).display !== 'none' - - const hoverEnter = (event: PointerEvent): void => { - if (event.pointerType === 'touch') return - cancelHover() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (!allowsHoverOpen()) return - setNow(Date.now()) - setMenuState({ sessionId, mode: 'hover' }) - }, 150) - } - - const hoverLeave = (event: PointerEvent): void => { - if (event.pointerType === 'touch') return - cancelHover() - if (!open || menuState.mode === 'pinned') return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - setMenuState({ sessionId, mode: 'closed' }) - }, 120) - } - - // Timers belong to this mounted session and cannot survive a disappearing trigger. - useEffect(() => cancelHover, [cancelHover, sessionId, hasJobs]) - - const anchorName = `--dsh-jobs-${useId().replaceAll(':', '')}` - useDismissOnOutsidePointer(rootRef, open, changeOpen, menuRef) - // Hover does not move focus; Escape must also work from the rest of the page. - useEffect(() => { - if (!open) return - const dismiss = (event: globalThis.KeyboardEvent): void => { - if (event.key !== 'Escape' || event.defaultPrevented) return - event.preventDefault() - changeOpen(false) - } - document.addEventListener('keydown', dismiss) - return () => { document.removeEventListener('keydown', dismiss) } - }, [open, changeOpen]) - - // The roster follows the mounted session: one stream while this control - // lives, released with it. - useEffect(() => watchRows(sessionId), [sessionId, watchRows]) - - // The clock only runs while an open list is showing something that moves. - useEffect(() => { - if (!open || liveRows.length === 0) return - setNow(Date.now()) - const timer = setInterval(() => { setNow(Date.now()) }, 1_000) - return () => { clearInterval(timer) } - }, [open, liveRows.length]) - - // Observation follows visibility: the stream opens when an observable panel - // expands and closes when it collapses, unmounts, or the popover closes. - const expandedRow = open && expandedKey !== undefined - ? rows.find(job => String(job.id) === expandedKey) - : undefined - const activeJob = expandedRow !== undefined && isObservable(expandedRow) ? expandedRow.id : undefined - useEffect(() => { - if (activeJob === undefined) return - return observe(sessionId, activeJob) - }, [sessionId, activeJob, observe]) - - // A returning roster starts closed rather than restoring an obsolete pin. - useEffect(() => { - if (!hasJobs) changeOpen(false) - }, [hasJobs, changeOpen]) - - // An expanded row that left the list (owner disposal) folds its panel. - useEffect(() => { - if (expandedKey !== undefined && !rows.some(job => String(job.id) === expandedKey)) { - setExpandedKey(undefined) - } - }, [rows, expandedKey]) - - // An armed kill disarms on a timer, and a failed one clears its hint; the - // pending phase instead waits for the RPC (or the row's own status flip). - // The cleanup clears the timer on every phase change, so a firing timer - // always describes the current phase and may reset unconditionally. - useEffect(() => { - if (killPhase === undefined || killPhase.state === 'pending') return - const timer = setTimeout( - () => { setKillPhase(undefined) }, - killPhase.state === 'armed' ? KILL_ARM_MS : KILL_FAILED_MS, - ) - return () => { clearTimeout(timer) } - }, [killPhase]) - - // A phase whose row stopped being killable (settled, stopping, removed) - // has no button to describe any more. - useEffect(() => { - if (killPhase !== undefined - && !rows.some(job => String(job.id) === killPhase.key && job.status === 'running')) { - setKillPhase(undefined) - } - }, [rows, killPhase]) - - const pressKill = (job: JobView): void => { - const key = String(job.id) - if (killPhase?.key !== key || killPhase.state !== 'armed') { - setKillPhase({ key, state: 'armed' }) - return - } - setKillPhase({ key, state: 'pending' }) - void killJob(sessionId, key).then((ok) => { - // An admitted kill stays pending: the unary response (HTTP) and the jobs - // frames (control stream) have no cross-carrier ordering, so re-enabling - // here could offer a duplicate kill while the row still reads `running`. - // The authoritative jobs frame flips the row to `stopping`, which removes - // the button and clears the phase through the killable-set effect above. - setKillPhase(current => current?.key === key && !ok - ? { key, state: 'failed' } - : current) - }) - } - - if (visibleCount === 0) return null - - const count = liveRows.length > 0 ? liveRows.length : visibleCount - const countLabel = t(count === 1 ? 'count.idle.one' : 'count.idle.other', { count }) - - const clearSettled = (): void => { - setClearedKeys((current) => { - const next = new Set(current) - for (const job of settledRows) next.add(String(job.id)) - return next - }) - if (expandedKey !== undefined && settledRows.some(job => String(job.id) === expandedKey)) { - setExpandedKey(undefined) - } - } - - // The portaled list sits at the end of the document, so Tab is bridged to - // keep the in-place order: the trigger leads into the list, and leaving - // either end of the list returns to the trigger's position in the page. - const onKeyDown = (event: KeyboardEvent): void => { - const trigger = triggerRef.current - if (event.key === 'Escape') { - event.preventDefault() - changeOpen(false) - trigger?.focus() - return - } - if (!open) return - const menu = menuRef.current - /* v8 ignore next -- both refs are attached while the open list renders. */ - if (event.key !== 'Tab' || trigger === null || menu === null) return - const focusable = [...menu.querySelectorAll(FOCUSABLE)] - if (event.target === trigger) { - // Every list carries a control: a live row's toggle or the settled section's buttons. - if (event.shiftKey) return - event.preventDefault() - focusable[0]?.focus() - } else if (event.shiftKey ? event.target === focusable[0] : event.target === focusable.at(-1)) { - // Shift+Tab lands on the trigger itself; Tab continues from it to the - // control that follows the trigger. - if (event.shiftKey) event.preventDefault() - trigger.focus() - } - } - - const item = (job: JobView) => ( - { - setExpandedKey(current => current === String(job.id) ? undefined : String(job.id)) - }} - {...job.status === 'running' - ? { - kill: { - state: killPhase?.key === String(job.id) ? killPhase.state : 'idle' as const, - onPress: () => { pressKill(job) }, - }, - } - : {}} - t={t} - /> - ) - - return ( -
    - - - - {liveRows.length > 0 && } - {open - ? createPortal( - { changeOpen(true) }} - onFocusCapture={() => { changeOpen(true) }} - > -
      - {liveRows.length > 0 - ? - : null} - {liveRows.map(item)} - {settledRows.length > 0 - ? ( -
    • - - -
    • - ) - : null} - {settledExpanded ? settledRows.map(item) : null} -
    -
    , - document.body, - ) - : null} -
    - ) -} diff --git a/packages/client/ui-jobs/src/client/JobsSection.module.css b/packages/client/ui-jobs/src/client/JobsSection.module.css new file mode 100644 index 0000000000..1250827987 --- /dev/null +++ b/packages/client/ui-jobs/src/client/JobsSection.module.css @@ -0,0 +1,266 @@ +/* The panel toggle sizes and places this dot; it names the state for assistive technology. */ +.runningIndicator { + background: var(--dsw-alias-state-business-primary); +} + +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +/* Rows sit inside the Session panel section body, which supplies the inset and + scrolling. They share the panel's columns: the status glyph's center 14px + from the row start, text at 30px, and the chevron's center 14px from the row + end. */ +.list { + display: flex; + flex-direction: column; + margin: 0; + padding: 0; + list-style: none; +} + +/* Fold toggle and clear action over the settled tail. */ +.sectionHeader { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 24px; + margin-top: 4px; + padding: 0 6px; + border-top: 0.5px solid var(--dsw-alias-border-l1); +} + +/* The leading section needs no divider above it. */ +.sectionHeader:first-child { + margin-top: 0; + border-top: 0; +} + +.sectionToggle, +.sectionClear { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 0; + border: 0; + background: transparent; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xxs-12); + font-variant-numeric: tabular-nums; + cursor: pointer; +} + +.sectionToggle:focus-visible, +.sectionClear:focus-visible { + color: var(--dsw-alias-label-secondary); +} + +@media (hover: hover) { + .sectionToggle:hover, + .sectionClear:hover { + color: var(--dsw-alias-label-secondary); + } +} + +.sectionChevron { + transform: rotate(-90deg); + transition: transform 120ms ease; +} + +.sectionChevronOpen { + transform: none; +} + +.item { + display: flex; + flex-direction: column; +} + +/* One 28px line per job: the command, its duration, the stop control, and the + chevron; the kind and state show in the row's hover card. The row button's + overlay covers the whole line, so the line highlights as one row; the stop + control sits above the overlay and the chevron reads through it. */ +.rowLine { + position: relative; + display: flex; + align-items: center; + gap: 8px; + min-height: 28px; + box-sizing: border-box; + padding: 4px 6px; + border-radius: var(--dsw-radius-sm); +} + +@media (hover: hover) { + .rowInteractive:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.rowLine:has(> .row:focus-visible) { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -2px; +} + +.row { + display: flex; + flex: 1; + align-items: center; + gap: 8px; + min-width: 0; + padding: 0; + border: 0; + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + text-align: left; +} + +button.row { + cursor: pointer; +} + +button.row::after { + position: absolute; + inset: 0; + border-radius: inherit; + content: ''; +} + +button.row:focus-visible { + outline: none; +} + +.glyph { + display: grid; + flex: none; + place-items: center; + width: 16px; + height: 20px; +} + +.label { + flex: 1; + font-size: 13px; + line-height: 20px; +} + +.duration { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + font-variant-numeric: tabular-nums; + line-height: 20px; +} + +/* The trailing column; a row without output keeps it empty so the durations + stay aligned. It takes no presses: the row button's overlay below takes + them, also once the open chevron's rotation would paint it above that overlay. */ +.chevron { + display: grid; + pointer-events: none; + flex: none; + align-self: center; + place-items: center; + width: 16px; + height: 20px; + color: var(--dsw-alias-label-tertiary); +} + +.chevronOpen { + transform: rotate(180deg); +} + +/* Two-press kill: a plain glyph like the row's other trailing icons, with a 24px + target that overhangs the 20px line, so a running row keeps its 28px. */ +.stop { + position: relative; + z-index: 1; + display: inline-flex; + flex: none; + align-items: center; + align-self: center; + justify-content: center; + min-width: 24px; + height: 24px; + margin: -2px -4px; + padding: 0; + border: 0; + border-radius: var(--dsw-radius-xs); + background: transparent; + color: var(--dsw-alias-label-tertiary); + cursor: pointer; +} + +.stop:focus-visible { + outline-offset: -2px; + color: var(--dsw-alias-state-error-primary); +} + +@media (hover: hover) { + .stop:hover { + color: var(--dsw-alias-state-error-primary); + } +} + +/* The armed press widens into a labeled danger pill so the confirm step is + legible without hover; the state-error token is the one StateDot uses. The + pill is the 20px the row's padding leaves, so arming keeps the 28px line. */ +.stopArmed { + gap: 4px; + height: 20px; + margin: 0; + padding: 0 6px; + border-radius: var(--dsw-radius-sm); + background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent); + color: var(--dsw-alias-state-error-primary); +} + +.stopLabel { + font-size: 11px; + line-height: 18px; + white-space: nowrap; +} + +.stopFailed { + color: var(--dsw-alias-state-error-primary); +} + +.panel { + margin: 2px 6px 6px; + /* Long commands and output lines wrap in full instead of ellipsizing or + scrolling sideways, and the output region scrolls within a fixed height + instead of folding its middle lines. */ + --dsl-terminal-command-whitespace: pre-wrap; + --dsl-terminal-line-whitespace: pre-wrap; + --dsl-terminal-output-max-height: 288px; +} + +/* The row carries the state dot, so the panel omits its own and reclaims the + dot gutter down to an ordinary content inset. It takes the density of a tool + call's terminal card. The overrides target the card element itself because + these variables are declared on it — a value inherited from this container + would lose to that declaration. */ +.panel :global([data-terminal]) { + --dsl-terminal-gutter: 12px; + --dsl-terminal-font: var(--dsw-font-markdown-code-block-small); + --dsl-terminal-line-height: 18px; + margin: 0; + border: 0.5px solid var(--dsw-alias-border-l1); +} + +.notice { + margin: 0 8px 6px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 16px; +} + +.noticeError { + color: var(--dsw-alias-state-error-primary); +} diff --git a/packages/client/ui-jobs/src/client/JobsSection.tsx b/packages/client/ui-jobs/src/client/JobsSection.tsx new file mode 100644 index 0000000000..3449162cca --- /dev/null +++ b/packages/client/ui-jobs/src/client/JobsSection.tsx @@ -0,0 +1,526 @@ +import { useEffect, useId, useMemo, useRef, useState } from 'react' +import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + HoverCard, HoverCardGroup, IconChevronDownOutlineRegular, IconStopFillRegular, MarqueeText, + StateDot, type StateDotState, TerminalBlock, type TerminalBlockLabels, Tooltip, useHoverMarquee, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import type { createJobsSectionStore, JobGroup } from './jobs-store.ts' +import { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' +import css from './JobsSection.module.css' + +/** Registration-side business face for the background-jobs section. */ +export interface JobsSectionInjected { + hooks: { + /** Client jobs snapshot (rosters and observations) bound by the renderer as useJobs. */ + jobs: { + getSnapshot(): JobsSnapshot + subscribe(listener: () => void): () => void + } + } + /** + * Keep one session's roster current while the list is mounted; returns the + * stop function. Reference-counted by the client service. + */ + watchRows: (sessionId: SessionId) => () => void + /** + * Start observing one job's live output; returns the stop function. + * Reference-counted by the client service, so panels can overlap safely. + */ + observe: (sessionId: SessionId | undefined, id: JobView['id']) => () => void + /** + * Kill one background job on the human's behalf. Resolves `true` when the + * registry admitted the request (`requested` or `already-finished`); row + * state itself converges through the jobs control frames. + */ + killJob: (sessionId: SessionId, jobId: string) => Promise +} + +/** Full props for the Session panel's background-jobs section. */ +export type JobsSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderFactories + & PropsLocale + & InjectFace + & PropsStore> + +/** Business face of the running dot on the Session panel toggle. */ +export type JobsRunningIndicatorInjected = Pick + +/** Full props of the running dot on the Session panel toggle. */ +export type JobsRunningIndicatorProps = + PropsRuntime<'conversation.session.panel.indicator'> + & PropsLocale + & InjectFace + +/** Stable empty list so a session with no jobs keeps one array identity. */ +const NO_JOBS: readonly JobView[] = [] + +/** Rows a group shows before its fold control holds the rest back. */ +const FOLD_LIMIT = 5 + +/** How long an armed kill waits for its confirming press before disarming. */ +const KILL_ARM_MS = 3_000 + +/** How long a failed kill keeps its hint before the button resets. */ +const KILL_FAILED_MS = 4_000 + + +function isLive(job: JobView): boolean { + return job.status === 'running' || job.status === 'stopping' +} + +/** + * Whether the row offers an output panel: every live job (its output may + * still arrive) and a settled one that left retained output behind. + */ +function isObservable(job: JobView): boolean { + return isLive(job) || job.output.total > 0 +} + +/** The one-line qualifier beside the status: live progress while running, the terminal reason once settled. */ +function jobDetail(job: JobView): string | undefined { + return job.progress ?? job.detail +} + +/** Closed-union exhaustiveness fence for the wire status set. */ +/* v8 ignore next 3 -- closed-union backstop; only reached if a status is forged */ +function assertNever(value: never): never { + throw new Error(`unhandled job status: ${JSON.stringify(value)}`) +} + +/** + * Status marker semantics. `stopping` and `killed` share the attention color: + * both mean the work ended (or is ending) on request rather than on its own. + * So does a job that finished with a nonzero exit code: the command reported a + * failure, while `failed` means the job itself broke. + */ +function dotState(job: JobView): StateDotState { + switch (job.status) { + case 'running': return 'ongoing' + case 'stopping': return 'warning' + case 'completed': return job.exitCode === undefined || job.exitCode === 0 ? 'done' : 'warning' + case 'killed': return 'warning' + case 'failed': return 'error' + /* v8 ignore next -- closed wire status union */ + default: return assertNever(job.status) + } +} + +function statusLabel(status: JobView['status'], t: TranslateNS): string { + switch (status) { + case 'running': return t('status.running') + case 'stopping': return t('status.stopping') + case 'completed': return t('status.completed') + case 'killed': return t('status.killed') + case 'failed': return t('status.failed') + /* v8 ignore next -- closed wire status union */ + default: return assertNever(status) + } +} + +/** + * Elapsed time in at most two adjacent units. A job that outlives an hour is + * already exceptional, so hours is the widest unit — beyond that the figure + * stays in hours rather than growing a day/month vocabulary no producer + * currently reaches. + */ +function formatDuration(elapsedMs: number, t: TranslateNS): string { + const total = Math.max(0, Math.floor(elapsedMs / 1_000)) + const seconds = total % 60 + const minutes = Math.floor(total / 60) % 60 + const hours = Math.floor(total / 3_600) + if (hours > 0) return t('duration.hours', { hours, minutes }) + if (minutes > 0) return t('duration.minutes', { minutes, seconds }) + return t('duration.seconds', { seconds }) +} + +/** Localized display copy for the embedded terminal panel. */ +function terminalLabels(t: TranslateNS): TerminalBlockLabels { + return { + commandLine: line => t('terminal.commandLine', { n: line }), + // The labels contract requires exit-fact formatters, but this panel never + // passes exit facts, so TerminalBlock never invokes them. + /* v8 ignore next */ + signal: signal => t('terminal.signal', { signal }), + /* v8 ignore next */ + exitCode: code => t('terminal.exitCode', { code }), + noExitCode: t('terminal.noExitCode'), + running: t('terminal.running'), + failed: t('terminal.failed'), + done: t('terminal.done'), + copy: t('terminal.copy'), + copied: t('terminal.copied'), + noOutput: t('terminal.noOutput'), + collapseAria: t('terminal.collapseAria'), + collapse: t('terminal.collapse'), + // The panel never caps lines (it scrolls), so the fold controls that + // would invoke these stay unrendered. + /* v8 ignore next */ + expandAria: hidden => t('terminal.expandAria', { n: hidden }), + /* v8 ignore next */ + expand: hidden => t('terminal.expand', { n: hidden }), + } +} + +/** + * Live rows first, the most recently started first, then settled rows + * newest-first, so the rows a group holds back past its limit are its oldest. + * Two rows that settled in the same millisecond fall back to start order, so + * the sort never depends on the host's map iteration. + */ +function ordered(jobs: readonly JobView[]): JobView[] { + return [...jobs].sort((left, right) => { + const liveLeft = isLive(left) + if (liveLeft !== isLive(right)) return liveLeft ? -1 : 1 + if (liveLeft) return right.startedAt - left.startedAt + const finished = (right.finishedAt ?? right.startedAt) - (left.finishedAt ?? left.startedAt) + return finished !== 0 ? finished : left.startedAt - right.startedAt + }) +} + +/** + * Two-press kill affordance state: `armed` waits for the confirming second + * press (and disarms on a timer), `pending` covers the in-flight RPC until the + * row's own status flip removes the button, `failed` shows briefly after a + * rejected kill. + */ +type KillState = 'idle' | 'armed' | 'pending' | 'failed' + +/** One job row plus, when observable and expanded, its live output panel. */ +function JobItem({ job, view, expanded, now, onToggle, kill, renderFactorySlot, t }: Pick & { + job: JobView + view: ObservedJob | undefined + expanded: boolean + /** Clock sample live rows derive their running duration from. */ + now: number + onToggle: () => void + /** Present on running rows: the human-kill button state and press handler. */ + kill?: { state: KillState; onPress: () => void } + t: TranslateNS +}) { + const live = isLive(job) + const status = statusLabel(job.status, t) + const detail = jobDetail(job) + const observable = isObservable(job) + const labels = useMemo(() => terminalLabels(t), [t]) + const elapsed = live ? now - job.startedAt : (job.finishedAt ?? job.startedAt) - job.startedAt + const duration = formatDuration(elapsed, t) + const labelRef = useRef(null) + const marquee = useHoverMarquee(labelRef) + const summaryId = useId() + // The stop control names its action in its own tooltip, so the row's hover card stays closed while the pointer is on it. + const [onStop, setOnStop] = useState(false) + const state = detail ?? status + // The row shows the command alone; the kind and state reach assistive technology here and sighted users in the hover card. + const body = ( + <> + + {job.label} + {`${job.kind} · ${state}`} + {duration} + + ) + // The tooltip names the action alone, since the command can run to many lines; the accessible name keeps the command + // to tell the rows' buttons apart. + const killTitle = kill?.state === 'armed' ? t('kill.confirm') : kill?.state === 'failed' ? t('kill.failed') : t('kill.stop') + const killName = kill?.state === 'armed' || kill?.state === 'failed' ? killTitle : t('kill.stopAria', { label: job.label }) + return ( +
  • + {/* The card leaves the command out: it can run to many lines, and the row's output panel shows it in full. */} + + {observable + ? ( + + ) + : {body}} + {kill !== undefined + ? ( + + + + ) + : null} + {/* The row button's overlay takes presses here too; a row without output keeps the column empty. */} + +
  • + )} + /> + {expanded && view !== undefined + ? ( +
    + {view.gapBefore ?
    {t('output.gap')}
    : null} + {view.error !== undefined + ?
    {t('output.error', { error: view.error })}
    + : null} + +
    + ) + : null} + + ) +} + +/** + * Session panel section for this session's background jobs. Mounting it keeps + * the session's roster stream open; it renders nothing until the session can + * see at least one job, so the panel hides the section with its title. Live + * rows come first; settled rows fold under a count that expands and clears + * client-side. Each of the two groups shows five rows and then a fold control + * that shows the rest, once that holds back two rows or more; the choice is + * kept per Session. Expanding an observable row (a live job, or a settled one + * with retained output) starts its observation stream, and collapsing it or + * folding it out of the list stops it — output only flows while someone is + * watching. A running row carries a two-press stop button that requests a + * human kill through the job controller. + * @param props - runtime slot currency, the jobs snapshot hook, the roster, + * observation, and kill controls, the fold store, and the namespace translator. + * @returns the job list, or null when there is nothing to show. + */ +export function JobsSection({ + sessionId, useJobs, watchRows, observe, killJob, useStore, actions, renderFactorySlot, t, useAccess, +}: JobsSectionProps) { + // The stop control follows job/kill; a reader that may list a job but not stop it sees the row only. + const mayKill = useAccess('job/kill') + const jobs = useJobs(state => state.rows[sessionId]) ?? NO_JOBS + const observedViews = useJobs(state => state.observed) + const [expandedKey, setExpandedKey] = useState(undefined) + const [now, setNow] = useState(() => Date.now()) + // Settled-section fold: the user's choice, kept per Session, wins; before one, + // the tail folds only while live work exists (a settled-only list opens expanded). + const settledOpen = useStore(state => state.settledOpen) + // Rows the user cleared from the settled tail (client-side hide only; the + // registry keeps its records and a later settlement reappears normally). + const cleared = useStore(state => state.cleared) + const unfolded = useStore(state => state.unfolded) + // One kill affordance advances at a time: arming a row disarms any other. + const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude } | undefined>(undefined) + + const rows = useMemo(() => ordered(jobs), [jobs]) + const liveRows = useMemo(() => rows.filter(isLive), [rows]) + const settledRows = useMemo( + () => rows.filter(job => !isLive(job) && cleared[String(job.id)] !== true), + [rows, cleared], + ) + const settledExpanded = settledOpen ?? liveRows.length === 0 + // Folding holds back two rows or more, since the fold control takes a row itself. + const liveFoldable = liveRows.length > FOLD_LIMIT + 1 + const shownLive = liveFoldable && !unfolded.live ? liveRows.slice(0, FOLD_LIMIT) : liveRows + const settledFoldable = settledRows.length > FOLD_LIMIT + 1 + const openSettled = settledExpanded ? settledRows : NO_JOBS + const shownSettled = settledFoldable && !unfolded.settled ? openSettled.slice(0, FOLD_LIMIT) : openSettled + + // The roster follows the mounted section: one stream while it lives, released with it. + useEffect(() => watchRows(sessionId), [sessionId, watchRows]) + + // The clock only runs while the list shows something that moves. + useEffect(() => { + if (liveRows.length === 0) return + setNow(Date.now()) + const timer = setInterval(() => { setNow(Date.now()) }, 1_000) + return () => { clearInterval(timer) } + }, [liveRows.length]) + + // Observation follows visibility: the stream opens when an observable panel + // expands and closes when it collapses, its row folds out of the list, or + // the section unmounts. + const expandedRow = expandedKey === undefined + ? undefined + : [...shownLive, ...shownSettled].find(job => String(job.id) === expandedKey) + const activeJob = expandedRow !== undefined && isObservable(expandedRow) ? expandedRow.id : undefined + useEffect(() => { + if (activeJob === undefined) return + return observe(sessionId, activeJob) + }, [sessionId, activeJob, observe]) + + // An armed kill disarms on a timer, and a failed one clears its hint; the + // pending phase instead waits for the RPC (or the row's own status flip). + // The cleanup clears the timer on every phase change, so a firing timer + // always describes the current phase and may reset unconditionally. + useEffect(() => { + if (killPhase === undefined || killPhase.state === 'pending') return + const timer = setTimeout( + () => { setKillPhase(undefined) }, + killPhase.state === 'armed' ? KILL_ARM_MS : KILL_FAILED_MS, + ) + return () => { clearTimeout(timer) } + }, [killPhase]) + + // A phase whose row stopped being killable (settled, stopping, removed) + // has no button to describe any more. + const killable = killPhase !== undefined + && rows.some(job => String(job.id) === killPhase.key && job.status === 'running') + if (killPhase !== undefined && !killable) setKillPhase(undefined) + + const pressKill = (job: JobView): void => { + const key = String(job.id) + if (killPhase?.key !== key || killPhase.state !== 'armed') { + setKillPhase({ key, state: 'armed' }) + return + } + setKillPhase({ key, state: 'pending' }) + void killJob(sessionId, key).then((ok) => { + // An admitted kill stays pending: the unary response (HTTP) and the jobs + // frames (control stream) have no cross-carrier ordering, so re-enabling + // here could offer a duplicate kill while the row still reads `running`. + // The authoritative jobs frame flips the row to `stopping`, which removes + // the button and clears the phase above. + setKillPhase(current => current?.key === key && !ok + ? { key, state: 'failed' } + : current) + }) + } + + if (liveRows.length + settledRows.length === 0) return null + + const clearSettled = (): void => { + actions.cleared(settledRows.map(job => String(job.id))) + if (expandedKey !== undefined && settledRows.some(job => String(job.id) === expandedKey)) { + setExpandedKey(undefined) + } + } + + const item = (job: JobView) => ( + { + setExpandedKey(current => current === String(job.id) ? undefined : String(job.id)) + }} + renderFactorySlot={renderFactorySlot} + {...job.status === 'running' && mayKill + ? { + kill: { + state: killPhase?.key === String(job.id) ? killPhase.state : 'idle' as const, + onPress: () => { pressKill(job) }, + }, + } + : {}} + t={t} + /> + ) + + /** The fold control of one group, as the group's last row. */ + const fold = (group: JobGroup, hidden: number) => { + const label = unfolded[group] ? t('fold.less') : t(`${group}.more`, { count: hidden }) + return ( +
  • + {renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded[group], + label, + name: t(`${group}.foldName`, { label }), + onToggle: () => { actions.unfoldedSet(group, !unfolded[group]) }, + })} +
  • + ) + } + + return ( + // Moving between rows swaps their hover cards without another dwell. + + {/* The section's heading names the region; a list name would repeat it. */} +
      + {shownLive.map(item)} + {liveFoldable ? fold('live', liveRows.length - FOLD_LIMIT) : null} + {settledRows.length > 0 + ? ( +
    • + + +
    • + ) + : null} + {shownSettled.map(item)} + {settledExpanded && settledFoldable ? fold('settled', settledRows.length - FOLD_LIMIT) : null} +
    +
    + ) +} + +/** + * Show on the panel toggle that the Session's background jobs run while the + * panel does not show them. The toggle stays mounted while the section does + * not, so this keeps the Session's roster stream open itself; the client + * service counts its watchers. + * @param props - Session values, the jobs snapshot hook, the roster control, whether the panel shows, and copy. + * @returns the dot with its name for assistive technology, or null with nothing to report. + */ +export function JobsRunningIndicator({ sessionId, panelShown, useJobs, watchRows, t }: JobsRunningIndicatorProps) { + const running = useJobs(state => (state.rows[sessionId] ?? NO_JOBS).filter(isLive).length) + useEffect(() => watchRows(sessionId), [sessionId, watchRows]) + if (panelShown || running === 0) return null + return ( + + {t('indicator.running', { count: running })} + + ) +} diff --git a/packages/client/ui-jobs/src/client/index.ts b/packages/client/ui-jobs/src/client/index.ts index b4595f53cb..2e20caba1d 100644 --- a/packages/client/ui-jobs/src/client/index.ts +++ b/packages/client/ui-jobs/src/client/index.ts @@ -1,17 +1,19 @@ /** - * Background-job plugin, browser half: contributes one session-header action - * that renders this session's jobs. Job rows, per-row observation streams, - * and the human kill all go through the `jobs` client service; this plugin - * holds no transport state of its own. + * Background-job plugin, browser half: contributes the Session panel's + * background-jobs section. Job rows, per-row observation streams, and the + * human kill all go through the `jobs` client service; this plugin holds no + * transport state of its own. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { JobId } from '@deepseek-ai/dsh-jobs/types' -import { JobListAction } from './JobListAction.tsx' -import type { JobListInjected } from './JobListAction.tsx' +import { JobsRunningIndicator, JobsSection } from './JobsSection.tsx' +import type { JobsRunningIndicatorInjected, JobsSectionInjected } from './JobsSection.tsx' +import { createJobsSectionStore } from './jobs-store.ts' import type {} from '@deepseek-ai/dsh-api-job-controller/client' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type JobKey } from './locales.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -21,26 +23,29 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { JobListActionProps, JobListInjected } from './JobListAction.tsx' +export type { JobsRunningIndicatorInjected, JobsRunningIndicatorProps, JobsSectionProps, JobsSectionInjected } from './JobsSection.tsx' /** Required services: the jobs rosters, observations, and kill, the slot registry, and dictionaries. */ export const inject = ['jobs', 'slots', 'locale'] /** - * Client plugin body: register the dictionaries and the header action. + * Client plugin body: register the dictionaries, the Session panel section, and its running dot on the panel toggle. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-jobs: dictionaries') + const t = ctx.locale.bind(NS) ctx.slots.inject( - 'conversation.session.header.actions', + 'conversation.session.panel.section', () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'job-list', - // Background work follows the preset label in the header actions band. - order: 20, + name: 'conversation.session.panel.section', + id: 'background-jobs', + // After change requests (100) and subagents (200). + order: 300, + label: () => t('list.aria'), locale: NS, - inject: (): JobListInjected => ({ + store: createJobsSectionStore(), + inject: (): JobsSectionInjected => ({ hooks: { jobs: ctx.jobs.state }, watchRows: sessionId => ctx.jobs.watchRows(sessionId), observe: (sessionId, id) => ctx.jobs.observe(sessionId, id), @@ -48,6 +53,17 @@ export function apply(ctx: ClientContext): void { // roster stream delivered, so the wire boundary stamps it back here. killJob: async (sessionId, jobId) => (await ctx.jobs.kill(sessionId, jobId as JobId)).ok, }), - }, JobListAction), + }, JobsSection), ) + ctx.slots.inject('conversation.session.panel.indicator', () => ctx.slots.register({ + name: 'conversation.session.panel.indicator', + id: 'background-jobs.running', + // Below an attention mark, which paints above running dots. + order: 20, + locale: NS, + inject: (): JobsRunningIndicatorInjected => ({ + hooks: { jobs: ctx.jobs.state }, + watchRows: sessionId => ctx.jobs.watchRows(sessionId), + }), + }, JobsRunningIndicator)) } diff --git a/packages/client/ui-jobs/src/client/jobs-store.ts b/packages/client/ui-jobs/src/client/jobs-store.ts new file mode 100644 index 0000000000..7c540ba096 --- /dev/null +++ b/packages/client/ui-jobs/src/client/jobs-store.ts @@ -0,0 +1,68 @@ +/** + * Settled rows the user cleared from the background-jobs section, whether the + * user opened or folded the settled rows, and which of the section's two + * groups the user unfolded past their row limit. The registration declares it + * as an exclusive store, so each Session keeps its own while its scope is + * retained, across hiding and showing the panel. + */ + +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' + +/** A group of the section's rows: the live ones, or the settled ones under their fold. */ +export type JobGroup = 'live' | 'settled' + +/** Cleared row keys and the folds of one Session. */ +export interface JobsSectionState { + /** Keys of the settled rows the user cleared. */ + cleared: Record + /** Whether the user opened (true) or folded (false) the settled rows; null until the user chooses. */ + settledOpen: boolean | null + /** Whether each group shows every row instead of holding back the rows past its limit. */ + unfolded: Record +} + +/** The jobs section store's write set. */ +type JobsSectionActions = { + cleared: (draft: JobsSectionState, keys: readonly string[]) => void + settledOpened: (draft: JobsSectionState, open: boolean) => void + unfoldedSet: (draft: JobsSectionState, group: JobGroup, unfolded: boolean) => void +} + +/** + * Declare the jobs section's store. + * @returns the store handle to declare on the registration. + */ +export function createJobsSectionStore(): EngineStoreHandle { + return defineStore({ + init: (): JobsSectionState => ({ cleared: {}, settledOpen: null, unfolded: { live: false, settled: false } }), + actions: { + /** + * Hide settled rows from the section; the registry keeps their records. + * The settled group folds to its limit again for the rows that settle next. + * @param d - draft state. + * @param keys - row keys to hide. + */ + cleared: (d, keys: readonly string[]) => { + for (const key of keys) d.cleared[key] = true + d.unfolded.settled = false + }, + /** + * Record the user's choice to open or fold the settled rows. + * @param d - draft state. + * @param open - whether the settled rows are now open. + */ + settledOpened: (d, open: boolean) => { + d.settledOpen = open + }, + /** + * Record the user's choice to show every row of a group or fold it to its limit again. + * @param d - draft state. + * @param group - the group the choice is about. + * @param unfolded - whether the group now shows every row. + */ + unfoldedSet: (d, group: JobGroup, unfolded: boolean) => { + d.unfolded[group] = unfolded + }, + }, + }) +} diff --git a/packages/client/ui-jobs/src/client/locales.ts b/packages/client/ui-jobs/src/client/locales.ts index c968a08b5d..c34f762133 100644 --- a/packages/client/ui-jobs/src/client/locales.ts +++ b/packages/client/ui-jobs/src/client/locales.ts @@ -5,15 +5,19 @@ export const NS = 'job' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'count.idle.one': '{count} 个后台任务', - 'count.idle.other': '{count} 个后台任务', 'list.aria': '后台任务', - 'section.live': '进行中', + 'indicator.running': '{count} 个后台任务运行中', 'section.settledCount': '已结束 {count}', 'section.clear': '清空', + 'live.more': '显示其余 {count} 个运行中', + 'live.foldName': '{label}(运行中的后台任务)', + 'settled.more': '显示其余 {count} 个已结束', + 'settled.foldName': '{label}(已结束的后台任务)', + 'fold.less': '收起', 'row.expandAria': '展开 {label} 的实时输出', 'row.collapseAria': '收起 {label} 的实时输出', - 'kill.stop': '停止任务 {label}', + 'kill.stop': '停止任务', + 'kill.stopAria': '停止任务 {label}', 'kill.confirm': '再次点击确认停止', 'kill.confirmAction': '确认停止', 'kill.failed': '停止失败', @@ -25,8 +29,6 @@ export const zh = { 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}小时{minutes}分', - 'duration.title.live': '已运行 {duration}', - 'duration.title.done': '耗时 {duration}', 'output.gap': '……较早的输出已丢弃……', 'output.error': '实时输出流中断:{error}', 'terminal.signal': '信号 {signal}', @@ -47,15 +49,19 @@ export const zh = { /** English dictionary, key-identical to the Chinese source of truth. */ export const en: Record = { - 'count.idle.one': '{count} background job', - 'count.idle.other': '{count} background jobs', 'list.aria': 'Background jobs', - 'section.live': 'Running', + 'indicator.running': 'Background jobs running: {count}', 'section.settledCount': 'Finished {count}', 'section.clear': 'Clear', + 'live.more': 'Show {count} more running', + 'live.foldName': '{label} (running background jobs)', + 'settled.more': 'Show {count} more finished', + 'settled.foldName': '{label} (finished background jobs)', + 'fold.less': 'Show less', 'row.expandAria': 'Show live output of {label}', 'row.collapseAria': 'Hide live output of {label}', - 'kill.stop': 'Stop task {label}', + 'kill.stop': 'Stop task', + 'kill.stopAria': 'Stop task {label}', 'kill.confirm': 'Click again to confirm', 'kill.confirmAction': 'Confirm stop', 'kill.failed': 'Stop failed', @@ -67,8 +73,6 @@ export const en: Record = { 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m', - 'duration.title.live': 'Running for {duration}', - 'duration.title.done': 'Took {duration}', 'output.gap': '… earlier output dropped …', 'output.error': 'live output stream interrupted: {error}', 'terminal.signal': 'signal {signal}', @@ -92,15 +96,19 @@ export type JobKey = keyof typeof zh /** Japanese copy, checked against the English keys. */ export const ja = { - 'count.idle.one': 'バックグラウンドジョブ {count} 件', - 'count.idle.other': 'バックグラウンドジョブ {count} 件', 'list.aria': 'バックグラウンドジョブ', - 'section.live': '実行中', + 'indicator.running': '実行中のバックグラウンドジョブ: {count}', 'section.settledCount': '完了 {count} 件', 'section.clear': 'クリア', + 'live.more': '実行中の残り{count}件を表示', + 'live.foldName': '{label}(実行中のバックグラウンドジョブ)', + 'settled.more': '完了した残り{count}件を表示', + 'settled.foldName': '{label}(完了したバックグラウンドジョブ)', + 'fold.less': '折りたたむ', 'row.expandAria': '{label} のライブ出力を表示', 'row.collapseAria': '{label} のライブ出力を非表示', - 'kill.stop': 'タスク {label} を停止', + 'kill.stop': 'タスクを停止', + 'kill.stopAria': 'タスク {label} を停止', 'kill.confirm': 'もう一度クリックして確定', 'kill.confirmAction': '停止を確定', 'kill.failed': '停止に失敗しました', @@ -112,8 +120,6 @@ export const ja = { 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分 {seconds}秒', 'duration.hours': '{hours}時間 {minutes}分', - 'duration.title.live': '実行時間 {duration}', - 'duration.title.done': '所要時間 {duration}', 'output.gap': '…以前の出力は破棄されました…', 'output.error': 'ライブ出力ストリームが中断されました: {error}', 'terminal.signal': 'シグナル {signal}', @@ -134,15 +140,19 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { - 'count.idle.one': 'Tareas en segundo plano: {count}', - 'count.idle.other': 'Tareas en segundo plano: {count}', 'list.aria': 'Trabajos en segundo plano', - 'section.live': 'corriendo', + 'indicator.running': 'Trabajos en segundo plano en ejecución: {count}', 'section.settledCount': 'Terminado {count}', 'section.clear': 'Borrar', + 'live.more': 'Mostrar {count} más en ejecución', + 'live.foldName': '{label} (trabajos en segundo plano en ejecución)', + 'settled.more': 'Mostrar {count} más terminados', + 'settled.foldName': '{label} (trabajos en segundo plano terminados)', + 'fold.less': 'Mostrar menos', 'row.expandAria': 'Mostrar salida en vivo de {label}', 'row.collapseAria': 'Ocultar salida en vivo de {label}', - 'kill.stop': 'Detener tarea {label}', + 'kill.stop': 'Detener tarea', + 'kill.stopAria': 'Detener tarea {label}', 'kill.confirm': 'Haga clic nuevamente para confirmar', 'kill.confirmAction': 'Confirmar parada', 'kill.failed': 'Detener falló', @@ -154,8 +164,6 @@ export const es = { 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m', - 'duration.title.live': 'Corriendo para {duration}', - 'duration.title.done': 'Tomó {duration}', 'output.gap': '… la producción anterior cayó…', 'output.error': 'transmisión de salida en vivo interrumpida: {error}', 'terminal.signal': 'señal {signal}', @@ -176,15 +184,19 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { - 'count.idle.one': 'Tâches en arrière-plan : {count}', - 'count.idle.other': 'Tâches en arrière-plan : {count}', 'list.aria': 'Travaux en arrière-plan', - 'section.live': 'Courir', + 'indicator.running': 'Travaux en arrière-plan en cours : {count}', 'section.settledCount': 'Terminé {count}', 'section.clear': 'Effacer', + 'live.more': 'Afficher {count} de plus en cours', + 'live.foldName': '{label} (travaux en arrière-plan en cours)', + 'settled.more': 'Afficher {count} de plus terminés', + 'settled.foldName': '{label} (travaux en arrière-plan terminés)', + 'fold.less': 'Afficher moins', 'row.expandAria': 'Afficher la sortie en direct de {label}', 'row.collapseAria': 'Masquer la sortie en direct de {label}', - 'kill.stop': 'Arrêter la tâche {label}', + 'kill.stop': 'Arrêter la tâche', + 'kill.stopAria': 'Arrêter la tâche {label}', 'kill.confirm': 'Cliquez à nouveau pour confirmer', 'kill.confirmAction': "Confirmer l'arrêt", 'kill.failed': "L'arrêt a échoué", @@ -196,8 +208,6 @@ export const fr = { 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m', - 'duration.title.live': 'Courir pour {duration}', - 'duration.title.done': 'A pris {duration}', 'output.gap': '… la production antérieure a chuté…', 'output.error': 'flux de sortie en direct interrompu : {error}', 'terminal.signal': 'signal {signal}', @@ -218,15 +228,19 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { - 'count.idle.one': 'Hintergrundaufgaben: {count}', - 'count.idle.other': 'Hintergrundaufgaben: {count}', 'list.aria': 'Hintergrundjobs', - 'section.live': 'Laufen', + 'indicator.running': 'Laufende Hintergrundjobs: {count}', 'section.settledCount': 'Fertig {count}', 'section.clear': 'Klar', + 'live.more': '{count} weitere laufende anzeigen', + 'live.foldName': '{label} (laufende Hintergrundjobs)', + 'settled.more': '{count} weitere beendete anzeigen', + 'settled.foldName': '{label} (beendete Hintergrundjobs)', + 'fold.less': 'Weniger anzeigen', 'row.expandAria': 'Live-Ausgabe von {label} anzeigen', 'row.collapseAria': 'Live-Ausgabe von {label} ausblenden', - 'kill.stop': 'Stoppen Sie die Aufgabe {label}', + 'kill.stop': 'Aufgabe stoppen', + 'kill.stopAria': 'Stoppen Sie die Aufgabe {label}', 'kill.confirm': 'Klicken Sie zur Bestätigung erneut', 'kill.confirmAction': 'Stopp bestätigen', 'kill.failed': 'Stoppen ist fehlgeschlagen', @@ -238,8 +252,6 @@ export const de = { 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m', - 'duration.title.live': 'Laufen für {duration}', - 'duration.title.done': 'Nahm {duration}', 'output.gap': '… frühere Produktion gesunken …', 'output.error': 'Live-Ausgabestream unterbrochen: {error}', 'terminal.signal': 'Signal {signal}', @@ -260,15 +272,19 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { - 'count.idle.one': 'Фоновые задачи: {count}', - 'count.idle.other': 'Фоновые задачи: {count}', 'list.aria': 'Фоновые задания', - 'section.live': 'Бег', + 'indicator.running': 'Выполняется фоновых заданий: {count}', 'section.settledCount': 'Закончено {count}', 'section.clear': 'Очистить', + 'live.more': 'Показать ещё {count} выполняющихся', + 'live.foldName': '{label} (выполняющиеся фоновые задания)', + 'settled.more': 'Показать ещё {count} завершённых', + 'settled.foldName': '{label} (завершённые фоновые задания)', + 'fold.less': 'Свернуть', 'row.expandAria': 'Показать живой вывод {label}', 'row.collapseAria': 'Скрыть прямой вывод {label}', - 'kill.stop': 'Остановить задачу {label}', + 'kill.stop': 'Остановить задачу', + 'kill.stopAria': 'Остановить задачу {label}', 'kill.confirm': 'Нажмите еще раз, чтобы подтвердить', 'kill.confirmAction': 'Подтвердить остановку', 'kill.failed': 'Остановить не удалось', @@ -280,8 +296,6 @@ export const ru = { 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m', - 'duration.title.live': 'Бегу за {duration}', - 'duration.title.done': 'Взял {duration}', 'output.gap': '… ранее объемы производства упали …', 'output.error': 'поток вывода в реальном времени прерван: {error}', 'terminal.signal': 'сигнал {signal}', @@ -302,15 +316,19 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { - 'count.idle.one': 'Tarefas em segundo plano: {count}', - 'count.idle.other': 'Tarefas em segundo plano: {count}', 'list.aria': 'Trabalhos em segundo plano', - 'section.live': 'Correndo', + 'indicator.running': 'Trabalhos em segundo plano em execução: {count}', 'section.settledCount': 'Concluído {count}', 'section.clear': 'Limpar', + 'live.more': 'Mostrar mais {count} em execução', + 'live.foldName': '{label} (trabalhos em segundo plano em execução)', + 'settled.more': 'Mostrar mais {count} concluídos', + 'settled.foldName': '{label} (trabalhos em segundo plano concluídos)', + 'fold.less': 'Mostrar menos', 'row.expandAria': 'Mostrar saída ao vivo de {label}', 'row.collapseAria': 'Ocultar saída ao vivo de {label}', - 'kill.stop': 'Parar tarefa {label}', + 'kill.stop': 'Parar tarefa', + 'kill.stopAria': 'Parar tarefa {label}', 'kill.confirm': 'Clique novamente para confirmar', 'kill.confirmAction': 'Confirmar parada', 'kill.failed': 'Falha na parada', @@ -322,8 +340,6 @@ export const pt = { 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m', - 'duration.title.live': 'Correndo por {duration}', - 'duration.title.done': 'Levou {duration}', 'output.gap': '… a produção anterior caiu…', 'output.error': 'transmissão ao vivo interrompida: {error}', 'terminal.signal': 'sinal {signal}', diff --git a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts index 73092ce046..ee6ae6fb4d 100644 --- a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts @@ -10,17 +10,18 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { describe, expect, it } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '../src/client/index.ts' -import type { JobListInjected } from '../src/client/JobListAction.tsx' +import type { JobsRunningIndicatorInjected, JobsSectionInjected } from '../src/client/JobsSection.tsx' import { apply as applyNode } from '../src/index.ts' import { en, NS, zh } from '../src/client/locales.ts' -/** Slot ledger reader: entry ids currently registered in the header list. */ -function headerEntryIds(ctx: Context): (string | undefined)[] { +/** Slot ledger reader: entry ids currently registered in the Session panel section list. */ +function sectionEntryIds(ctx: Context): (string | undefined)[] { return ctx.slots - .entries('conversation.session.header.actions') + .entries('conversation.session.panel.section') .map(entry => entry.options.id) } @@ -40,7 +41,8 @@ async function bench(): Promise<{ ctx: Context; fiber: ReturnType null) ctx.provide('jobs', { @@ -81,10 +83,10 @@ describe('ui-jobs browser half', () => { it('exposes the jobs source and the roster, observation, and kill controls through the inject face', async () => { const { ctx } = await bench() const entry = ctx.slots - .entries('conversation.session.header.actions') - .find(candidate => candidate.options.id === 'job-list') - const inject = entry?.inject as (() => JobListInjected) | undefined - if (inject === undefined) throw new Error('job-list entry registered no inject face') + .entries('conversation.session.panel.section') + .find(candidate => candidate.options.id === 'background-jobs') + const inject = entry?.inject as (() => JobsSectionInjected) | undefined + if (inject === undefined) throw new Error('background-jobs entry registered no inject face') const face = inject() expect(face.hooks.jobs).toBeDefined() const release = face.watchRows(brandString('session')) @@ -103,11 +105,20 @@ describe('ui-jobs browser half', () => { expect(kills).toEqual([['sess-live', 'bash-3'], ['sess-live', 'bash-4']]) }) - it('registers the header action, and fiber teardown removes it (HMR safety)', async () => { + it('registers the Session panel section, and fiber teardown removes it (HMR safety)', async () => { const { ctx, fiber } = await bench() - expect(headerEntryIds(ctx)).toContain('job-list') + expect(sectionEntryIds(ctx)).toContain('background-jobs') + const entry = ctx.slots.entries('conversation.session.panel.section').find(candidate => candidate.options.id === 'background-jobs') + expect(entry?.options.order).toBe(300) + expect(resolveSlotLabel(entry?.options.label)).toBe(zh['list.aria']) + const dot = ctx.slots.entries('conversation.session.panel.indicator')[0] + expect(dot).toMatchObject({ options: { id: 'background-jobs.running', order: 20 } }) + const face = dot?.inject as (() => JobsRunningIndicatorInjected) | undefined + face?.().watchRows('dot-session' as SessionId)() + expect(watched).toContain('dot-session') await fiber.dispose() - expect(headerEntryIds(ctx)).not.toContain('job-list') + expect(sectionEntryIds(ctx)).not.toContain('background-jobs') + expect(ctx.slots.entries('conversation.session.panel.indicator')).toHaveLength(0) }) it('registers both dictionaries under its own namespace and releases them with the fiber', async () => { diff --git a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx deleted file mode 100644 index 5bbf91ace5..0000000000 --- a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx +++ /dev/null @@ -1,950 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' -import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { JobListAction, type JobListActionProps } from '../src/client/JobListAction.tsx' -import { zh, en, ja, es, fr, de, ru, pt } from '../src/client/locales.ts' - -beforeEach(() => { - class TooltipObserver implements ResizeObserver { - constructor(private readonly callback: ResizeObserverCallback) {} - observe(target: Element): void { - const size = { inlineSize: 160, blockSize: 30 } - this.callback([{ - target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), - }], this) - } - unobserve(): void {} - disconnect(): void {} - } - vi.stubGlobal('ResizeObserver', TooltipObserver) - vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) -}) - -beforeEach(() => { - vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) -}) - -afterEach(() => { - cleanup() - vi.restoreAllMocks() - vi.unstubAllGlobals() - vi.useRealTimers() -}) - -const SESSION = 'session' as SessionId -const t: JobListActionProps['t'] = makeTranslate(zh) - -/** A running job with nothing retained yet. */ -function job(over: Partial = {}): JobView { - return { - id: 'bash-1' as JobView['id'], - kind: 'bash', - label: 'pnpm run build', - status: 'running', - startedAt: 1_700_000_000_000, - output: { total: 0, earliest: 0 }, - ...over, - } -} - -/** A job that left retained output behind, so its row offers a panel even once settled. */ -function outputJob(over: Partial = {}): JobView { - return job({ output: { total: 12, earliest: 0 }, ...over }) -} - -function props( - jobs: readonly JobView[], - observe: JobListActionProps['observe'] = () => () => {}, - observed: Readonly> = {}, - killJob: JobListActionProps['killJob'] = async () => true, - watchRows: JobListActionProps['watchRows'] = () => () => {}, -): JobListActionProps { - const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed } - function useJobs(select: (value: JobsSnapshot) => T): T { - return select(jobsState) - } - return { sessionId: SESSION, useJobs, watchRows, observe, killJob, t } as JobListActionProps -} - -function openList(): void { - fireEvent.click(screen.getAllByRole('button')[0]!) -} - -describe('JobListAction count copy', () => { - it.each([ - [zh, '1 个后台任务', '2 个后台任务'], - [en, '1 background job', '2 background jobs'], - [ja, 'バックグラウンドジョブ 1 件', 'バックグラウンドジョブ 2 件'], - [es, 'Tareas en segundo plano: 1', 'Tareas en segundo plano: 2'], - [fr, 'Tâches en arrière-plan : 1', 'Tâches en arrière-plan : 2'], - [de, 'Hintergrundaufgaben: 1', 'Hintergrundaufgaben: 2'], - [ru, 'Фоновые задачи: 1', 'Фоновые задачи: 2'], - [pt, 'Tarefas em segundo plano: 1', 'Tarefas em segundo plano: 2'], - ] as const)('uses neutral count copy for live and settled jobs in locale %#', (dictionary, one, two) => { - const translate: JobListActionProps['t'] = makeTranslate(dictionary) - const settled = job({ id: 'settled' as JobView['id'], status: 'completed', finishedAt: 1_700_000_003_000 }) - const { rerender } = render() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: two, description: '' })).toBeDefined() - }) -}) - -describe('JobListAction visibility', () => { - it('renders nothing while the session sees no jobs', () => { - const { container } = render() - expect(container.innerHTML).toBe('') - }) - - it('watches the session roster while mounted and releases it on unmount', () => { - const stop = vi.fn() - const watchRows = vi.fn(() => stop) - const { unmount } = render() - expect(watchRows).toHaveBeenCalledWith(SESSION) - expect(stop).not.toHaveBeenCalled() - unmount() - expect(stop).toHaveBeenCalledTimes(1) - }) - - it('counts live jobs on the trigger', () => { - render() - expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined() - }) - - it('retains the compact Layers icon through running, stopping, and idle states without a root chevron', () => { - const { rerender } = render() - const trigger = screen.getByRole('button') - expect(trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]')).not.toBeNull() - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - expect(trigger.querySelector('[data-icon="dsw-icon-chevron-down-outline-regular"]')).toBeNull() - rerender() - expect(screen.getByRole('button')).toBe(trigger) - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - rerender() - expect(screen.getByRole('button')).toBe(trigger) - expect(trigger.querySelector('[data-state="ongoing"]')).toBeNull() - const icon = trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]') - expect(icon?.getAttribute('width')).toBe('14') - expect(trigger.querySelectorAll('svg')).toHaveLength(1) - }) - - it('falls back to the total when nothing is live', () => { - render() - expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined() - }) -}) - -describe('JobListAction hover', () => { - function pointer(target: Element, type: 'pointerover' | 'pointerout', pointerType = 'mouse'): void { - // jsdom lacks PointerEvent; preserve its pointer type on the native event. - const event = new MouseEvent(type, { bubbles: true }) - Object.defineProperty(event, 'pointerType', { value: pointerType }) - fireEvent(target, event) - } - - function advance(ms: number): void { - act(() => { vi.advanceTimersByTime(ms) }) - } - - function hoverOpen(): HTMLElement { - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - pointer(trigger, 'pointerover') - advance(149) - expect(screen.queryByRole('list')).toBeNull() - advance(1) - expect(trigger.getAttribute('aria-expanded')).toBe('true') - return trigger - } - - it('keeps the compact trigger click-only and shows its count tooltip after 500ms', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[data-job-count]')! - count.style.display = 'none' - pointer(trigger, 'pointerover') - advance(499) - expect(screen.queryByRole('list')).toBeNull() - expect(screen.queryByRole('tooltip')).toBeNull() - advance(1) - expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') - fireEvent.click(trigger) - expect(screen.queryByRole('tooltip')).toBeNull() - pointer(trigger, 'pointerout') - advance(500) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('cancels pending wide hover when CSS hides the count and compact clicks close hover-opened lists', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[data-job-count]')! - pointer(trigger, 'pointerover') - advance(100) - count.style.display = 'none' - advance(50) - expect(screen.queryByRole('list')).toBeNull() - pointer(trigger, 'pointerout') - count.style.display = '' - hoverOpen() - count.style.display = 'none' - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('shows count on keyboard focus immediately and opens and pins with ArrowDown', async () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - trigger.querySelector('[data-job-count]')!.style.display = 'none' - fireEvent.keyDown(document.body, { key: 'Tab' }) - act(() => { trigger.focus() }) - expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') - fireEvent.keyDown(trigger, { key: 'ArrowDown' }) - await act(async () => { vi.runAllTicks() }) - expect(screen.queryByRole('tooltip')).toBeNull() - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - expect(document.activeElement).toBe(row) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('list')).toBeNull() - expect(document.activeElement).toBe(trigger) - }) - - it('waits for hover, bridges the portal gap, and closes after leaving both surfaces', () => { - vi.useFakeTimers() - const observe = vi.fn(() => () => {}) - const { container } = render() - const trigger = hoverOpen() - const menu = screen.getByRole('list').parentElement! - expect(container.contains(menu)).toBe(false) - expect(observe).not.toHaveBeenCalled() - pointer(trigger, 'pointerout') - advance(119) - pointer(menu, 'pointerover') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - pointer(menu, 'pointerout') - advance(119) - expect(screen.getByRole('list')).toBeDefined() - advance(1) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('cancels short hover and preserves a returning pointer during leave grace', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover') - advance(149) - pointer(trigger, 'pointerout') - advance(150) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - pointer(trigger, 'pointerout') - advance(100) - pointer(trigger, 'pointerover') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - }) - - it('pins a hover-opened list on click until explicit dismissal', () => { - vi.useFakeTimers() - render() - const trigger = hoverOpen() - fireEvent.click(trigger) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - fireEvent.click(trigger) - fireEvent.pointerDown(document.body) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - pointer(trigger, 'pointerout') - advance(120) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('ignores touch hover while keeping tap usable', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover', 'touch') - advance(150) - expect(screen.queryByRole('list')).toBeNull() - fireEvent.click(trigger) - pointer(trigger, 'pointerout', 'touch') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('pins keyboard focus and releases expanded output on Escape or hover close', () => { - vi.useFakeTimers() - const stop = vi.fn() - const observe = vi.fn(() => stop) - render() - const trigger = hoverOpen() - pointer(trigger, 'pointerout') - act(() => { trigger.focus() }) - fireEvent.keyDown(trigger, { key: 'Tab' }) - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - expect(document.activeElement).toBe(row) - advance(120) - fireEvent.click(row) - expect(observe).toHaveBeenCalledTimes(1) - fireEvent.keyDown(row, { key: 'Escape' }) - expect(document.activeElement).toBe(trigger) - expect(stop).toHaveBeenCalledTimes(1) - hoverOpen() - expect(observe).toHaveBeenCalledTimes(2) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.queryByRole('list')).toBeNull() - expect(stop).toHaveBeenCalledTimes(2) - }) - - it('pins pointer interaction so leaving cannot interrupt stop confirmation', () => { - vi.useFakeTimers() - render() - const trigger = hoverOpen() - pointer(trigger, 'pointerout') - const stop = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) - fireEvent.pointerDown(stop) - fireEvent.click(stop) - pointer(screen.getByRole('list').parentElement!, 'pointerout') - advance(120) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByRole('list')).toBeDefined() - }) - - it('dismisses a hover-opened list with Escape while focus is elsewhere', () => { - vi.useFakeTimers() - render() - hoverOpen() - fireEvent.keyDown(document.body, { key: 'a' }) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.keyDown(document.body, { key: 'Escape' }) - expect(screen.queryByRole('list')).toBeNull() - }) - - it.each(['opening', 'closing'] as const)('cleans up a pending %s timer on unmount', (phase) => { - vi.useFakeTimers() - const { unmount } = render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover') - if (phase === 'closing') { - advance(150) - pointer(trigger, 'pointerout') - } - unmount() - expect(vi.getTimerCount()).toBe(0) - advance(150) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('releases expanded output and pending hover close before showing another session', () => { - vi.useFakeTimers() - const stop = vi.fn() - const observe = vi.fn(() => stop) - const first = props([outputJob()], observe) - const { rerender } = render() - const trigger = hoverOpen() - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - fireEvent.click(row) - expect(observe).toHaveBeenCalledTimes(1) - pointer(trigger, 'pointerout') - const nextId = 'next-session' as SessionId - rerender( select({ rows: { [nextId]: [outputJob()] }, observed: {} })} - />) - expect(stop).toHaveBeenCalledTimes(1) - expect(observe).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - hoverOpen() - advance(120) - expect(screen.getByRole('list')).toBeDefined() - expect(observe).toHaveBeenLastCalledWith(nextId, 'bash-1') - }) - - it('cancels pending hover and clears pins on session change or an empty roster', () => { - vi.useFakeTimers() - const first = props([job()]) - const nextId = 'next-session' as SessionId - const next: JobListActionProps = { - ...first, - sessionId: nextId, - useJobs: select => select({ rows: { [nextId]: [job()] }, observed: {} }), - } - const { rerender } = render() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(screen.queryByRole('list')).toBeNull() - const trigger = hoverOpen() - fireEvent.click(trigger) - rerender() - expect(screen.queryByRole('list')).toBeNull() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(vi.getTimerCount()).toBe(0) - rerender() - hoverOpen() - fireEvent.click(screen.getByRole('button', { name: '1 个后台任务' })) - rerender() - rerender() - expect(screen.queryByRole('list')).toBeNull() - }) -}) - -describe('JobListAction rows', () => { - it('renders a settled job without retained output as a static row', () => { - render() - expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined() - openList() - expect(screen.getByText('explore the repo')).toBeDefined() - expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull() - }) - - it('offers a panel on a live row before any output arrived', () => { - render() - openList() - expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined() - }) - - it('shows the live progress line in place of the status word', () => { - render() - openList() - const list = screen.getByRole('list', { name: zh['list.aria'] }) - expect(within(list).getByText('pnpm run build')).toBeDefined() - expect(within(list).getByText('winding down')).toBeDefined() - }) - - it('folds the settled tail behind its count while live work exists, and clears on demand', () => { - const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })] - render() - openList() - expect(screen.getByText(zh['section.live'], { selector: 'li' })).toBeDefined() - const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) - // Folded by default while something runs; the toggle expands it. - expect(toggle.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText('settled work')).toBeNull() - fireEvent.click(toggle) - expect(screen.getByText('settled work')).toBeDefined() - // Clearing hides the tail client-side and drops the whole section line. - fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) - expect(screen.queryByText('settled work')).toBeNull() - expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull() - }) - - it('opens the settled tail by default when nothing is live', () => { - render() - openList() - expect(screen.getByText('pnpm run build')).toBeDefined() - expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true') - }) - - it('clearing drops an expanded settled panel with its rows', () => { - const observe = vi.fn(() => () => {}) - render() - openList() - // Nothing live: the tail is open; expand the settled row's output panel. - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') })) - expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2') - fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) - expect(screen.queryByText('settled work')).toBeNull() - expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull() - }) - - it('shows a settled duration and ticks a live one', () => { - vi.useFakeTimers({ now: 1_700_000_020_000 }) - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) - expect(screen.getByText('5秒')).toBeDefined() - expect(screen.getByText('12秒')).toBeDefined() - expect(screen.getByText('1小时3分')).toBeDefined() - expect(screen.getByText('1分12秒')).toBeDefined() - act(() => { vi.advanceTimersByTime(1_000) }) - expect(screen.getByText('6秒')).toBeDefined() - }) - - it('lists rows with kind, label, and detail-or-status', () => { - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - const items = within(list).getAllByRole('listitem') - // The section line is a listitem too now: live row, section, settled row. - expect(items).toHaveLength(3) - expect(items[0]?.textContent).toContain('pnpm run build') - // A live row's second line is kind · duration; the status word only - // appears through a detail (none while running). - expect(items[0]?.textContent).toMatch(/小时|分|秒/) - expect(items[2]?.textContent).toContain('exit code: 3') - }) - - it('orders live rows first by start and settled rows newest-first with tie-breaks', () => { - const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView => - job({ - id: id as JobView['id'], - label, - status: 'completed', - startedAt, - ...finishedAt !== undefined ? { finishedAt } : {}, - }) - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') })) - const labels = within(screen.getByRole('list', { name: zh['list.aria'] })) - .getAllByRole('listitem') - .map(item => item.querySelector('[title]')?.getAttribute('title')) - .filter((title): title is string => title != null && !title.startsWith('已运行') && !title.startsWith('耗时')) - expect(labels).toEqual([ - 'live-2', 'live-1', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e', - ]) - expect(screen.getAllByText(zh['status.completed']).length).toBeGreaterThan(0) - }) - - it('breaks a settled tie on start order so map iteration never decides it', () => { - render() - openList() - expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[title]')?.getAttribute('title')).filter(title => title !== undefined)) - .toEqual(['first', 'second']) - }) - - it('prefers the producer detail over the generic status word', () => { - render() - openList() - expect(within(screen.getByRole('list')).getByText('signal: SIGTERM')).toBeDefined() - }) - - it('renders settled status words and every lifecycle indicator', () => { - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) - for (const word of ['已完成', '已取消', '已失败']) { - expect(within(screen.getByRole('list')).getByText(word)).toBeDefined() - } - expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state'))) - .toEqual(['ongoing', 'warning', 'done', 'warning', 'error']) - }) -}) - -describe('JobListAction observation', () => { - it('marks killed rows, renders every output line unfolded, and copies the command', async () => { - const writeText = vi.fn().mockResolvedValue(undefined) - Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) - const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n') - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: lines, - gapBefore: false, - streaming: false, - } - render() - openList() - expect(screen.getByText(zh['status.killed'])).toBeDefined() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - // The panel scrolls instead of folding: every line renders, no fold control. - expect(screen.getByText('line 1')).toBeDefined() - expect(screen.getByText('line 24')).toBeDefined() - expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull() - // The panel draws no state dot or label of its own — the row carries it. - expect(screen.queryByText(zh['terminal.done'])).toBeNull() - // The copy control carries the command, not the output. - await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) }) - expect(writeText).toHaveBeenCalledWith('pnpm run build') - }) - - it('anchors the portaled list with CSS without reading geometry on resize or ancestor scroll', () => { - const { container } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - const anchor = trigger.closest('div')! - const measure = vi.spyOn(anchor, 'getBoundingClientRect') - fireEvent.click(trigger) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - const menu = list.closest('[data-menu-material]')! - expect(menu.parentElement).toBe(document.body) - expect(container.contains(list)).toBe(false) - expect(anchor.style.anchorName).not.toBe('') - expect(menu.style.positionAnchor).toBe(anchor.style.anchorName) - expect(menu.style.left).toBe('') - expect(menu.style.top).toBe('') - fireEvent(window, new Event('resize')) - fireEvent.scroll(container) - expect(menu.style.positionAnchor).toBe(anchor.style.anchorName) - expect(measure).not.toHaveBeenCalled() - }) - - it('gives independent job controls separate CSS anchors', () => { - render(<>) - const triggers = screen.getAllByRole('button', { name: '1 个后台任务' }) - const first = triggers[0]!.closest('div')! - const second = triggers[1]!.closest('div')! - expect(first.style.anchorName).not.toBe('') - expect(second.style.anchorName).not.toBe('') - expect(first.style.anchorName).not.toBe(second.style.anchorName) - }) - - it('keeps visual viewport changes out of inline placement and closes normally', () => { - const viewport = Object.assign(new EventTarget(), { width: 600, height: 500, offsetLeft: 40, offsetTop: 60 }) - vi.stubGlobal('visualViewport', viewport) - const listen = vi.spyOn(viewport, 'addEventListener') - render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - fireEvent.click(trigger) - const menu = screen.getByRole('list', { name: zh['list.aria'] }).closest('[data-menu-material]')! - const placement = menu.style.positionAnchor - act(() => { - viewport.offsetLeft = 100 - viewport.offsetTop = 120 - viewport.dispatchEvent(new Event('scroll')) - viewport.height = 200 - viewport.dispatchEvent(new Event('resize')) - }) - expect(menu.style.positionAnchor).toBe(placement) - expect(menu.style.left).toBe('') - expect(menu.style.top).toBe('') - expect(menu.style.getPropertyValue('--dsh-anchored-max-width')).toBe('') - expect(menu.style.getPropertyValue('--dsh-anchored-max-height')).toBe('') - expect(listen).not.toHaveBeenCalled() - fireEvent.click(trigger) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - }) - - it('keeps portaled controls interactive and releases observation on dismissal and unmount', () => { - const stop = vi.fn() - const observe = vi.fn(() => stop) - const { container, unmount } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - trigger.focus() - fireEvent.click(trigger) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - expect(container.contains(list)).toBe(false) - const row = screen.getByRole('button', { - name: zh['row.expandAria'].replace('{label}', 'pnpm run build'), - }) - fireEvent.pointerDown(row) - fireEvent.click(row) - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) - expect(observe).toHaveBeenCalledTimes(1) - expect(stop).not.toHaveBeenCalled() - const kill = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) - fireEvent.pointerDown(kill) - fireEvent.click(kill) - expect(kill.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) - - row.focus() - fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(document.activeElement).toBe(trigger) - expect(stop).toHaveBeenCalledTimes(1) - fireEvent.click(trigger) - expect(observe).toHaveBeenCalledTimes(2) - fireEvent.pointerDown(document.body) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(stop).toHaveBeenCalledTimes(2) - fireEvent.click(trigger) - expect(observe).toHaveBeenCalledTimes(3) - const reopened = screen.getByRole('list', { name: zh['list.aria'] }) - unmount() - expect(document.body.contains(reopened)).toBe(false) - expect(stop).toHaveBeenCalledTimes(3) - }) - - it('ignores other keys while open and closes once the roster empties', () => { - const settledPair = [ - outputJob({ id: 'bash-1' as JobView['id'], status: 'completed', finishedAt: 2 }), - outputJob({ id: 'bash-2' as JobView['id'], status: 'completed', finishedAt: 3 }), - ] - const { rerender } = render() - expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined() - openList() - const list = screen.getByRole('list', { name: zh['list.aria'] }) - fireEvent.keyDown(list, { key: 'a' }) - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBeDefined() - // The roster emptying unmounts the control entirely; the open flag resets first. - rerender() - expect(screen.queryByRole('button')).toBeNull() - }) - - it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => { - const stop = vi.fn() - const observe = vi.fn(() => stop) - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: 'compiling…\n', - gapBefore: false, - streaming: true, - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1') - expect(screen.getByText('compiling…')).toBeDefined() - - fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') })) - expect(stop).toHaveBeenCalledTimes(1) - }) - - it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => { - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: '', - gapBefore: false, - streaming: true, - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(screen.getByRole('list', { name: zh['list.aria'] }).querySelector('[data-running]')).not.toBeNull() - expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull() - }) - - it('surfaces retention gaps and stream failures above the panel', () => { - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: 'tail only', - gapBefore: true, - streaming: false, - error: 'connection lost', - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(screen.getByText(zh['output.gap'])).toBeDefined() - expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined() - }) - - it('bridges Tab between the trigger and the portaled list and closes on Escape', () => { - render() - const trigger = screen.getAllByRole('button')[0]! - fireEvent.keyDown(trigger, { key: 'Tab' }) - openList() - const [first, last] = within(screen.getByRole('list', { name: zh['list.aria'] })).getAllByRole('button') - trigger.focus() - // Shift+Tab from the trigger leaves toward the controls before it. - expect(fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true })).toBe(true) - expect(document.activeElement).toBe(trigger) - // Tab from the trigger enters the list. - expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(first) - // Inside the list Tab stays the browser's until an end is reached. - expect(fireEvent.keyDown(first!, { key: 'Tab' })).toBe(true) - // Tab off the last control resumes from the trigger's place in the page. - expect(fireEvent.keyDown(last!, { key: 'Tab' })).toBe(true) - expect(document.activeElement).toBe(trigger) - // Shift+Tab off the first control returns to the trigger itself. - first!.focus() - expect(fireEvent.keyDown(first!, { key: 'Tab', shiftKey: true })).toBe(false) - expect(document.activeElement).toBe(trigger) - first!.focus() - fireEvent.keyDown(first!, { key: 'Escape' }) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(document.activeElement).toBe(trigger) - }) - - it('stops observation when the popover closes via Escape', () => { - const stop = vi.fn() - render( stop)} />) - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - fireEvent.keyDown(screen.getByRole('list', { name: zh['list.aria'] }), { key: 'Escape' }) - expect(stop).toHaveBeenCalledTimes(1) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - }) - - it('folds an expanded panel whose row left the roster', () => { - const stop = vi.fn() - // One stable observe identity across renders, as the inject face provides. - const observe = () => stop - const { rerender } = render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - rerender() - expect(stop).toHaveBeenCalledTimes(1) - expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull() - }) -}) - -describe('JobListAction human kill', () => { - const stopTitle = (label: string): string => zh['kill.stop'].replace('{label}', label) - - it('offers the stop control only on running rows', () => { - render() - openList() - expect(screen.getByTitle(stopTitle('pnpm run build'))).toBeDefined() - expect(screen.queryByTitle(stopTitle('done'))).toBeNull() - }) - - it('arms on the first press and kills on the confirming press', async () => { - const killJob = vi.fn(async () => true) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(killJob).not.toHaveBeenCalled() - expect(stop.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByTitle(zh['kill.confirm'])).toBe(stop) - // The armed step is legible without hover: the button carries the label. - expect(stop.textContent).toBe(zh['kill.confirmAction']) - await act(async () => { fireEvent.click(stop) }) - expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1') - // An admitted kill stays pending: the unary response and the jobs frames - // have no cross-carrier ordering, so only the authoritative frame (the row - // leaving the killable set) releases the control — never the response. - expect(stop.getAttribute('data-kill-state')).toBe('pending') - expect(stop.hasAttribute('disabled')).toBe(true) - }) - - it('an armed press disarms after the confirmation window', () => { - vi.useFakeTimers() - const killJob = vi.fn(async () => true) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - act(() => { vi.advanceTimersByTime(3_000) }) - expect(stop.getAttribute('data-kill-state')).toBe('idle') - expect(killJob).not.toHaveBeenCalled() - }) - - it('a rejected kill shows its hint and then resets', async () => { - // Fake timers from the start so the failed-hint reset arms on the fake clock. - vi.useFakeTimers() - const killJob = vi.fn(async () => false) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - await act(async () => { fireEvent.click(stop) }) - expect(stop.getAttribute('data-kill-state')).toBe('failed') - expect(screen.getByTitle(zh['kill.failed'])).toBe(stop) - act(() => { vi.advanceTimersByTime(4_000) }) - expect(stop.getAttribute('data-kill-state')).toBe('idle') - }) - - it('arming a second row disarms the first', () => { - render() - openList() - const first = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(first) - expect(first.getAttribute('data-kill-state')).toBe('armed') - const second = screen.getByTitle(stopTitle('pnpm run watch')) - fireEvent.click(second) - expect(second.getAttribute('data-kill-state')).toBe('armed') - expect(first.getAttribute('data-kill-state')).toBe('idle') - }) - - it('a kill resolving after another row armed leaves the newer phase alone', async () => { - let resolveKill!: (ok: boolean) => void - const killJob = vi.fn(() => new Promise((resolve) => { resolveKill = resolve })) - render() - openList() - const first = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(first) - fireEvent.click(first) - expect(killJob).toHaveBeenCalledTimes(1) - // While the first kill is in flight, the user arms the second row; the - // late resolution must not clobber that newer phase. - const second = screen.getByTitle(stopTitle('pnpm run watch')) - fireEvent.click(second) - expect(second.getAttribute('data-kill-state')).toBe('armed') - await act(async () => { resolveKill(false) }) - expect(second.getAttribute('data-kill-state')).toBe('armed') - expect(first.getAttribute('data-kill-state')).toBe('idle') - }) - - it('clears an armed phase whose row stopped being killable', () => { - const { rerender } = render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - rerender() - // The stopping row offers no kill control any more, and the stale phase is gone. - expect(screen.queryByTitle(stopTitle('pnpm run build'))).toBeNull() - expect(document.querySelector('[data-kill-state]')).toBeNull() - }) -}) - -it.each([1, 2, 5, 21])('renders count-independent Russian labels for %i jobs', (count) => { - const jobs = Array.from({ length: count }, (_, i) => job({ id: `job-${i}` as JobView['id'] })) - const translate: JobListActionProps['t'] = makeTranslate(ru) - const view = render() - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() - view.rerender( ({ ...item, status: 'completed', finishedAt: 1_700_000_003_000 })))} t={translate} />) - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() -}) diff --git a/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx new file mode 100644 index 0000000000..a90eb6236f --- /dev/null +++ b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx @@ -0,0 +1,759 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useSyncExternalStore } from 'react' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { JobsRunningIndicator, JobsSection, type JobsRunningIndicatorProps, type JobsSectionProps } from '../src/client/JobsSection.tsx' +import { createJobsSectionStore } from '../src/client/jobs-store.ts' +import { en, zh, ru } from '../src/client/locales.ts' +import type { PanelDetailsProps, PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' + +beforeEach(() => { + class TooltipObserver implements ResizeObserver { + constructor(private readonly callback: ResizeObserverCallback) {} + observe(target: Element): void { + const size = { inlineSize: 160, blockSize: 30 } + this.callback([{ + target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), + }], this) + } + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', TooltipObserver) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) +}) + +beforeEach(() => { + vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +const SESSION = 'session' as SessionId +const t: JobsSectionProps['t'] = makeTranslate(zh) + +/** A running job with nothing retained yet. */ +function job(over: Partial = {}): JobView { + return { + id: 'bash-1' as JobView['id'], + kind: 'bash', + label: 'pnpm run build', + status: 'running', + startedAt: 1_700_000_000_000, + output: { total: 0, earliest: 0 }, + ...over, + } +} + +/** A job that left retained output behind, so its row offers a panel even once settled. */ +function outputJob(over: Partial = {}): JobView { + return job({ output: { total: 12, earliest: 0 }, ...over }) +} + +/** One Session's section store, as the registration mints it. */ +type SectionStore = ReturnType['create']> + +/** + * The Session panel's Factories as this suite renders them: the fold control as a button with its state, name, and + * label, and a row's details as one element per part in order. ui-session-panel's own suite owns their markup. + */ +function renderPanelFactory(name: string, input: object) { + if (name === 'conversation.session.panel.details') { + const { title, lines = [], status, facts = [] } = input as PanelDetailsProps + return ( +
    + {title !== undefined &&
    {title}
    } + {lines.map(line =>
    {line}
    )} + {status !== undefined &&
    {status.label}
    } + {facts.length > 0 &&
    {facts.map(fact => {fact.label})}
    } +
    + ) + } + const fold = input as PanelFoldProps + return +} + +/** Test-local selector hook over a framework-neutral store instance. */ +function hookOf(instance: { subscribe: (listener: () => void) => () => void; getSnapshot: () => T }) { + return function useSelector(select: (state: T) => S): S { + return select(useSyncExternalStore(instance.subscribe, instance.getSnapshot)) + } +} + +function props( + jobs: readonly JobView[], + observe: JobsSectionProps['observe'] = () => () => {}, + observed: Readonly> = {}, + killJob: JobsSectionProps['killJob'] = async () => true, + watchRows: JobsSectionProps['watchRows'] = () => () => {}, + store: SectionStore = createJobsSectionStore().create(), + mayKill = true, +): JobsSectionProps { + const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed } + function useJobs(select: (value: JobsSnapshot) => T): T { + return select(jobsState) + } + return { + sessionId: SESSION, useJobs, watchRows, observe, killJob, useStore: hookOf(store), actions: store.actions, t, + useAccess: () => mayKill, renderFactorySlot: renderPanelFactory, + } as Pick as JobsSectionProps +} + +describe('JobsRunningIndicator', () => { + function indicator(jobs: readonly JobView[], panelShown: boolean, watchRows: JobsSectionProps['watchRows'] = () => () => {}) { + const section = props(jobs, undefined, {}, undefined, watchRows) + const dotProps = { + sessionId: section.sessionId, useJobs: section.useJobs, watchRows: section.watchRows, t: section.t, panelShown, + } as Pick as JobsRunningIndicatorProps + return render() + } + + it('shows a named dot while jobs run and the panel does not show them, counting stopping jobs', () => { + const view = indicator([ + job(), job({ id: 'bash-2' as JobView['id'], status: 'stopping' }), job({ id: 'bash-3' as JobView['id'], status: 'completed' }), + ], false) + expect(view.container.querySelector('[data-jobs-running]')?.textContent).toBe(zh['indicator.running'].replace('{count}', '2')) + }) + + it('renders nothing while the panel shows, without jobs, and after they settle', () => { + expect(indicator([job()], true).container.innerHTML).toBe('') + cleanup() + expect(indicator([], false).container.innerHTML).toBe('') + cleanup() + expect(indicator([job({ status: 'completed' })], false).container.innerHTML).toBe('') + }) + + it('keeps the roster stream open while the toggle is mounted, even while the panel shows', () => { + const stop = vi.fn() + const watchRows = vi.fn(() => stop) + const view = indicator([], true, watchRows) + expect(watchRows).toHaveBeenCalledWith(SESSION) + expect(stop).not.toHaveBeenCalled() + view.unmount() + expect(stop).toHaveBeenCalledOnce() + }) +}) + +describe('JobsSection visibility', () => { + it('renders nothing while the session sees no jobs', () => { + const { container } = render() + expect(container.innerHTML).toBe('') + }) + + it('watches the session roster while mounted and releases it on unmount', () => { + const stop = vi.fn() + const watchRows = vi.fn(() => stop) + const { unmount } = render() + expect(watchRows).toHaveBeenCalledWith(SESSION) + expect(stop).not.toHaveBeenCalled() + unmount() + expect(stop).toHaveBeenCalledTimes(1) + }) + +}) + +describe('JobsSection rows', () => { + it('renders a settled job without retained output as a static row', () => { + render() + // The section heading names the region, so the list carries no name of its own. + expect(screen.getByRole('list').hasAttribute('aria-label')).toBe(false) + expect(screen.getByText('explore the repo')).toBeDefined() + expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull() + }) + + it('offers a panel on a live row before any output arrived', () => { + render() + expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined() + }) + + it('shows the live progress line in place of the status word', () => { + render() + const list = screen.getByRole('list') + expect(within(list).getByText('pnpm run build')).toBeDefined() + expect(within(list).getByText('bash · winding down')).toBeDefined() + }) + + it('folds the settled tail behind its count while live work exists, and clears on demand', () => { + const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })] + render() + const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) + // Folded by default while something runs; the toggle expands it. + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByText('settled work')).toBeNull() + fireEvent.click(toggle) + expect(screen.getByText('settled work')).toBeDefined() + // Clearing hides the tail client-side and drops the whole section line. + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + expect(screen.queryByText('settled work')).toBeNull() + expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull() + }) + + it('keeps cleared rows hidden when the section mounts again for the same Session', () => { + const store = createJobsSectionStore().create() + const settled = job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 }) + const first = render() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + first.unmount() + render() + expect(screen.queryByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })).toBeNull() + expect(screen.queryByText('settled work')).toBeNull() + }) + + it('keeps the settled fold the user opened when the section mounts again for the same Session', () => { + const store = createJobsSectionStore().create() + const settled = job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 }) + const toggle = (): HTMLElement => screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) + const first = render() + fireEvent.click(toggle()) + first.unmount() + render() + expect([toggle().getAttribute('aria-expanded'), screen.queryByText('settled work') !== null]).toEqual(['true', true]) + }) + + it('opens the settled tail by default when nothing is live', () => { + render() + expect(screen.getByText('pnpm run build')).toBeDefined() + expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true') + }) + + it('clearing drops an expanded settled panel with its rows', () => { + const observe = vi.fn(() => () => {}) + render() + // Nothing live: the tail is open; expand the settled row's output panel. + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') })) + expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2') + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + expect(screen.queryByText('settled work')).toBeNull() + expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull() + }) + + it('shows a settled duration and ticks a live one', () => { + vi.useFakeTimers({ now: 1_700_000_020_000 }) + render() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) + expect(screen.getByText('5秒')).toBeDefined() + expect(screen.getByText('12秒')).toBeDefined() + expect(screen.getByText('1小时3分')).toBeDefined() + expect(screen.getByText('1分12秒')).toBeDefined() + act(() => { vi.advanceTimersByTime(1_000) }) + expect(screen.getByText('6秒')).toBeDefined() + }) + + it('lists rows with kind, label, and detail-or-status', () => { + render() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) + const list = screen.getByRole('list') + const items = within(list).getAllByRole('listitem') + // The section line is a listitem too now: live row, section, settled row. + expect(items).toHaveLength(3) + expect(items[0]?.textContent).toContain('pnpm run build') + // A live row's second line is kind · duration; the status word only + // appears through a detail (none while running). + expect(items[0]?.textContent).toMatch(/小时|分|秒/) + expect(items[2]?.textContent).toContain('exit code: 3') + }) + + it('orders live rows first by latest start and settled rows newest-first with tie-breaks', () => { + const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView => + job({ + id: id as JobView['id'], + label, + status: 'completed', + startedAt, + ...finishedAt !== undefined ? { finishedAt } : {}, + }) + render() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') })) + const labels = within(screen.getByRole('list')) + .getAllByRole('listitem') + .map(item => item.querySelector('[data-job-label]')?.textContent) + .filter((label): label is string => label != null) + expect(labels).toEqual([ + 'live-1', 'live-2', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e', + ]) + expect(screen.getAllByText(`bash · ${zh['status.completed']}`).length).toBeGreaterThan(0) + }) + + it('breaks a settled tie on start order so map iteration never decides it', () => { + render() + expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[data-job-label]')?.textContent).filter(label => label !== undefined)) + .toEqual(['first', 'second']) + }) + + it('prefers the producer detail over the generic status word', () => { + render() + expect(within(screen.getByRole('list')).getByText('bash · signal: SIGTERM')).toBeDefined() + }) + + it('renders settled status words and every lifecycle indicator', () => { + render() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) + for (const word of ['已完成', '已取消', '已失败']) { + expect(within(screen.getByRole('list')).getByText(`bash · ${word}`)).toBeDefined() + } + expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state'))) + .toEqual(['ongoing', 'warning', 'done', 'warning', 'error']) + }) + + it('marks a job that finished with a nonzero exit code with the warning dot', () => { + render() + expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state'))) + .toEqual(['warning', 'done', 'done']) + expect(screen.getByText('bash · exit code: 71')).toBeDefined() + }) + + it('keeps the trailing column on a row without output, with no chevron and no row button', () => { + const view = render() + const line = view.container.querySelector('[data-job-row]') as HTMLElement + expect(within(line).queryByRole('button')).toBeNull() + expect(line.lastElementChild?.getAttribute('aria-hidden')).toBe('true') + expect(line.lastElementChild?.childElementCount).toBe(0) + }) + + it('places the fold chevron after the settled count', () => { + render() + const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) + expect(toggle.lastElementChild?.tagName.toLowerCase()).toBe('svg') + expect(toggle.firstChild?.nodeType).toBe(Node.TEXT_NODE) + }) +}) + +describe('JobsSection group folds', () => { + /** Live jobs named `live-`, a higher n started later. */ + const live = (count: number): JobView[] => Array.from({ length: count }, (_, index) => + outputJob({ id: `live-${index}` as JobView['id'], label: `live-${index}`, startedAt: 1_700_000_000_000 + index })) + /** Settled jobs named `done-`, a higher n finished later. */ + const done = (count: number): JobView[] => Array.from({ length: count }, (_, index) => + outputJob({ id: `done-${index}` as JobView['id'], label: `done-${index}`, status: 'completed', finishedAt: 1_700_000_100_000 + index })) + /** The list's items in order: a job's label, the settled header as `{…}`, a fold control as `[…]`. */ + const items = (): string[] => within(screen.getByRole('list')).getAllByRole('listitem').map((item) => { + const control = item.querySelector('[data-fold]') + if (control !== null) return `[${control.textContent}]` + return item.querySelector('[data-job-label]')?.textContent ?? `{${item.querySelector('button')?.textContent ?? ''}}` + }) + const folds = (): HTMLElement[] => [...document.querySelectorAll('[data-fold]')] + const settledToggle = (count: number): HTMLElement => screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', String(count)) }) + + it('shows six live rows in full and holds two back from seven, behind the group fold control before the settled header', () => { + const six = render() + expect(items()).toEqual(['live-5', 'live-4', 'live-3', 'live-2', 'live-1', 'live-0', '{已结束 1}']) + six.unmount() + render() + // The most recently started rows stay; the control is the group's last row, an item of the list. + expect(items()).toEqual(['live-6', 'live-5', 'live-4', 'live-3', 'live-2', '[显示其余 2 个运行中]', '{已结束 1}']) + const control = folds()[0] as HTMLElement + expect([control.getAttribute('aria-label'), control.getAttribute('aria-expanded')]).toEqual(['显示其余 2 个运行中(运行中的后台任务)', 'false']) + fireEvent.click(control) + expect(items()).toEqual(['live-6', 'live-5', 'live-4', 'live-3', 'live-2', 'live-1', 'live-0', '[收起]', '{已结束 1}']) + expect([folds()[0]?.getAttribute('aria-label'), folds()[0]?.getAttribute('aria-expanded')]).toEqual(['收起(运行中的后台任务)', 'true']) + fireEvent.click(folds()[0] as HTMLElement) + expect(items()).toHaveLength(7) + }) + + it('folds the open settled group on its own, and offers no settled control while the group is closed', () => { + render() + // Live work keeps the settled group closed: only the live group has a control. + expect(folds().map(control => control.textContent)).toEqual(['显示其余 2 个运行中']) + fireEvent.click(settledToggle(8)) + expect(items().slice(6)).toEqual(['{已结束 8}', 'done-7', 'done-6', 'done-5', 'done-4', 'done-3', '[显示其余 3 个已结束]']) + const settled = folds()[1] as HTMLElement + expect(settled.getAttribute('aria-label')).toBe('显示其余 3 个已结束(已结束的后台任务)') + fireEvent.click(settled) + // Each control folds only its own group. + expect(items()).toEqual([ + 'live-6', 'live-5', 'live-4', 'live-3', 'live-2', '[显示其余 2 个运行中]', + '{已结束 8}', 'done-7', 'done-6', 'done-5', 'done-4', 'done-3', 'done-2', 'done-1', 'done-0', '[收起]', + ]) + expect(folds()[1]?.getAttribute('aria-label')).toBe('收起(已结束的后台任务)') + fireEvent.click(settledToggle(8)) + expect(folds()).toHaveLength(1) + }) + + it('shows six settled rows in full, and folds the group to its limit again after a clear', () => { + const store = createJobsSectionStore().create() + const first = render() + expect(items()).toHaveLength(7) + expect(folds()).toHaveLength(0) + first.unmount() + const second = render() + fireEvent.click(folds()[0] as HTMLElement) + expect(store.getSnapshot().unfolded).toEqual({ live: false, settled: true }) + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + expect(store.getSnapshot().unfolded).toEqual({ live: false, settled: false }) + second.unmount() + // Rows that settle after the clear fold at the limit again. + const later = Array.from({ length: 7 }, (_, index) => outputJob({ + id: `later-${index}` as JobView['id'], label: `later-${index}`, status: 'completed', finishedAt: 1_700_000_200_000 + index, + })) + render() + expect(items()).toEqual(['{已结束 7}', 'later-6', 'later-5', 'later-4', 'later-3', 'later-2', '[显示其余 2 个已结束]']) + }) + + it('keeps a group unfolded when the section mounts again for the same Session', () => { + const store = createJobsSectionStore().create() + const first = render() + fireEvent.click(folds()[0] as HTMLElement) + first.unmount() + render() + expect(items()).toHaveLength(9) + expect(folds()[0]?.getAttribute('aria-expanded')).toBe('true') + }) + + it('stops observing an expanded row that folds out of the list, and observes it again once it shows', () => { + const stop = vi.fn() + const observe = vi.fn(() => stop) + render() + fireEvent.click(folds()[0] as HTMLElement) + // live-0 started first, so the fold holds it back. + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'live-0') })) + expect(observe).toHaveBeenCalledExactlyOnceWith(SESSION, 'live-0') + fireEvent.click(folds()[0] as HTMLElement) + expect(stop).toHaveBeenCalledTimes(1) + expect(screen.queryByText('live-0')).toBeNull() + fireEvent.click(folds()[0] as HTMLElement) + expect(observe).toHaveBeenCalledTimes(2) + expect(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'live-0') })).toBeDefined() + }) + + it('stops observing an expanded settled row while its group is closed', () => { + const stop = vi.fn() + const observe = vi.fn(() => stop) + render() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'done-1') })) + expect(observe).toHaveBeenCalledExactlyOnceWith(SESSION, 'done-1') + fireEvent.click(settledToggle(2)) + expect(stop).toHaveBeenCalledTimes(1) + }) + + it.each(Object.entries({ zh, en }))('names each fold control with its visible text first in %s', (_locale, copy) => { + for (const group of ['live', 'settled'] as const) { + for (const label of [copy[`${group}.more`].replace('{count}', '3'), copy['fold.less']]) { + expect(copy[`${group}.foldName`].replace('{label}', label).startsWith(label)).toBe(true) + } + } + }) +}) + +describe('JobsSection observation', () => { + it('marks killed rows, renders every output line unfolded, and copies the command', async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n') + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: lines, + gapBefore: false, + streaming: false, + } + render() + expect(screen.getByText(`bash · ${zh['status.killed']}`)).toBeDefined() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + // The panel scrolls instead of folding: every line renders, no fold control. + expect(screen.getByText('line 1')).toBeDefined() + expect(screen.getByText('line 24')).toBeDefined() + expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull() + // The panel draws no state dot or label of its own — the row carries it. + expect(screen.queryByText(zh['terminal.done'])).toBeNull() + // The copy control carries the command, not the output. + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) }) + expect(writeText).toHaveBeenCalledWith('pnpm run build') + }) + + it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => { + const stop = vi.fn() + const observe = vi.fn(() => stop) + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: 'compiling…\n', + gapBefore: false, + streaming: true, + } + render() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1') + expect(screen.getByText('compiling…')).toBeDefined() + + fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') })) + expect(stop).toHaveBeenCalledTimes(1) + }) + + it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => { + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: '', + gapBefore: false, + streaming: true, + } + render() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(screen.getByRole('list').querySelector('[data-running]')).not.toBeNull() + expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull() + }) + + it('surfaces retention gaps and stream failures above the panel', () => { + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: 'tail only', + gapBefore: true, + streaming: false, + error: 'connection lost', + } + render() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(screen.getByText(zh['output.gap'])).toBeDefined() + expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined() + }) + + it('folds an expanded panel whose row left the roster', () => { + const stop = vi.fn() + // One stable observe identity across renders, as the inject face provides. + const observe = () => stop + const { rerender } = render() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + rerender() + expect(stop).toHaveBeenCalledTimes(1) + expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull() + }) +}) + +describe('JobsSection human kill', () => { + const stopTitle = (label: string): string => zh['kill.stopAria'].replace('{label}', label) + + it('offers the stop control only on running rows', () => { + render() + expect(screen.getByRole('button', { name: stopTitle('pnpm run build') })).toBeDefined() + expect(screen.queryByRole('button', { name: stopTitle('done') })).toBeNull() + }) + + it('arms on the first press and kills on the confirming press', async () => { + const killJob = vi.fn(async () => true) + render() + const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') }) + fireEvent.click(stop) + expect(killJob).not.toHaveBeenCalled() + expect(stop.getAttribute('data-kill-state')).toBe('armed') + expect(screen.getByRole('button', { name: zh['kill.confirm'] })).toBe(stop) + // The armed step is legible without hover: the button carries the label. + expect(stop.textContent).toBe(zh['kill.confirmAction']) + await act(async () => { fireEvent.click(stop) }) + expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1') + // An admitted kill stays pending: the unary response and the jobs frames + // have no cross-carrier ordering, so only the authoritative frame (the row + // leaving the killable set) releases the control — never the response. + expect(stop.getAttribute('data-kill-state')).toBe('pending') + expect(stop.hasAttribute('disabled')).toBe(true) + }) + + it('an armed press disarms after the confirmation window', () => { + vi.useFakeTimers() + const killJob = vi.fn(async () => true) + render() + const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') }) + fireEvent.click(stop) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + act(() => { vi.advanceTimersByTime(3_000) }) + expect(stop.getAttribute('data-kill-state')).toBe('idle') + expect(killJob).not.toHaveBeenCalled() + }) + + it('a rejected kill shows its hint and then resets', async () => { + // Fake timers from the start so the failed-hint reset arms on the fake clock. + vi.useFakeTimers() + const killJob = vi.fn(async () => false) + render() + const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') }) + fireEvent.click(stop) + await act(async () => { fireEvent.click(stop) }) + expect(stop.getAttribute('data-kill-state')).toBe('failed') + expect(screen.getByRole('button', { name: zh['kill.failed'] })).toBe(stop) + act(() => { vi.advanceTimersByTime(4_000) }) + expect(stop.getAttribute('data-kill-state')).toBe('idle') + }) + + it('arming a second row disarms the first', () => { + render() + const first = screen.getByRole('button', { name: stopTitle('pnpm run build') }) + fireEvent.click(first) + expect(first.getAttribute('data-kill-state')).toBe('armed') + const second = screen.getByRole('button', { name: stopTitle('pnpm run watch') }) + fireEvent.click(second) + expect(second.getAttribute('data-kill-state')).toBe('armed') + expect(first.getAttribute('data-kill-state')).toBe('idle') + }) + + it('a kill resolving after another row armed leaves the newer phase alone', async () => { + let resolveKill!: (ok: boolean) => void + const killJob = vi.fn(() => new Promise((resolve) => { resolveKill = resolve })) + render() + const first = screen.getByRole('button', { name: stopTitle('pnpm run build') }) + fireEvent.click(first) + fireEvent.click(first) + expect(killJob).toHaveBeenCalledTimes(1) + // While the first kill is in flight, the user arms the second row; the + // late resolution must not clobber that newer phase. + const second = screen.getByRole('button', { name: stopTitle('pnpm run watch') }) + fireEvent.click(second) + expect(second.getAttribute('data-kill-state')).toBe('armed') + await act(async () => { resolveKill(false) }) + expect(second.getAttribute('data-kill-state')).toBe('armed') + expect(first.getAttribute('data-kill-state')).toBe('idle') + }) + + it('clears an armed phase whose row stopped being killable', () => { + const { rerender } = render() + const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') }) + fireEvent.click(stop) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + rerender() + // The stopping row offers no kill control any more, and the stale phase is gone. + expect(screen.queryByRole('button', { name: stopTitle('pnpm run build') })).toBeNull() + expect(document.querySelector('[data-kill-state]')).toBeNull() + }) + + it('omits the stop control without job/kill access', () => { + const view = render() + expect(view.getByText('pnpm run build')).toBeTruthy() + expect(view.container.querySelector('[data-kill-state]')).toBeNull() + }) +}) + +it('renders the Russian settled-count copy', () => { + const translate: JobsSectionProps['t'] = makeTranslate(ru) + render() + expect(screen.getByRole('button', { name: ru['section.settledCount'].replace('{count}', '1') })).toBeDefined() +}) + +describe('JobsSection hover', () => { + it('shows the kind, state, and duration without the command in a hover card after 500ms, and the kind and state to assistive technology', () => { + vi.useFakeTimers({ now: 1_700_000_010_000 }) + vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' }))) + try { + const view = render() + const row = view.container.querySelector('[data-job-row]')! + const button = within(row).getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) + expect(document.getElementById(button.getAttribute('aria-describedby') ?? '')?.textContent).toBe('bash · 运行中') + const anchor = row.parentElement as HTMLElement + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(499) }) + expect(document.querySelector('[data-session-panel-details]')).toBeNull() + act(() => { vi.advanceTimersByTime(1) }) + const card = document.querySelector('[data-session-panel-details]') as HTMLElement + expect([...card.children].map(child => child.textContent)).toEqual(['bash', '运行中', '10秒']) + } finally { + vi.useRealTimers() + } + }) + + it('keeps the hover card closed while the pointer rests on the stop control, and closes an open one there', () => { + vi.useFakeTimers({ now: 1_700_000_010_000 }) + vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' }))) + try { + const view = render() + const anchor = (view.container.querySelector('[data-job-row]')!).parentElement as HTMLElement + const stop = screen.getByRole('button', { name: zh['kill.stopAria'].replace('{label}', 'pnpm run build') }) + // Entering the row at the stop control reaches the anchor first, then the control. + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + fireEvent.pointerEnter(stop, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(1000) }) + expect(document.querySelector('[data-session-panel-details]')).toBeNull() + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(zh['kill.stop']) + fireEvent.pointerLeave(stop, { pointerType: 'mouse' }) + fireEvent.pointerLeave(anchor, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(1000) }) + // A card the row opened closes once the pointer reaches the stop control. + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(500) }) + expect(document.querySelector('[data-session-panel-details]')).not.toBeNull() + fireEvent.pointerEnter(stop, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(1000) }) + expect(document.querySelector('[data-session-panel-details]')).toBeNull() + } finally { + vi.useRealTimers() + } + }) + + it('reveals a clipped command on row hover instead of native titles, and names only the stop action in a tooltip after 500ms', () => { + vi.useFakeTimers() + try { + const view = render() + expect(view.container.querySelector('[title]')).toBeNull() + const label = view.container.querySelector('[data-job-label]')! + Object.defineProperty(label, 'scrollWidth', { value: 300, configurable: true }) + Object.defineProperty(label, 'clientWidth', { value: 200, configurable: true }) + const row = label.closest('[data-job-row]')! + fireEvent.pointerEnter(row) + expect([label.hasAttribute('data-marquee'), label.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '100px']) + fireEvent.pointerLeave(row) + expect([label.hasAttribute('data-marquee'), label.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, '']) + const stop = screen.getByRole('button', { name: zh['kill.stopAria'].replace('{label}', 'pnpm run build') }) + fireEvent.pointerEnter(stop, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(499) }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + act(() => { vi.advanceTimersByTime(1) }) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(zh['kill.stop']) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/packages/client/ui-jobs/tests/jobs-styles.client.spec.ts b/packages/client/ui-jobs/tests/jobs-styles.client.spec.ts new file mode 100644 index 0000000000..84025b76b4 --- /dev/null +++ b/packages/client/ui-jobs/tests/jobs-styles.client.spec.ts @@ -0,0 +1,39 @@ +/** + * Job row geometry as CSS text: CSS Modules resolve to class-name maps in the + * component suite, so only the stylesheet proves that the chevron leaves its + * presses to the row button, including once the open chevron rotates, and that + * a row keeps one 28px line. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/client/JobsSection.module.css', import.meta.url)), 'utf8') + +function rule(selector: string): string { + const match = new RegExp(`(?:^|\\n)${selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\{([^}]*)\\}`).exec(css.replace(/\/\*[\s\S]*?\*\//g, '')) + if (match === null) throw new Error(`JobsSection.module.css has no ${selector} rule`) + return match[1] ?? '' +} + +describe('JobsSection.module.css', () => { + it('lets presses on the chevron reach the row button beneath it', () => { + expect(rule('.chevron')).toMatch(/pointer-events:\s*none/) + expect(rule('.chevronOpen')).toMatch(/transform:\s*rotate\(180deg\)/) + }) + + it('keeps a job on one 28px line, with the stop target overhanging it', () => { + expect(rule('.rowLine')).toMatch(/min-height:\s*28px/) + expect(rule('.rowLine')).toMatch(/padding:\s*4px 6px/) + expect(rule('.label')).toMatch(/line-height:\s*20px/) + expect(rule('.stop')).toMatch(/height:\s*24px/) + expect(rule('.stop')).toMatch(/margin:\s*-2px -4px/) + }) + + it('keeps the 28px line while the stop control is armed, its pill filling the row padding', () => { + expect(rule('.stopArmed')).toMatch(/height:\s*20px/) + expect(rule('.stopArmed')).toMatch(/margin:\s*0;/) + expect(rule('.stopArmed')).toMatch(/padding:\s*0 6px/) + expect(rule('.stopLabel')).toMatch(/line-height:\s*18px/) + }) +}) diff --git a/packages/client/ui-jobs/tsconfig.json b/packages/client/ui-jobs/tsconfig.json index f5e1825084..aaf0919623 100644 --- a/packages/client/ui-jobs/tsconfig.json +++ b/packages/client/ui-jobs/tsconfig.json @@ -8,20 +8,20 @@ "src" ], "references": [ + { + "path": "../../../vendor/cordis" + }, { "path": "../../api/job-controller/tsconfig.client.json" }, { "path": "../../api/session-controller/tsconfig.client.json" }, - { - "path": "../../../vendor/cordis" - }, { "path": "../locale/tsconfig.client.json" }, { - "path": "../ui-conversation/tsconfig.client.json" + "path": "../store" }, { "path": "../ui-primitives" @@ -32,6 +32,9 @@ { "path": "../ui-session" }, + { + "path": "../ui-session-panel" + }, { "path": "../ui-slots" } diff --git a/packages/client/ui-message-feedback/README.i18n.yaml b/packages/client/ui-message-feedback/README.i18n.yaml index 91205d3552..0e74c56b5d 100644 --- a/packages/client/ui-message-feedback/README.i18n.yaml +++ b/packages/client/ui-message-feedback/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-message-feedback/use-this-package: - en: e0127a604ff4aebb - zh: 38f1b3db30f81b22 + en: ac5cd1595f1626c3 + zh: ff428d8caa5a380e /deepseek-ai-dsh-client-ui-message-feedback/use-this-package/failures: - en: e4807e47bca06517 - zh: 649a3f9f62771865 + en: ebecf639f3166d7c + zh: d99985b9e7d1dac0 /deepseek-ai-dsh-client-ui-message-feedback/understand-the-implementation: en: 61260495346ceb3e zh: 32e05d3eb82fcaf2 diff --git a/packages/client/ui-message-feedback/README.md b/packages/client/ui-message-feedback/README.md index feffb193d6..1506abc9fd 100644 --- a/packages/client/ui-message-feedback/README.md +++ b/packages/client/ui-message-feedback/README.md @@ -25,7 +25,7 @@ This package is the Web GUI's feedback surface: the Like/Dislike pair in the fin ## Use this package -Mount this plugin alongside `ui-conversation` and `ui-commands`; the Like/Dislike pair then appears in the action row of each turn's closing assistant message, between copy and branch, and Feedback in the composer menu opens the same dialog. Mounting `session-log-export` also adds Feedback to the Session Header's more-actions menu. A recorded rating shows the filled glyph and stays visible without hover. Like and Dislike both open the dialog: seven category chips and a detail box are optional, and Submit records the selected judgment with whatever was filled in before the toast thanks the user; the conversation log travels with every feedback event. Clicking the recorded rating retracts it without opening the dialog. A bare `/feedback`, picked from the menu or typed and sent without text, opens the same dialog for the Session; `/feedback ` keeps the Host command path and its acknowledgement row. +Mount this plugin alongside `ui-conversation` and `ui-commands`; the Like/Dislike pair then appears in the action row of each turn's closing assistant message, between copy and branch, and Feedback in the composer menu opens the same dialog. Mounting `session-log-export` also adds Feedback to the Session Header's more-actions menu. The rating glyphs use 16px boxes at the default content font size, matching the adjacent completion actions while retaining fixed 1px outline strokes. A recorded rating shows the filled glyph and stays visible without hover. Like and Dislike both open the dialog: seven category chips and a detail box are optional, and Submit records the selected judgment with whatever was filled in before the toast thanks the user; the conversation log travels with every feedback event. Clicking the recorded rating retracts it without opening the dialog. A bare `/feedback`, picked from the menu or typed and sent without text, opens the same dialog for the Session; `/feedback ` keeps the Host command path and its acknowledgement row. ### Failures @@ -35,6 +35,8 @@ Access: the rating buttons render only while the current Peer may call `messageF ----- +The feedback dialog uses the shared modal heading spacing. Category chips form a tight group, details follow as a separate field, and the submit action has a larger separation than the gaps within either input group. + ## Understand the implementation diff --git a/packages/client/ui-message-feedback/README.zh.md b/packages/client/ui-message-feedback/README.zh.md index 27a879c2c8..55d84cbf3c 100644 --- a/packages/client/ui-message-feedback/README.zh.md +++ b/packages/client/ui-message-feedback/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -与 `ui-conversation`、`ui-commands` 一起挂载本插件;Like/Dislike 对随即出现在每个轮次收尾助手消息的动作行中,位于复制与分支之间,输入框菜单里的「反馈」会打开同一个弹窗。挂载 `session-log-export` 后,会话标题栏的更多操作菜单也会增加「反馈」。已记录的评分显示实心图标,不需要悬停也一直可见。点赞和点踩都会打开弹窗:七个分类标签和一个详情框都可不填;提交后才会记录带所填内容的对应评分并弹出感谢 toast,对话日志随每个反馈事件一起投递。再次点击已记录的评分会直接撤回,不打开弹窗。不带文本的 `/feedback`,无论是从菜单选中还是直接输入后发送,都会为 Session 打开同一个弹窗;`/feedback ` 仍走宿主命令路径并显示确认行。 +与 `ui-conversation`、`ui-commands` 一起挂载本插件;Like/Dislike 对随即出现在每个轮次收尾助手消息的动作行中,位于复制与分支之间,输入框菜单里的「反馈」会打开同一个弹窗。挂载 `session-log-export` 后,会话标题栏的更多操作菜单也会增加「反馈」。评分图标在默认内容字号下使用 16px 框,与相邻的收尾操作匹配,轮廓描边保持 1px。已记录的评分显示实心图标,不需要悬停也一直可见。点赞和点踩都会打开弹窗:七个分类标签和一个详情框都可不填;提交后才会记录带所填内容的对应评分并弹出感谢 toast,对话日志随每个反馈事件一起投递。再次点击已记录的评分会直接撤回,不打开弹窗。不带文本的 `/feedback`,无论是从菜单选中还是直接输入后发送,都会为 Session 打开同一个弹窗;`/feedback ` 仍走宿主命令路径并显示确认行。 ### 失败 @@ -35,6 +35,8 @@ kind: "package-reference" ----- +反馈弹窗使用共享弹窗的标题间距。分类选项组成紧凑分组,补充说明作为独立字段;提交操作与字段的分隔大于输入组内间距。 + ## 理解实现 diff --git a/packages/client/ui-message-feedback/src/client/FeedbackDialog.module.css b/packages/client/ui-message-feedback/src/client/FeedbackDialog.module.css index 74468dbd3d..89c1bc0396 100644 --- a/packages/client/ui-message-feedback/src/client/FeedbackDialog.module.css +++ b/packages/client/ui-message-feedback/src/client/FeedbackDialog.module.css @@ -1,7 +1,7 @@ /* The card width leaves four categories on the first row and three on the second. The doubled selector overrides the Modal card geometry. */ .dialog.dialog { - gap: 38px; + gap: 24px; width: min(488px, 100%); border-radius: var(--dsw-radius-panel); } @@ -10,7 +10,6 @@ display: flex; flex-wrap: wrap; gap: 8px; - margin-top: -14px; } .chip { diff --git a/packages/client/ui-message-feedback/src/client/MessageFeedbackActions.module.css b/packages/client/ui-message-feedback/src/client/MessageFeedbackActions.module.css index 2ae909c255..7a1bede1bb 100644 --- a/packages/client/ui-message-feedback/src/client/MessageFeedbackActions.module.css +++ b/packages/client/ui-message-feedback/src/client/MessageFeedbackActions.module.css @@ -15,11 +15,11 @@ cursor: pointer; } -/* The 15px glyphs follow the same px delta as the text they serve; the CSS - edge overrides each svg's own width/height attributes. */ +/* Match the completion row's glyph size without flex shrinking. */ .action svg { - width: calc(15px + var(--dsh-content-font-delta, 0px)); - height: calc(15px + var(--dsh-content-font-delta, 0px)); + flex: none; + width: calc(16px + var(--dsh-content-font-delta, 0px)); + height: calc(16px + var(--dsh-content-font-delta, 0px)); } @media (hover: hover) { diff --git a/packages/client/ui-message-feedback/tests/styles.client.spec.ts b/packages/client/ui-message-feedback/tests/styles.client.spec.ts index 84b1d270d2..4ab461f55b 100644 --- a/packages/client/ui-message-feedback/tests/styles.client.spec.ts +++ b/packages/client/ui-message-feedback/tests/styles.client.spec.ts @@ -85,7 +85,7 @@ describe('MessageFeedbackActions row styles', () => { // font size moves the row. expect(block('MessageFeedbackActions', '.action')).toMatch(/width:\s*calc\(28px \+ var\(--dsh-content-font-delta, 0px\)\)/) expect(block('MessageFeedbackActions', '.action')).toMatch(/height:\s*calc\(28px \+ var\(--dsh-content-font-delta, 0px\)\)/) - expect(block('MessageFeedbackActions', '.action svg')).toMatch(/width:\s*calc\(15px \+ var\(--dsh-content-font-delta, 0px\)\)/) + expect(block('MessageFeedbackActions', '.action svg')).toMatch(/width:\s*calc\(16px \+ var\(--dsh-content-font-delta, 0px\)\)/) }) it('uses the tertiary label colour for recorded rating icons', () => { @@ -95,9 +95,12 @@ describe('MessageFeedbackActions row styles', () => { }) describe('FeedbackDialog layout styles', () => { - it('uses the reviewed spacing, text colours, and submit-button geometry', () => { - expect(block('FeedbackDialog', '.dialog.dialog')).toMatch(/gap:\s*38px/) - expect(block('FeedbackDialog', '.categories')).toMatch(/margin-top:\s*-14px/) + it('separates dialog groups without negative category margins', () => { + expect(block('FeedbackDialog', '.dialog.dialog')).toMatch(/gap:\s*24px/) + expect(block('FeedbackDialog', '.categories')).not.toMatch(/margin(?:-top)?:[^;]*-/) + }) + + it('uses theme text colours and submit-button geometry', () => { expect(block('FeedbackDialog', '.chip')).toMatch(/color:\s*var\(--dsw-alias-label-primary\)/) expect(block('FeedbackDialog', '.detail::placeholder')).toMatch(/color:\s*var\(--dsw-alias-label-caption\)/) expect(block('FeedbackDialog', '.detail')).toContain('border-radius: var(--dsw-radius-lg)') diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 625d86768a..d56e0e373b 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -18,8 +18,8 @@ en: 0e2230da6a2214a1 zh: 0452e7556c9175f2 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: cead8d55a9508a8f - zh: d1ef63a880cbec55 + en: f88d040bb80449cf + zh: 64d6cd6df91d810a /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 8da3af8ae98adbb3 zh: b411b32d6b2b9e04 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 0f56794a18..029a23717e 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -41,7 +41,7 @@ The button's model menu shows search only when its full catalog contains more th Model and reasoning-effort names use weight 400 (regular) in the composer menu, including the selected item. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. -Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the Effort row absent; there is no arbitrary effort input. +Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons share the foreground color of their associated model or effort value. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the Effort row absent; there is no arbitrary effort input. The composer replaces the model and effort text with the Models icon when the expanded controls cannot share one line, and restores the text when space permits. The full selection remains available in the trigger's accessible name, tooltip, and menu. diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index a2eb90266c..d72293d41c 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -41,7 +41,7 @@ DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示 composer 菜单中的模型名称和推理等级均使用 400(regular)字重,包括选中项。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 -两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示 Effort 行;不存在任意推理强度输入。 +两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头与关联的模型或推理强度值使用相同的前景色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示 Effort 行;不存在任意推理强度输入。 展开的控件无法排在同一行时,composer 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.module.css b/packages/client/ui-model-selection/src/client/ModelSelect.module.css index 69d3f1d35c..5f31baa6bb 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -390,5 +390,5 @@ flex: 0 0 auto; width: 12px; height: 12px; - color: var(--dsw-alias-menu-icon); + color: var(--dsw-alias-label-tertiary); } diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index 60b0cb137d..a562bbfcc6 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 725b47765ee8f30b /deepseek-ai-dsh-client-ui-open-in-app/use-this-package: - en: b149da9963eb9837 - zh: 2426ea37fbd0f8b7 + en: 9c51cadb83cbc2fd + zh: 51caad8478647208 /deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect: en: c9022effccebd157 zh: 54e76ec13b5c1029 diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index 5664376801..55fb86e95e 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -25,6 +25,8 @@ Open a Session’s directory through **Open in** in its Header More menu or its ## Use this package +The compact split control is 24px high inside the document toolbar’s 28px control row, with 24px minimum segment widths; the labeled large variant keeps the standard control geometry. + Mount this plugin in the Web composition beside [`dsh-host-open-in-app`](../../host/open-in-app/README.md); this row takes no config. A known Session directory and at least one installed, localized catalog application enable its Open in submenu. The document preview of [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.md) shows file controls when the Host reports a desktop through `session.canOpenWorkspacePath`; removing this row removes all its controls and menu contributions. The Header entry uses the More button owned by [`ui-conversation`](../ui-conversation/README.md), with shared button behavior from [`ui-context-menu`](../ui-context-menu/README.md). Open in remains available there without the export plugin; this package supplies menu items rather than its own Header button. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index 69598cbc60..fbcf2af21e 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -25,6 +25,8 @@ kind: "package-reference" ## 使用本包 +紧凑分体控件在文档工具栏的 28px 控件行内保持 24px 高度,各分段最小宽度为 24px;带文字的大号变体保持标准控件几何。 + 把本插件与 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 并排挂载到 Web 组合;本行不接受配置。会话目录已知且至少有一个已安装、已本地化的目录应用时,显示在应用中打开子菜单。Host 通过 `session.canOpenWorkspacePath` 报告桌面可用时,[`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.zh.md) 的文档预览显示文件控件;删除本行会移除其全部控件与菜单贡献。 头部入口使用 [`ui-conversation`](../ui-conversation/README.zh.md) 持有的更多按钮,由 [`ui-context-menu`](../ui-context-menu/README.zh.md) 提供共享按钮行为。未挂载导出插件时,在应用中打开仍可通过该入口使用;本包提供菜单项,而不创建自己的头部按钮。 diff --git a/packages/client/ui-open-in-app/src/client/OpenTargetButton.module.css b/packages/client/ui-open-in-app/src/client/OpenTargetButton.module.css index 891cf7910b..67fb73330a 100644 --- a/packages/client/ui-open-in-app/src/client/OpenTargetButton.module.css +++ b/packages/client/ui-open-in-app/src/client/OpenTargetButton.module.css @@ -1,5 +1,4 @@ -/* Sized to sit in the document header's 24px control row beside its round - icon buttons: a hairline pill with a 12px label and a narrow chevron half. */ +/* Compact split actions sit within the document header's 28px control row. */ .menuAnchor { display: inline-flex; @@ -32,12 +31,20 @@ cursor: pointer; } +/* Keep both compact targets at 24px without spending layout width on the frame. */ +.split[data-size='compact'] { + border: 0; + box-shadow: inset 0 0 0 0.5px var(--dsw-alias-border-l4); +} + .main { gap: 4px; + min-width: 24px; padding: 3px 5px; } .chevron { + min-width: 24px; padding: 3px 4px 3px 3px; border-left: 0.5px solid var(--dsw-alias-border-l4); color: var(--dsw-alias-label-secondary); diff --git a/packages/client/ui-open-in-app/src/client/controller.ts b/packages/client/ui-open-in-app/src/client/controller.ts index bd43f8af7e..9d2eba76ce 100644 --- a/packages/client/ui-open-in-app/src/client/controller.ts +++ b/packages/client/ui-open-in-app/src/client/controller.ts @@ -99,17 +99,19 @@ export class OpenInAppController { private async run(): Promise { let apps: readonly string[] = [] + let payload: OpenInAppAppsPayload | undefined try { - const response = await this.fetcher(OPEN_IN_APP_APPS_ROUTE, { - headers: { accept: 'application/json' }, - }) - if (response.ok) { - const payload = await response.json() as OpenInAppAppsPayload - if (Array.isArray(payload.apps)) apps = payload.apps.filter(id => typeof id === 'string') - } - } catch (_error) { - // An unreachable Host supplies no directory openers in menus or controls. + payload = await this.readAppsPayload() + } catch (_appsUnavailable) { + // An unreachable Host or an unreadable reply supplies no directory openers in menus or controls. } + if (Array.isArray(payload?.apps)) apps = payload.apps.filter(id => typeof id === 'string') this.apps.set(apps) } + + /** The Host's opener payload, or `undefined` for a non-OK reply; rejects when the Host or its reply is unreadable. */ + private async readAppsPayload(): Promise { + const response = await this.fetcher(OPEN_IN_APP_APPS_ROUTE, { headers: { accept: 'application/json' } }) + return response.ok ? await response.json() as OpenInAppAppsPayload : undefined + } } diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index 85ea703b5d..1d2d10c4d9 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -96,7 +96,7 @@ export class OpenInAppPathController { let ok = false try { ok = (await this.remote.session.openWorkspacePath(request)).ok - } catch { + } catch (_hostUnreachable) { // Swallows carrier rejections: a Host that cannot be reached failed the // gesture like a Host that refused it, and the control announces that. } @@ -173,14 +173,13 @@ export class OpenInAppPathController { } private async run(): Promise { - let available = false + let result: RemoteResult | undefined try { - const result = await this.remote.session.canOpenWorkspacePath() - available = result.ok && result.value - } catch { + result = await this.remote.session.canOpenWorkspacePath() + } catch (_hostUnreachable) { // Swallows carrier rejections: an unreachable Host reads as no desktop, // so the preview shows no path control rather than a broken one. } - this.desktop.set(available) + this.desktop.set(result?.ok === true && result.value) } } diff --git a/packages/client/ui-permission-presets/README.i18n.yaml b/packages/client/ui-permission-presets/README.i18n.yaml index 9e64b4a3c4..36c374e851 100644 --- a/packages/client/ui-permission-presets/README.i18n.yaml +++ b/packages/client/ui-permission-presets/README.i18n.yaml @@ -18,8 +18,8 @@ en: b4193258023cf8ae zh: e8e6e0ea0ccb8ef4 /deepseek-ai-dsh-client-ui-permission-presets/use-this-package/the-picker: - en: 4e5a070ad4321548 - zh: 010063336bd2b8df + en: 3394f86700861a7a + zh: b78658f046151c3f /deepseek-ai-dsh-client-ui-permission-presets/use-this-package/the-settings-row: en: 5067f6aa12496225 zh: cfa6796684f97535 diff --git a/packages/client/ui-permission-presets/README.md b/packages/client/ui-permission-presets/README.md index cc552f5a78..2b79175ba2 100644 --- a/packages/client/ui-permission-presets/README.md +++ b/packages/client/ui-permission-presets/README.md @@ -31,7 +31,7 @@ In narrow browser settings, the default-permission label uses a smaller gutter b ### The picker -A pick submits the `/permission ` command line. The argument-bearing form (`/permission ` typed directly) still switches directly; the decoration replaces only the bare invocation. The built-in labels are `Read Only`, `Workspace Write`, `Full access`, and `Auto review` in English and `仅可查看`, `工作区内修改`, `完全权限`, and `自动审查` in Chinese. Explicit host labels remain unchanged, unknown kebab-case names render in title case, and `auto` carries an `EXP` badge in menu options plus an experimental-risk confirmation. The selected composer control shows the mode without the badge. `custom` is display state, never a target. +A pick submits the `/permission ` command line. The argument-bearing form (`/permission ` typed directly) still switches directly; the decoration replaces only the bare invocation. The built-in labels are `Read Only`, `Workspace Write`, `Full access`, and `Auto review` in English and `仅可查看`, `工作区内修改`, `完全权限`, and `自动审查` in Chinese. Explicit host labels remain unchanged, unknown kebab-case names render in title case, and `auto` carries an `EXP` badge in menu options plus an experimental-risk confirmation. The selected composer control shows the mode without the badge. `custom` is display state, never a target. Composer triggers use 16px Medium permission icons with fixed 1.3px strokes; ordinary menu rows retain 14px Regular icons with fixed 1px strokes. The trigger and menu labels share a 32px leading inset from their aligned surfaces. When the live catalog withdraws a preset, the composer closes its pending confirmation and shows the Session's current value instead of an unavailable optimistic pick. Every catalog invalidation — the payload-free notification or a connection-generation change — closes an open slash picker or its confirmation without consuming the draft, while publishing the result of a read the picker waits for leaves it open with its failure and retry state; reopening reads the current catalog. A submitted command remains busy until its response settles. diff --git a/packages/client/ui-permission-presets/README.zh.md b/packages/client/ui-permission-presets/README.zh.md index d8c4b63854..5fca033f3e 100644 --- a/packages/client/ui-permission-presets/README.zh.md +++ b/packages/client/ui-permission-presets/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" ### 选择器 -选中即提交 `/permission ` 命令行。带参形式(直接键入 `/permission `)仍直接切换;装饰只替换裸调用。内置标签在英文界面中是 `Read Only`、`Workspace Write`、`Full access` 和 `Auto review`,在中文界面中是「仅可查看」「工作区内修改」「完全权限」和「自动审查」。显式 host 标签保持原样,未知 kebab-case 名称渲染为 Title Case;`auto` 在菜单选项中带有 `EXP` 标记,并在可见选择时要求实验风险确认。选中后的 composer 控件显示模式,不展示该标记。`custom` 只是显示状态,绝非目标。 +选中即提交 `/permission ` 命令行。带参形式(直接键入 `/permission `)仍直接切换;装饰只替换裸调用。内置标签在英文界面中是 `Read Only`、`Workspace Write`、`Full access` 和 `Auto review`,在中文界面中是「仅可查看」「工作区内修改」「完全权限」和「自动审查」。显式 host 标签保持原样,未知 kebab-case 名称渲染为 Title Case;`auto` 在菜单选项中带有 `EXP` 标记,并在可见选择时要求实验风险确认。选中后的 composer 控件显示模式,不展示该标记。`custom` 只是显示状态,绝非目标。Composer 入口使用 16px Medium 权限图标,描边固定为 1.3px;普通菜单行保留 14px Regular 图标,描边固定为 1px。入口与菜单文本相对各自对齐的表面左边缘,共享 32px 起点。 实时目录撤销某个预设时,composer 关闭对应的待确认对话框,并用 Session 的当前值替代已不可用的乐观选择。每次目录失效(无 payload 的通知或连接代际变更)会关闭已打开的 slash 选择器或其确认对话框,不消费草稿;而发布某个 picker 正在等待的读取结果时,该 picker 保持打开并保留失败与重试状态;重新打开时读取当前目录。已经提交的命令在响应结束前继续保持忙碌状态。 diff --git a/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css b/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css index 306051aed2..b5d2679e85 100644 --- a/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css +++ b/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css @@ -5,7 +5,7 @@ min-width: 0; max-width: 220px; height: 28px; - padding: 0 4px 0 8px; + padding: 0 4px 0 12px; border: none; /* Rounded chip chrome, matching the sibling model trigger. */ border-radius: var(--dsw-radius-sm); @@ -38,11 +38,10 @@ flex: 0 0 auto; } -/* The shared 16px glyphs render one step smaller on the exposed trigger; - the dropdown rows keep the full 16px. */ +/* Keep the composer mode visible beside its label. */ .triggerIcon svg { - width: 14px; - height: 14px; + width: 16px; + height: 16px; } .triggerLabel { diff --git a/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx b/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx index 0281c41a24..0b2ca6f313 100644 --- a/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx +++ b/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx @@ -2,8 +2,10 @@ import { useEffect, useState } from 'react' import type { ReactNode } from 'react' import clsx from 'clsx' import { - IconChevronDownOutlineRegular, Menu, PermissionIconAutoReviewRegular, PermissionIconFullAccessRegular, - PermissionIconReadOnlyRegular, PermissionIconWorkspaceWriteRegular, RiskConfirmation, + IconChevronDownOutlineRegular, Menu, PermissionIconAutoReviewMedium, PermissionIconAutoReviewRegular, + PermissionIconFullAccessMedium, PermissionIconFullAccessRegular, PermissionIconReadOnlyMedium, + PermissionIconReadOnlyRegular, PermissionIconWorkspaceWriteMedium, PermissionIconWorkspaceWriteRegular, + RiskConfirmation, } from '@deepseek-ai/dsh-client-ui-primitives' import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives' import type { @@ -25,16 +27,16 @@ import css from './PermissionSelect.module.css' /* Permission glyphs follow currentColor so the trigger and menu rows tint the shared product artwork with their own text color. */ -const permissionGlyphs = new Map([ - ['read-only', ], - ['workspace-write', ], - [FULL_ACCESS, ], - [AUTO_REVIEW, ], +const permissionGlyphs = new Map([ + ['read-only', { menu: , trigger: }], + ['workspace-write', { menu: , trigger: }], + [FULL_ACCESS, { menu: , trigger: }], + [AUTO_REVIEW, { menu: , trigger: }], ]) -/** Glyph for a permission option value; host-configured names outside the design set get none. */ -function permissionGlyph(value: string): ReactNode | undefined { - return permissionGlyphs.get(value) +/** Glyph for a permission value and surface; host-configured names outside the design set get none. */ +function permissionGlyph(value: string, surface: 'menu' | 'trigger'): ReactNode | undefined { + return permissionGlyphs.get(value)?.[surface] } function permissionLabel( @@ -103,7 +105,7 @@ export function PermissionSelect({ const busy = pick !== null || confirmation !== null const items: MenuEntry[] = catalog.options.map((option) => { - const icon = permissionGlyph(option.value) + const icon = permissionGlyph(option.value, 'menu') const label = permissionLabel(option.value, option.name, t) const badge = optionBadge(option.value, t) return { @@ -180,8 +182,8 @@ export function PermissionSelect({ disabled={locked || busy} onClick={() => { setOpen(!open) }} > - {permissionGlyph(currentValue) !== undefined && ( - {permissionGlyph(currentValue)} + {permissionGlyph(currentValue, 'trigger') !== undefined && ( + {permissionGlyph(currentValue, 'trigger')} )} {currentLabel} diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 6cedb02b4c..4b25510c90 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -15,23 +15,23 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-primitives/use-this-package: - en: 33a5b39959a595c6 - zh: efd1088e9f13ed67 + en: f4b8f00c40213dc1 + zh: 7d12e0b41beabda4 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 05a81bd53a0585f1 - zh: 717afc6b87ce95e4 + en: 07574e4640e01163 + zh: cc3f074a6ec0a17d /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: - en: fd3499ef403a0594 - zh: 3a17727316d3c666 + en: ba57395620c1aab5 + zh: 551f454132fb4669 /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: en: 7fed4894a6d0d568 zh: c22881bfcef2d4b6 /deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy: - en: 3fd7072b662eed0a - zh: 88c6c299c0a6f8cd + en: 3942dc183d5f966d + zh: 63b1a07476fbc672 /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation: - en: 88448dce667337fe - zh: 5d9b6035191a0b08 + en: 6711120ef56212fb + zh: b18541d630196881 /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation/source-map: en: a39e67d79e171221 zh: 593e260c073336f9 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 959af5d494..d11233fa31 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -25,6 +25,8 @@ Use `dsh-client-ui-primitives` to build web-client controls and render agent out ## Use this package +Checkboxes retain native input semantics with shared corner geometry and check artwork anchored to the input wrapper; forced-color mode uses the native control. Empty input icons and placeholder text share auxiliary ink. Text inputs keep a 16px font floor for coarse pointers. Segmented tabs use the shared keyboard focus ring while preserving the selected indicator. Selected and disabled chips keep their state fill during hover. + `Toast` uses the theme’s toast background and label colors in both light and dark modes. `Menu` data rows and `MenuItemButton` component rows accept owner-provided effective shortcuts and align their keys at the trailing edge as muted text without a background, including submenus. Menu row separators align with the horizontal content edges of their rows. Menus hide these hints when the primary pointer is coarse (`pointer: coarse`) and [keyboard navigation](#input-modality) is inactive. Keyboard navigation reveals them until the next pointer press; keyboard bindings remain active. `ShortcutKeys` defaults to unboxed keys for menu and inline hints. Its `tooltip` variant uses lighter keycaps over the dark bubble and groups plus-separated combinations into one filled block. `Tooltip.shortcutKeys` vertically centers keycaps beside optional localized action text, or shows only keys when the label is empty. The optional `className` supplies owner interaction styles. `Modal` uses the frame’s shared overlay inset, with a minimum 24px viewport margin. Its mask leaves the Windows caption unpainted while the full-viewport layer blocks background clicks. `Modal` and the settings shell share top-layer Escape and Tab handling through `useModalLayer`, restoring the previous focus on close. A dialog that remains mounted restores focus left inside its closed layer, preserving focus already moved elsewhere. `closeTopModal(document)` requests the foreground modal’s current close action; newer menus or unregistered dialogs block dismissal of the modal behind them. Components use `isBehindModal` to avoid moving focus behind a nested dialog. Menus consume their local Escape before modal dismissal. `observeComposition` supplies the same composition-end and legacy IME guard to local modal and recording handlers; callers dispose its document listeners with their interaction lifetime. `isMobileDevice()` identifies iOS and Android phones and tablets for automatic text-input focus and keyboard dismissal. It recognizes `Android`, `iPhone`, `iPad`, or `iPod` in the UA, and iPads reporting `MacIntel` with more than one touch point. Other devices, including Windows touchscreen computers, return false regardless of window width. The function caches its first result for all callers in the page; component remounts reuse that result, and reloading the page reads the browser environment again. Identified mobile devices require explicit text-input focus. Browser modes or custom UAs that conceal the mobile platform can prevent identification; unrecognized UAs return false. A desktop UA alone cannot distinguish Android tablets from Linux computers. @@ -55,6 +57,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `SegmentedTabs` | Controlled equal-width tabs with a sliding indicator and Left/Right, Home, and End navigation. The caller supplies labels, tab/panel ids, and panel content. Default `size="md"` is 42px tall with a 4px inset; `size="sm"` is 34px tall with a 2px inset. | | `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. | | `PathLabel` | Single-line file path with subdued directories, a primary filename, and the full path on hover. Fitting paths align left; clipped paths preserve their suffix with a left-edge fade that updates on path and size changes. | +| `MarqueeText`, `useHoverMarquee` | Single-line text that clips with an ellipsis at rest, and the hook that marquees it: spread the pointer handlers it returns onto the owning row, and while the pointer is on the row a clipped text travels at 30px/s to its far edge and holds there, fading the edges that still hide text; leaving returns it to the start at once. The stylesheet animates the travel, and the hook measures the overflow once per entry. `hold` keeps the text marqueed without the pointer, such as while the row's menu is open. Overflow of at most 8px, touch pointers, and text that fits stay put; reduced motion shows the far edge at once. | | `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader whose animations pin to document time zero on mount and on every animation restart, such as a list reorder, so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. `appearance="step"` shows a filled check for completion and a hollow pending circle. | | `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. | | `DisclosureRow` | 24px compact disclosure that lays title and content side by side. The header supplies tertiary at rest and secondary on hover; text and icons inherit it regardless of expandability or open state unless the caller supplies a feature-specific override. Semantic status colors remain explicit. Collapsed rows preview a down chevron on hover, and expanded rows keep an up chevron visible. `headerAccessory` places an independent action outside the disclosure target and shimmer; with an accessory, the title row shrinks to its content width. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. | @@ -64,8 +67,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `Modal` | Centered dialog over a page mask. A nested dialog can intercept keys with `onKeyDownCapture` before document Escape handlers. The tint and dialog fade in while backdrop blur stays fully applied, honoring reduced motion. Set `backdropBlur={false}` when the caller already blurs the source page. `tone="warning"` places an amber warning icon in the title and removes the body's extra top margin; other dialogs retain their spacing. | | `RiskConfirmation` | Sensitive action gated behind an explicit checkbox, using the shared warning-title layout. | | `Tooltip` | Hover and keyboard-focus text anchored to a cloned child; optional `delayMs` controls hover delay and `focusDelayMs` controls keyboard-focus delay, both defaulting to 0 ms. Optional `portal` rendering escapes clipping containers and ancestor stacking contexts that cap the bubble's z-index. | -| `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. | -| `useTitleMarquee`, `titleMarqueeClass` | Scrolls a one-line clipped title to its far edge while its row is hovered and fades its clipping edges; the Session list uses it. | +| `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. A compact card opens beside the anchor's end edge, or beside its start edge when it would cross the viewport's end and fits there, as for rows of a panel at the window's end; with room on neither side it opens below the anchor from the anchor's start edge, or above it without room below, so it does not cover the anchor; a card too tall for either stays inside the viewport, in its bottom end corner. CSS anchor positioning places it, so the card follows its anchor without script measurement; Firefox resolves the anchor without the transforms of its ancestors, so a compact card whose anchor sits under a transformed ancestor is misplaced there. | | `DraggableImage` | Original-image gestures with explicit transfer and feedback callbacks. | | `ImageLightbox` | Shared image modal with focus restoration and Escape dismissal. | | `usePointerGrace` | Cancelable dismissal delay that lets the pointer cross the gap between a trigger and its card; pending timers are cleared on unmount. | @@ -80,7 +82,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `UserTextRun`, `ReferenceChip` | Uninterpreted inline text and business-resolved reference labels or activation buttons. | | `CommandText` | Selectable command or argument text; only horizontal overflow adds a named keyboard focus target. | | `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, `WebBlock` | The agent-output card matching each tool-result intent. | -| `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. `IconDragHandleOutlineRegular`/`Medium` draw a three-line grip for reordering. The thinking glyph keeps an inset orbit within its 16px view box. `IconAppsAddOutlineRegular`/`Medium`, the More launcher glyph, take `compact` to draw their tiles closer together at card size. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. | +| `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. `IconDragHandleOutlineRegular`/`Medium` draw a three-line grip for reordering. `IconFilesDiffOutlineRegular`/`Medium` draw two stacked pages, the front one marked with a plus over a minus, for the changes across a set of files. The thinking glyph keeps an inset orbit within its 16px view box. `IconAppsAddOutlineRegular`/`Medium`, the More launcher glyph, take `compact` to draw their tiles closer together at card size. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. | | `PermissionIconReadOnlyRegular`/`Medium`, `PermissionIconWorkspaceWriteRegular`/`Medium`, `PermissionIconFullAccessRegular`/`Medium`, `PermissionIconAutoReviewRegular`/`Medium` | Permission-mode glyphs for read-only, workspace-write, full-access, and auto-review choices. | | `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | Fixed-palette 36×36 plugin artwork; `Terminal` supplies the light-blue prompt in plugin cards and sidebar guide entries. `Default` marks plugins without artwork of their own. Def ids are per-instance, so the same artwork repeats safely on one page. | | `GuideArtworkBrowser`/`Files` | Fixed-palette 36×36 browser and folder artwork for sidebar guide entries. | @@ -98,7 +100,9 @@ Writing your own component in your own package is fine when the need is genuinel ### Controls and icons -The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. Line artwork uses stroke widths of 1 and 1.3 SVG user units respectively; the `size` prop controls rendered dimensions. Strokes scale with the viewport: a 1-unit stroke in a 16-unit view box renders at 0.875 CSS px at 14px and 0.75 CSS px at 12px, before further transforms. The renderer does not apply non-scaling strokes; filled contours scale as geometry and do not respond to stroke-width changes. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconMailReadOutlineRegular`/`Medium` show an open envelope; `IconMailUnreadOutlineRegular`/`Medium` show a closed envelope with an unread dot. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `IconEyeOutlineRegular`/`Medium` draw an open eye with a pupil and `IconEyeOffOutlineRegular`/`Medium` the same contour crossed by a diagonal slash, for paired show and hide toggles. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. +Shared menu and navigation artwork uses optical insets per glyph; `size` still measures the SVG box, not the painted contour. Edit and archive outlines retain the chosen stroke width when resized. Circular information and check glyphs use the same inset circle as peer status controls; the historical `IconCheckCircleFill` names retain the outlined circled-check appearance and now honor the chosen stroke weight. + +The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. The `size` prop controls rendered dimensions. Stroked paths use `non-scaling-stroke`, keeping Regular at 1 CSS px and Medium at 1.3 CSS px. Filled contours, including filled parts of mixed icons, still scale as geometry and do not respond to stroke-width changes; the fixed-stroke statement excludes those parts. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconMailReadOutlineRegular`/`Medium` show an open envelope; `IconMailUnreadOutlineRegular`/`Medium` show a closed envelope with an unread dot. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `IconEyeOutlineRegular`/`Medium` draw an open eye with a pupil and `IconEyeOffOutlineRegular`/`Medium` the same contour crossed by a diagonal slash, for paired show and hide toggles. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. `Tooltip` reads the anchor on hover or keyboard focus and fits its bubble from `ResizeObserver` border-box sizes. It stays hidden until its first fit, prefers the requested side, then tries the opposite and perpendicular sides, sliding along the anchor without covering it when a side fits. Horizontal placements keep a 10px gap; vertical placements use `gap` (8px by default). Width and height stay within a 12px viewport margin; text wraps, and content taller than the viewport scrolls when pinned. If no side fits, a stable viewport-bounded fallback can overlap the anchor. Viewport resize refreshes the anchor coordinates; label-size changes reuse them. Fitting does not synchronously measure the bubble or trigger a React render. Touch presses dismiss unpinned hints and do not trigger hover hints, including compatibility mouse events. Mouse entry opens hints only while `(any-hover: hover)` reports an available hover-capable input, excluding iOS mouse entry caused by a tapped icon changing. Keyboard focus and explicit click-to-open explanations remain available on touch-only devices. Opt-in `openOnClick` lets an informational button pin the bubble by click or tap and associates it with the anchor description. Another click or tap, Escape, Tab, or an outside pointerdown closes it. Ordinary action buttons execute their action directly without a touch tooltip. Opt-in `onlyWhenClipped` shows the bubble only when the anchor or an HTML element inside it overflows horizontally when the bubble is about to show, so a label that repeats ellipsis-cut text appears only while it adds information. @@ -134,10 +138,12 @@ Explicit `./`, `../`, slash/backslash-rooted paths (including UNC), and Windows The atoms cannot read the application locale, so every piece of user-facing copy arrives through required label props. `HoverCard`, `TerminalBlock`, `JsonTree`, `CodeBlock`, `MarkdownText`, `JsonBlock`, `ConnectionIndicator`, `Modal`, `DiffBlock`, `ReadBlock`, `SearchBlock`, `WebBlock`, and `ZoomControls` accept complete localized labels. The package owns no language fallback; omission fails typechecking, and each feature maps its typed `t` seat into the primitive's label interface. -`Menu.anchorRef` names a trigger rendered outside the component, including one attached later in the same commit or replaced between openings. Keyboard dismissal of an `autoFocus` menu restores the previously focused control while it remains connected. `anchorPoint` accepts client-viewport coordinates, matching `event.clientX`/`clientY` and `getBoundingClientRect()`. On Safari, opening the menu or changing the point converts these coordinates to the layout viewport once. CSS then handles zoom and panning without continuous viewport listeners or rectangle measurements. `Menu.contextual` positions from that point without the frame inset and closes on a right-click inside the popup. Contextual popups with no rendered `role="menuitem"` rows stay hidden, including when legacy Slots return no content. Structured `items` reserve an icon column per divider group; `footer` and each submenu calculate their own groups. A contextual `footer` with a leading separator uses that line instead of adding a second border. Opaque `children` retain their own layout; a legacy Slot after data rows keeps its declared leading separator. `exiting` retains an inert popup for its fade; `returnFocus` restores the original control after asynchronous preparation. `MenuSurface.phase` fades the material, direct content, and macOS backing separately so the material keeps blurring the page. `MENU_TRANSITION_MS` supplies both CSS timing and the popup lifecycle timers. Ordinary dropdowns open without the contextual preparation delay. +`Menu.anchorRef` names a trigger rendered outside the component, including one attached later in the same commit or replaced between openings. An open menu closes when another popup trigger (an `aria-haspopup` control outside it) is activated, including one that stops its pointer presses, such as the shared context-menu button; `isExternalTrigger` exempts the triggers a popup manages itself. Keyboard dismissal of an `autoFocus` menu restores the previously focused control while it remains connected. `anchorPoint` accepts client-viewport coordinates, matching `event.clientX`/`clientY` and `getBoundingClientRect()`. On Safari, opening the menu or changing the point converts these coordinates to the layout viewport once. CSS then handles zoom and panning without continuous viewport listeners or rectangle measurements. `Menu.contextual` positions from that point without the frame inset and closes on a right-click inside the popup. Contextual popups with no rendered `role="menuitem"` rows stay hidden, including when legacy Slots return no content. Structured `items` reserve an icon column per divider group; `footer` and each submenu calculate their own groups. A contextual `footer` with a leading separator uses that line instead of adding a second border. Opaque `children` retain their own layout; a legacy Slot after data rows keeps its declared leading separator. `exiting` retains an inert popup for its fade; `returnFocus` restores the original control after asynchronous preparation. `MenuSurface.phase` fades the material, direct content, and macOS backing separately so the material keeps blurring the page. `MENU_TRANSITION_MS` supplies both CSS timing and the popup lifecycle timers. Ordinary dropdowns open without the contextual preparation delay. ----- +Inline link icons retain their full layout box and align to the current font’s cap-height center; links keep normal paragraph wrapping. Modal content without a description has a shorter heading-to-body gap. Close-button boxes share the body and footer’s trailing edge; their icons remain centered inside the larger hit targets. Risk warnings and acknowledgements share leading icon slots and text starts. + ## Understand the implementation @@ -145,7 +151,7 @@ The atoms cannot read the application locale, so every piece of user-facing copy Portalled menus close when their anchor becomes inert or hidden; contextual menus use the original control supplied by `returnFocus`. `isExternalTrigger(node)` lets the caller identify external controls whose pointer presses must reach its toggle handler without outside dismissal. Without this prop, presses outside the anchor and menu panels dismiss, including presses on `returnFocus` targets. `returnFocus` alone only controls focus restoration. While open, a contextual menu adds its ID to that control's `aria-controls` and restores the previous value on close. Their owner’s retained content stays mounted. -`Menu.listClassName` styles the menu card independently of the anchor wrapper, including in portal mode. Tall portal menus retain the trigger’s horizontal alignment while using the window’s vertical scrolling space; horizontal clamping applies only when the card cannot fit beside that edge. Leading icons use the `--dsw-alias-menu-icon` color; destructive icons retain their error color. +`Menu.listClassName` styles the menu card independently of the anchor wrapper, including in portal mode. Tall portal menus retain the trigger’s horizontal alignment while using the window’s vertical scrolling space; horizontal clamping applies only when the card cannot fit beside that edge. Leading icons use the `--dsw-alias-menu-icon` color; destructive icons retain their error color. Ordinary menu icons and selection checks use 14px boxes; the compact variant keeps 12px boxes. Use Regular line icons to retain a fixed 1px stroke at the rendered size. Submenu parents show a right chevron and open through focus, click, or hover-capable non-touch pointer events. ArrowRight on a menu row enters its child, never activates the external popup trigger; ArrowLeft and Escape return focus to the parent. Each child portals outside the parent's scrolling area, prefers the right side, flips left when it fits, and uses the root menu's visual-viewport limits and WebKit coordinate normalization with internal scrolling. When neither side fits, click or ArrowRight replaces the visible parent panel with the child and a return row; focus alone keeps the parent panel visible. `submenuBackLabel` supplies its localized text; when omitted, the return row uses the caller's parent label beside a left arrow and never selects the parent. Placement depends on available space, not the device's user agent; touch clicks open children on wide screens too. Resizing retains focused child nodes. JavaScript hover requires `(any-hover: hover)` and a non-touch pointer event, so secondary mice and pens can open children even when the primary pointer is touch. Compatibility mouse hover events do not open or collapse children. The pointer grace permits crossing the gap between cards; sibling rows close the previous child. Grace dismissal returns focus left in the child to its parent. Removing or disabling the parent, or emptying its children, restores the root panel and cancels that submenu. Focus left in the removed child returns to its enabled parent, the first enabled root row, or the anchor; focus already moved elsewhere stays there. @@ -162,6 +168,8 @@ Group membership is captured at setup. Dispose before observing changed groups,
    Implementation internals — click to expand +Markdown link icons retain their complete boxes and internal whitespace. Their external prose gap is larger than the icon-to-label gap, while prose links remain able to wrap. + The package enforces one separation: presentational React atoms with zero Cordis and zero slot knowledge, styled only through `--dsw-*` tokens, while every feature-specific concern (locale, session data, composition) stays in the composing plugin. ### Source map diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 39386e10c6..c45c65ea15 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -25,6 +25,8 @@ kind: "package-library" ## 使用本包 +复选框保留原生输入语义,使用统一圆角,勾选图形定位于输入包装框;强制颜色模式使用原生控件。空输入框的图标与占位文字使用相同的辅助颜色。触摸输入条件下,文本输入字号不低于 16px。分段标签沿用统一的键盘焦点描边,并保留选中指示。选中和禁用的标签在悬停时保留状态底色。 + `Toast` 在浅色和深色模式下均使用主题的系统提示背景与文字颜色。`Menu` 数据条目与 `MenuItemButton` 组件条目接收功能 owner 提供的有效快捷键,并在末端以无背景的浅灰色文字对齐显示,子菜单也采用同一呈现。菜单行的分割线与该行内容区的左右边缘对齐。主指针为粗指针(`pointer: coarse`)且未使用[键盘导航](#input-modality)时,菜单隐藏这些提示。键盘导航会显示提示,直到下一次指针按下;快捷键绑定始终生效。`ShortcutKeys` 默认以无方块的按键文字显示菜单和行内提示。`tooltip` 变体在深色气泡上使用稍浅的键帽,以加号连接的组合则共用一个填充色块。`Tooltip.shortcutKeys` 将键帽与可选的本地化操作文本垂直居中排列,标签为空时只显示按键。可选的 `className` 供调用方设置交互状态样式。`Modal` 使用框架共享的浮层起点,视口边距至少为 24px。其遮罩不绘制 Windows 顶栏区域,覆盖整个视口的模态层仍阻挡背景点击。`Modal` 与设置外壳通过 `useModalLayer` 共用顶层 Esc 和 Tab 处理,关闭时恢复先前焦点。关闭后保留在 DOM 中的弹窗仅恢复仍停留于内部的焦点,不覆盖已经移到其他位置的焦点。`closeTopModal(document)` 请求前台弹窗当前的关闭操作;上层菜单或未注册的对话框会阻止关闭其后方弹窗。组件通过 `isBehindModal` 避免将焦点移到嵌套弹窗后方。菜单先消费自己的 Esc,再由模态层处理关闭。 `observeComposition` 为局部弹层和录键处理提供相同的 composition-end 与旧版 IME 保护;调用方随交互生命周期释放其 document 监听。 `isMobileDevice()` 识别 iOS 和 Android 手机及平板,供自动聚焦和收起键盘使用。它识别 UA 中的 `Android`、`iPhone`、`iPad` 或 `iPod`,以及报告 `MacIntel` 且触摸点数大于一的 iPad。其他设备(包括 Windows 触屏电脑)返回 false,不受窗口宽度影响。函数缓存首次判断结果,供页面内的所有调用方共享;组件重新挂载会复用该结果,重新加载页面时会再次读取浏览器环境。识别出的移动设备需要用户主动聚焦文本输入框。隐藏移动平台信息的浏览器模式或自定义 UA 可能导致识别失败;未识别的 UA 返回 false。仅凭桌面 UA 无法区分 Android 平板与 Linux 电脑。 @@ -55,6 +57,7 @@ kind: "package-library" | `SegmentedTabs` | 受控的等宽分段标签,支持滑动指示条及左/右方向键、Home、End 导航。调用方提供文案、标签与面板 id,以及面板内容。默认 `size="md"` 总高 42px、内边距 4px;`size="sm"` 总高 34px、内边距 2px。 | | `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 | | `PathLabel` | 单行文件路径:目录使用弱化颜色,文件名使用主色,悬停可查看完整路径。空间足够时靠左显示;溢出时保留尾部并在左侧渐隐,路径或尺寸变化时更新。 | +| `MarqueeText`、`useHoverMarquee` | 静止时以省略号截断的单行文字,以及让它滚动显示的 hook:把 hook 返回的指针处理函数展开到所在的行上,指针停在行上时,被截断的文字以 30px/s 匀速移到末尾并停在那里,仍有文字被遮住的边缘渐隐;离开时立即回到开头。移动由样式表的动画完成,hook 每次进入只测量一次溢出宽度。`hold` 让文字在指针不在行上时也保持滚动显示,例如行的菜单打开期间。溢出不超过 8px、触摸指针以及放得下的文字都不滚动;减少动态效果时直接显示末尾。 | | `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画在挂载时以及每次动画重启(如列表重排)时固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 `appearance="step"` 以实心勾表示完成、空心圆表示等待。 | | `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 | | `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。标题行默认使用 tertiary,悬停时使用 secondary;文字与图标继承该颜色,不受能否展开及开合状态影响,调用方可提供功能专属覆盖。语义状态色保持显式指定。收起时悬停预览向下箭头,展开后持续显示向上箭头。`headerAccessory` 将独立操作放在折叠触发区域和流光之外;有此操作时,标题行收窄到内容宽度。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 | @@ -64,8 +67,7 @@ kind: "package-library" | `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。`tone="warning"` 在标题中显示橙色警告图标,并移除正文额外的顶部间距;其他弹窗的间距保持不变。 | | `RiskConfirmation` | 以显式复选框把关的敏感操作确认,采用共用的警告标题布局。 | | `Tooltip` | 锚定在克隆子元素上的悬停与键盘聚焦提示;可选的 `delayMs` 控制悬停延迟,`focusDelayMs` 控制键盘聚焦延迟,均默认为 0 毫秒。可通过 `portal` 渲染到外层,避免被容器裁剪,或受祖先层叠上下文限制其 z-index。 | -| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。 | -| `useTitleMarquee`、`titleMarqueeClass` | 行被悬停时把被截断的单行标题滚动到末尾,并淡化截断边缘;会话列表使用它。 | +| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。紧凑卡片出现在锚点结束一侧;会超出视口结束边缘、而开始一侧放得下时出现在开始一侧,例如窗口末端面板中的行;两侧都放不下时出现在锚点下方,与锚点的开始边缘对齐,下方放不下则出现在上方,因此不会盖住锚点;高到上下都放不下的卡片留在视口内,位于底部结束一角。它由 CSS 锚点定位放置,卡片跟随锚点时不需要脚本测量;Firefox 解析锚点位置时不计入祖先元素的 transform,锚点位于带 transform 的祖先之内时,紧凑卡片在 Firefox 中的位置会偏移。 | | `DraggableImage` | 通过显式传递与反馈回调提供原图拖放。 | | `ImageLightbox` | 共享图片浮层,支持焦点恢复与 Esc 关闭。 | | `usePointerGrace` | 可取消的延迟关闭,让指针能够跨越触发控件与卡片间的空隙;卸载时清除待执行定时器。 | @@ -80,7 +82,7 @@ kind: "package-library" | `UserTextRun`、`ReferenceChip` | 不做解析的行内文本,以及业务已解析的引用标签或激活按钮。 | | `CommandText` | 可选中的命令或参数文本;仅横向溢出时添加具名的键盘聚焦目标。 | | `TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock`、`WebBlock` | 与各类工具结果意图对应的 agent 输出卡片。 | -| `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。`IconDragHandleOutlineRegular`/`Medium` 以三条横线表示可拖动的排序手柄。思考图标的轨道在 16px 视口内保留内边距。“更多”入口使用的 `IconAppsAddOutlineRegular`/`Medium` 接受 `compact`,在卡片尺寸下让方块更靠近。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 | +| `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。`IconDragHandleOutlineRegular`/`Medium` 以三条横线表示可拖动的排序手柄。`IconFilesDiffOutlineRegular`/`Medium` 画两页叠放的文件,前页带上加下减,表示一组文件的变更。思考图标的轨道在 16px 视口内保留内边距。“更多”入口使用的 `IconAppsAddOutlineRegular`/`Medium` 接受 `compact`,在卡片尺寸下让方块更靠近。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 | | `PermissionIconReadOnlyRegular`/`Medium`、`PermissionIconWorkspaceWriteRegular`/`Medium`、`PermissionIconFullAccessRegular`/`Medium`、`PermissionIconAutoReviewRegular`/`Medium` | 只读、工作区写入、完全访问与自动审查选项使用的权限模式图形。 | | `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | 固定配色的 36×36 插件插画;`Terminal` 为插件卡片和侧边栏开始页入口提供浅蓝色提示符。`Default` 用于没有自有插画的插件。def id 按实例生成,同一插画可在一页中安全重复。 | | `GuideArtworkBrowser`/`Files` | 固定配色的 36×36 浏览器与文件夹插画,用于侧栏引导入口。 | @@ -98,7 +100,9 @@ kind: "package-library" ### 控件与图标 -上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。线条图形分别使用 1 和 1.3 SVG 用户单位的描边宽度;`size` prop 控制渲染尺寸。描边随视口缩放:16 单位 viewBox 中宽度为 1 的描边,在 14px 下为 0.875 CSS px,在 12px 下为 0.75 CSS px,尚未计入额外变换。渲染器不使用非缩放描边;填充轮廓随几何缩放,不受 stroke-width 变化影响。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconMailReadOutlineRegular`/`Medium` 使用打开的信封,`IconMailUnreadOutlineRegular`/`Medium` 使用带未读圆点的闭合信封。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`IconEyeOutlineRegular`/`Medium` 绘制带瞳孔的睁眼,`IconEyeOffOutlineRegular`/`Medium` 在同一轮廓上加一条斜线,用于成对的显示与隐藏开关。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 +共享的菜单与导航图标按图形分别保留视觉内边距;`size` 仍表示 SVG 框,而非实际绘制轮廓。编辑与归档的轮廓在缩放时保留所选描边粗细。圆形信息与勾选图标使用和同级状态控件相同的内缩圆环;沿用的 `IconCheckCircleFill` 名称保持空心圆环勾选的外观,并遵循所选描边粗细。 + +上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。`size` prop 控制渲染尺寸。描边路径使用 `non-scaling-stroke`,Regular 保持 1 CSS px,Medium 保持 1.3 CSS px。填充轮廓(包括混合图标中的填充部分)仍随几何缩放,不受 stroke-width 变化影响;固定描边结论不涵盖这些部分。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconMailReadOutlineRegular`/`Medium` 使用打开的信封,`IconMailUnreadOutlineRegular`/`Medium` 使用带未读圆点的闭合信封。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`IconEyeOutlineRegular`/`Medium` 绘制带瞳孔的睁眼,`IconEyeOffOutlineRegular`/`Medium` 在同一轮廓上加一条斜线,用于成对的显示与隐藏开关。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 `Tooltip` 在悬停或键盘聚焦时读取锚点位置,再根据 `ResizeObserver` 提供的边框盒尺寸调整气泡。首次定位前保持隐藏,优先使用指定方向,再尝试相反方向和垂直于该方向的两侧;只要某一侧容得下,就沿锚点平移而不遮挡锚点。左右放置保留 10px 间距,上下放置使用 `gap`(默认 8px)。宽高限制在视口内并保留 12px 边距;文本自动换行,超出视口高度的内容在固定气泡后可滚动。若所有方向都放不下,则使用稳定的视口内回退位置,可能遮挡锚点。视口尺寸变化会重新读取锚点坐标,标签尺寸变化则复用坐标;定位不会同步测量气泡,也不会触发 React 渲染。 触摸按下会关闭未固定的提示,且不会触发悬停提示,包括触摸后的兼容鼠标事件。只有 `(any-hover: hover)` 表明存在可悬停的输入设备时,鼠标进入才会打开提示,从而排除 iOS 因已点击图标变化而生成的鼠标进入事件。仅有触摸输入的设备仍可使用键盘聚焦提示和显式点击打开的说明。信息按钮可显式启用 `openOnClick`,通过鼠标或触摸点击固定气泡供阅读,并将内容关联为锚点的无障碍描述;再次点击、Escape、Tab 或外部 pointerdown 会关闭。普通操作按钮在触摸点击时直接执行操作,不显示 Tooltip。可选的 `onlyWhenClipped` 只在气泡即将显示时锚点或其内部某个 HTML 元素横向溢出才显示气泡,因此重复被省略号截断文本的标签只在能补充信息时出现。 @@ -134,10 +138,12 @@ kind: "package-library" 这些原子组件无法读取应用 locale,因此每段面向用户的文案都必须通过 label prop 提供。`HoverCard`、`TerminalBlock`、`JsonTree`、`CodeBlock`、`MarkdownText`、`JsonBlock`、`ConnectionIndicator`、`Modal`、`DiffBlock`、`ReadBlock`、`SearchBlock`、`WebBlock` 与 `ZoomControls` 接收完整的本地化 label。本包不拥有语言回退;遗漏会导致类型检查失败,各功能会把带类型的 `t` 席位映射到 primitive 的 label 接口。 -`Menu` 的 `anchorRef` 指定组件外部的触发元素,支持同一次提交中稍后挂载的元素,以及在两次打开之间替换的元素。`autoFocus` 菜单通过键盘关闭时,会恢复到打开前仍在页面中的焦点控件。`anchorPoint` 接收客户端视口坐标,与 `event.clientX`/`clientY` 和 `getBoundingClientRect()` 一致。Safari 在菜单打开或坐标变化时将其转换为布局视口坐标一次,后续缩放和平移由 CSS 处理,不持续监听视口或测量矩形。`Menu.contextual` 从该指针位置定位而不避让顶部栏,并在弹窗内右键时关闭。右键弹窗没有实际渲染的 `role="menuitem"` 行时保持隐藏,包括旧 Slot 返回空内容的情况。结构化 `items` 按分隔线组预留图标栏;`footer` 与各子菜单独立计算分组。右键菜单的 `footer` 以分隔线开头时,直接使用该线,不再叠加边框。不透明的 `children` 保留原有布局;数据行后方的旧 Slot 保留其声明的首条分隔线。`exiting` 在淡出期间保留不可交互的弹窗;`returnFocus` 在异步准备后恢复原控件焦点。`MenuSurface.phase` 分别对材质层、直接内容和 macOS 背景淡入淡出,让材质层继续模糊页面。`MENU_TRANSITION_MS` 同时提供 CSS 动画与弹窗生命周期计时。普通下拉菜单不经过右键菜单的准备延迟。 +`Menu` 的 `anchorRef` 指定组件外部的触发元素,支持同一次提交中稍后挂载的元素,以及在两次打开之间替换的元素。打开的菜单在它之外的另一个弹出触发器(带 `aria-haspopup` 的控件)被激活时关闭,包括会拦截自身指针按下的触发器,例如共享右键菜单的按钮;`isExternalTrigger` 认领的触发器由所属弹窗自行处理。`autoFocus` 菜单通过键盘关闭时,会恢复到打开前仍在页面中的焦点控件。`anchorPoint` 接收客户端视口坐标,与 `event.clientX`/`clientY` 和 `getBoundingClientRect()` 一致。Safari 在菜单打开或坐标变化时将其转换为布局视口坐标一次,后续缩放和平移由 CSS 处理,不持续监听视口或测量矩形。`Menu.contextual` 从该指针位置定位而不避让顶部栏,并在弹窗内右键时关闭。右键弹窗没有实际渲染的 `role="menuitem"` 行时保持隐藏,包括旧 Slot 返回空内容的情况。结构化 `items` 按分隔线组预留图标栏;`footer` 与各子菜单独立计算分组。右键菜单的 `footer` 以分隔线开头时,直接使用该线,不再叠加边框。不透明的 `children` 保留原有布局;数据行后方的旧 Slot 保留其声明的首条分隔线。`exiting` 在淡出期间保留不可交互的弹窗;`returnFocus` 在异步准备后恢复原控件焦点。`MenuSurface.phase` 分别对材质层、直接内容和 macOS 背景淡入淡出,让材质层继续模糊页面。`MENU_TRANSITION_MS` 同时提供 CSS 动画与弹窗生命周期计时。普通下拉菜单不经过右键菜单的准备延迟。 ----- +行内链接保留图标完整布局框,按当前字体的大写字母高度中心定位,并保留段落内自然换行。没有说明的弹窗缩短标题至正文的距离;关闭按钮外框与正文及页尾操作共用尾端边缘,图标在较大的点击热区内居中。风险说明与确认勾选共用前导槽和文字起点。 + ## 理解实现 @@ -145,7 +151,7 @@ kind: "package-library" 锚点变为 inert 或隐藏时,portal 菜单会关闭;右键菜单使用 `returnFocus` 提供的原始控件。调用方通过 `isExternalTrigger(node)` 指定外部控件,使其指针按下事件不触发外部关闭,而由自己的切换处理器处理。省略该 prop 时,锚点与菜单面板之外的按下事件都会关闭菜单,包括 `returnFocus` 目标上的按下事件。单独设置 `returnFocus` 只控制焦点恢复。右键菜单打开期间会将自身 ID 加入该控件的 `aria-controls`,关闭时恢复原值。其所属区域保留的内容继续挂载。 -`Menu.listClassName` 独立控制菜单卡片样式,不影响入口容器,也适用于 portal 模式。较高的 portal 菜单使用窗口内的纵向滚动空间时,仍保持与触发元素的横向对齐;只有卡片在该侧放不下时才调整横向位置。前置图标使用 `--dsw-alias-menu-icon` 文本色;破坏性操作图标保留错误色。 +`Menu.listClassName` 独立控制菜单卡片样式,不影响入口容器,也适用于 portal 模式。较高的 portal 菜单使用窗口内的纵向滚动空间时,仍保持与触发元素的横向对齐;只有卡片在该侧放不下时才调整横向位置。前置图标使用 `--dsw-alias-menu-icon` 文本色;破坏性操作图标保留错误色。普通菜单图标和选中勾使用 14px 框,紧凑变体保留 12px 框。线性图标使用 Regular 版本,使实际显示的描边固定为 1px。 子菜单父项显示向右箭头,可通过聚焦、点击或支持悬停的非触摸指针事件展开。菜单行上的 ArrowRight 进入其子级,不激活外部弹窗入口;ArrowLeft 与 Escape 将焦点还给父项。每个子级通过 portal 脱离父级滚动区域,优先向右展开,左侧能容纳时向左翻转,并采用根菜单相同的 visual viewport 限制与 WebKit 坐标归一化规则,在内部限高滚动。两侧均放不下时,点击或 ArrowRight 用子级及返回行替换当前可见的父菜单面板;仅聚焦时仍显示父面板。`submenuBackLabel` 提供该行的本地化文案;省略时使用调用方的父项标签配合向左箭头,返回操作不会选定父项。布局取决于可用空间,不取决于设备 UA;宽屏触控设备也可通过点击展开子级。调整窗口大小时保留已聚焦子项的 DOM 节点。JavaScript 悬停要求 `(any-hover: hover)` 与非触摸指针事件,所以主指针为触摸时,外接鼠标或笔仍可展开子级。兼容鼠标悬停事件不会展开或收起子级。指针宽限允许跨越卡片间隙;同级其他行会关闭原子级。宽限结束关闭子级时,仍在子级中的焦点会回到父项。父项被移除、禁用或其子项清空时,恢复根面板并取消该子菜单。留在被移除子级中的焦点会回到仍可用的父项、首个可用根菜单行或锚点;已经移到其他位置的焦点保持不变。 @@ -162,6 +168,8 @@ kind: "package-library"
    实现细节——点击展开 +Markdown 链接图标保留完整图标框及内部留白。与前文的外间距大于图标到标签的内间距,正文链接仍可换行。 + 本包只做一件事:提供零 cordis、零 slot 知识、仅经 `--dsw-*` token 设置样式的纯 React 原子组件,而所有功能专属的关注点(locale、会话数据、组合)都留在拼装它们的插件中。 ### 源码地图 diff --git a/packages/client/ui-primitives/package.json b/packages/client/ui-primitives/package.json index 6702ddf30d..10148e5f70 100644 --- a/packages/client/ui-primitives/package.json +++ b/packages/client/ui-primitives/package.json @@ -44,7 +44,7 @@ "@types/mdast": "^4.0.4", "micromark-factory-space": "^2.0.1", "micromark-extension-math": "^3.1.0", - "mdast-util-from-markdown": "^2.0.3", + "mdast-util-from-markdown": "^2.1.0", "mdast-util-gfm": "^3.1.0", "mdast-util-math": "^3.0.0", "micromark-extension-gfm": "^3.0.0", diff --git a/packages/client/ui-primitives/src/Checkbox.module.css b/packages/client/ui-primitives/src/Checkbox.module.css index 35bdb05bce..050e6f6132 100644 --- a/packages/client/ui-primitives/src/Checkbox.module.css +++ b/packages/client/ui-primitives/src/Checkbox.module.css @@ -1,22 +1,63 @@ .checkbox { display: inline-flex; align-items: center; - gap: 6px; + gap: 8px; font-size: 14px; line-height: 20px; color: var(--dsw-alias-label-primary); cursor: pointer; } +.control { + position: relative; + display: inline-flex; + flex: none; +} + .checkbox input { + appearance: none; + box-sizing: border-box; flex: 0 0 auto; width: 16px; height: 16px; margin: 0; - accent-color: var(--dsw-alias-brand-primary); + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-bg-layer-1); cursor: inherit; } +.checkbox input:checked { + border-color: var(--dsw-alias-button-primary-fill); + background: var(--dsw-alias-button-primary-fill); +} + +.mark { + position: absolute; + inset: 0; + margin: auto; + display: flex; + width: 12px; + height: 12px; + visibility: hidden; + pointer-events: none; + color: var(--dsw-alias-label-primary-foreground); +} + +.checkbox input:checked + .mark { + visibility: visible; +} + +@media (forced-colors: active) { + .checkbox input { + appearance: auto; + } + + .checkbox input:checked + .mark { + visibility: hidden; + } +} + .checkbox input:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: 2px; diff --git a/packages/client/ui-primitives/src/Checkbox.tsx b/packages/client/ui-primitives/src/Checkbox.tsx index e53456863d..eede18767a 100644 --- a/packages/client/ui-primitives/src/Checkbox.tsx +++ b/packages/client/ui-primitives/src/Checkbox.tsx @@ -1,6 +1,7 @@ /** Controlled native checkbox with a caller-owned visible and accessible label. */ import clsx from 'clsx' +import { IconCheckOutlineRegular } from './icons/index.tsx' import css from './Checkbox.module.css' /** @@ -25,9 +26,12 @@ export function Checkbox({ checked, onChange, label, disabled = false, title, cl }) { return (
    + { onChange(event.target.checked) }} /> + + {label} ) diff --git a/packages/client/ui-primitives/src/HoverCard.module.css b/packages/client/ui-primitives/src/HoverCard.module.css index e98ff29d69..176674d722 100644 --- a/packages/client/ui-primitives/src/HoverCard.module.css +++ b/packages/client/ui-primitives/src/HoverCard.module.css @@ -17,6 +17,48 @@ box-shadow: var(--dsw-shadow-lv3); } +/* A compact card sits beside its anchor's end edge with its top on the + anchor's top: the insets keep it 8px from the anchor and from the viewport's + edges. When that would cross the viewport, the first fallback that fits + places it: beside the start edge; on either side with its bottom at the + viewport's margin; then, with room on neither side, below the anchor from + the anchor's start edge, or above it, so the card does not cover its anchor. + A card too tall for that holds the viewport's bottom and end margins. + Chromium tries five fallbacks, so there the browser's own overflow shift + keeps such a card inside the viewport instead, against its edges. */ +.compact { + position-area: inline-end span-block-end; + inset: 0 8px 8px; + position-try-fallbacks: + flip-inline, + --dsh-hover-card-low, + --dsh-hover-card-low flip-inline, + --dsh-hover-card-below, + --dsh-hover-card-above, + --dsh-hover-card-held; +} + +@position-try --dsh-hover-card-low { + position-area: inline-end span-all; + align-self: end; +} + +@position-try --dsh-hover-card-below { + position-area: block-end span-inline-end; + inset: 8px 8px 8px 0; +} + +@position-try --dsh-hover-card-above { + position-area: block-start span-inline-end; + inset: 8px 8px 8px 0; +} + +@position-try --dsh-hover-card-held { + position-area: span-all; + justify-self: end; + align-self: end; +} + .copyable { cursor: pointer; } diff --git a/packages/client/ui-primitives/src/HoverCard.tsx b/packages/client/ui-primitives/src/HoverCard.tsx index bd727d0c85..1bf15d713e 100644 --- a/packages/client/ui-primitives/src/HoverCard.tsx +++ b/packages/client/ui-primitives/src/HoverCard.tsx @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useCallback, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode, RefObject, SyntheticEvent } from 'react' import clsx from 'clsx' import { createPortal } from 'react-dom' @@ -16,15 +16,19 @@ const INLINE_PREVIEW_WIDTH = 300 const ANCHOR_GAP = 8 const VIEWPORT_MARGIN = 8 +/** Where the script places a card; a compact card has no coordinates, since the stylesheet anchors it. */ interface CardPosition { - left: number - top: number + left?: number + top?: number width?: number maxWidth?: number maxHeight?: number bridge?: { left: number; top: number; width: number; height: number } } +/** The position of every compact card: one value, so placing it again renders nothing. */ +const ANCHORED: CardPosition = {} + /** * Render an anchor with a hover-triggered preview card independently of nested tooltips. * Touch entry does not open a preview or intercept the anchor's action. @@ -32,9 +36,11 @@ interface CardPosition { * @param props.content - card content; the pointer may rest on it, so it is * readable and selectable, but it carries no dismissal affordance of its own. * @param props.openDelayMs - hover dwell before the card shows (default 500). - * @param props.variant - compact card beside the anchor, or a preview above/below it - * with 24px side insets, a 420px height cap, the frame-top clearance (capped below an anchor inside the top strip), - * and 100ms opacity transitions. + * @param props.variant - compact card beside the anchor's end edge, or its start edge when only that side fits, or + * below the anchor, else above it, when neither side fits, or in the viewport's bottom end corner when it is too + * tall for those, which the stylesheet decides by CSS anchor positioning; or a preview above/below it with 24px + * side insets, a 420px height cap, the frame-top clearance (capped below an anchor inside the top strip), and 100ms + * opacity transitions. * @param props.widthAnchorRef - optional element whose width and horizontal position size the preview. * @param props.inline - keep the anchor in prose; show a contained preview on hover or keyboard focus. * Its hover region connects the anchor and preview across the visual gap. @@ -67,6 +73,8 @@ export function HoverCard({ copyLabel?: string copiedLabel?: string })) { + const compact = variant !== 'preview' && !inline + const anchorName = `--dsh-hover-card-${useId().replaceAll(':', '')}` const rootRef = useRef(null) const cardRef = useRef(null) const portalRef = useRef(null) @@ -168,6 +176,8 @@ export function HoverCard({ // Fixed-position from the anchor rect before paint; track the anchor while // open (capture-phase scroll catches nested panes), as in Menu portal mode. + // The stylesheet anchors a compact card, so it needs neither the rect nor + // the tracking. useLayoutEffect(() => { if (!open) { setPos(null); return } const place = () => { @@ -178,6 +188,10 @@ export function HoverCard({ dismissImmediately() return } + if (compact) { + setPos(ANCHORED) + return + } const r = wrapper.getBoundingClientRect() const h = cardRef.current?.offsetHeight ?? 0 if (variant === 'preview') { @@ -196,32 +210,27 @@ export function HoverCard({ }) return } - if (inline) { - const height = Math.max(h, cardRef.current?.scrollHeight ?? 0) - const maxWidth = Math.max(0, Math.min(INLINE_PREVIEW_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2)) - const width = fitContent ? Math.min(cardRef.current?.offsetWidth ?? maxWidth, maxWidth) : maxWidth - const topMargin = overlayTopMargin(VIEWPORT_MARGIN, r, ANCHOR_GAP) - const belowTop = Math.max(topMargin, r.bottom + ANCHOR_GAP) - const above = Math.max(0, r.top - ANCHOR_GAP - topMargin) - const below = Math.max(0, window.innerHeight - belowTop - VIEWPORT_MARGIN) - const onTop = height > below && above > below - const maxHeight = onTop ? above : below - const left = Math.max(VIEWPORT_MARGIN, Math.min(r.left, window.innerWidth - width - VIEWPORT_MARGIN)) - const top = onTop ? r.top - ANCHOR_GAP - Math.min(height, maxHeight) : belowTop - const bridgeTop = onTop ? top + Math.min(height, maxHeight) : r.bottom - const bridgeLeft = Math.min(r.left, left) - setPos({ - left, top, ...fitContent ? {} : { width }, maxWidth, maxHeight, - bridge: { - left: bridgeLeft, top: bridgeTop, - width: Math.max(r.right, left + width) - bridgeLeft, - height: Math.max(0, (onTop ? r.top : top) - bridgeTop), - }, - }) - return - } - const top = r.top + h > window.innerHeight - VIEWPORT_MARGIN ? window.innerHeight - h - VIEWPORT_MARGIN : r.top - setPos({ left: r.right + ANCHOR_GAP, top }) + const height = Math.max(h, cardRef.current?.scrollHeight ?? 0) + const maxWidth = Math.max(0, Math.min(INLINE_PREVIEW_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2)) + const width = fitContent ? Math.min(cardRef.current?.offsetWidth ?? maxWidth, maxWidth) : maxWidth + const topMargin = overlayTopMargin(VIEWPORT_MARGIN, r, ANCHOR_GAP) + const belowTop = Math.max(topMargin, r.bottom + ANCHOR_GAP) + const above = Math.max(0, r.top - ANCHOR_GAP - topMargin) + const below = Math.max(0, window.innerHeight - belowTop - VIEWPORT_MARGIN) + const onTop = height > below && above > below + const maxHeight = onTop ? above : below + const left = Math.max(VIEWPORT_MARGIN, Math.min(r.left, window.innerWidth - width - VIEWPORT_MARGIN)) + const top = onTop ? r.top - ANCHOR_GAP - Math.min(height, maxHeight) : belowTop + const bridgeTop = onTop ? top + Math.min(height, maxHeight) : r.bottom + const bridgeLeft = Math.min(r.left, left) + setPos({ + left, top, ...fitContent ? {} : { width }, maxWidth, maxHeight, + bridge: { + left: bridgeLeft, top: bridgeTop, + width: Math.max(r.right, left + width) - bridgeLeft, + height: Math.max(0, (onTop ? r.top : top) - bridgeTop), + }, + }) } place() // Observe only the anchor's ancestors: an offscreen drawer can hide without resizing its retained row. @@ -229,31 +238,21 @@ export function HoverCard({ for (let ancestor = rootRef.current?.parentElement; ancestor != null; ancestor = ancestor.parentElement) { visibility.observe(ancestor, { attributes: true, attributeFilter: ['inert', 'hidden'] }) } - const observer = (variant === 'preview' || inline) && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(place) : null + const observer = !compact && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(place) : null for (const element of [cardRef.current, rootRef.current, widthAnchorRef?.current]) { if (element !== null && element !== undefined) observer?.observe(element) } - window.addEventListener('scroll', place, true) - window.addEventListener('resize', place) + if (!compact) { + window.addEventListener('scroll', place, true) + window.addEventListener('resize', place) + } return () => { observer?.disconnect() visibility.disconnect() window.removeEventListener('scroll', place, true) window.removeEventListener('resize', place) } - }, [open, variant, widthAnchorRef, positioned, inline, fitContent, dismissImmediately]) - - // The first placement ran before the card mounted (height read 0): once the - // card's real height is measurable, correct the bottom-edge clamp. The - // correction converges — a clamped top satisfies the guard, so it runs once. - useLayoutEffect(() => { - if (!open || pos === null || variant === 'preview' || inline) return - /* v8 ignore next -- the card is mounted whenever pos is set, so the ref is attached here. */ - const h = cardRef.current?.offsetHeight ?? 0 - if (pos.top + h > window.innerHeight - VIEWPORT_MARGIN) { - setPos({ left: pos.left, top: window.innerHeight - h - VIEWPORT_MARGIN }) - } - }, [open, pos, variant, inline]) + }, [open, compact, variant, widthAnchorRef, positioned, fitContent, dismissImmediately]) const copy = async (text: string): Promise => { if (copied || copyingRef.current) return @@ -280,9 +279,13 @@ export function HoverCard({ const card = open && pos !== null && (
    { if (!disabled && event.target.matches(':focus-visible')) { cancelClose(); setPhase('open') } } : undefined} diff --git a/packages/client/ui-primitives/src/Input.module.css b/packages/client/ui-primitives/src/Input.module.css index 30ff82da20..d01f6361d3 100644 --- a/packages/client/ui-primitives/src/Input.module.css +++ b/packages/client/ui-primitives/src/Input.module.css @@ -34,5 +34,11 @@ } .input::placeholder { - color: var(--dsw-alias-label-dimmed); + color: var(--dsw-alias-label-tertiary); +} + +@media (pointer: coarse) { + .input { + font-size: 16px; + } } diff --git a/packages/client/ui-primitives/src/LinkIcon.tsx b/packages/client/ui-primitives/src/LinkIcon.tsx index d8f8347282..312a71b193 100644 --- a/packages/client/ui-primitives/src/LinkIcon.tsx +++ b/packages/client/ui-primitives/src/LinkIcon.tsx @@ -53,25 +53,25 @@ export function classifyLinkPath(path: string): LinkIconKind { const PhotoGlyph = ({ size, className, strokeWidth }: IconProps & { strokeWidth: number }) => ( ) const PaperDocGlyph = ({ size, className, strokeWidth }: IconProps & { strokeWidth: number }) => ( ) const PaperGlyph = ({ size, className, strokeWidth }: IconProps & { strokeWidth: number }) => ( ) diff --git a/packages/client/ui-primitives/src/Marquee.module.css b/packages/client/ui-primitives/src/Marquee.module.css new file mode 100644 index 0000000000..562113c9fe --- /dev/null +++ b/packages/client/ui-primitives/src/Marquee.module.css @@ -0,0 +1,47 @@ +/* Single-line text that clips with an ellipsis at rest. While it marquees + (data-marquee), the ellipsis drops, the inner span travels to the far edge + over the distance and time the hook measured, and both clipping edges fade + in over 12px instead of hard-cutting a character. */ +.text { + display: block; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* At the far edge the end fade lifts so the final character reads at full + strength: a zero-length animation, delayed by the travel's duration, swaps + the mask and holds it. */ +.text[data-marquee] { + text-overflow: clip; + mask-image: linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent); + animation: dsh-marquee-arrive 0s var(--dsh-marquee-duration) forwards; +} + +@keyframes dsh-marquee-arrive { + to { mask-image: linear-gradient(to right, transparent, #000 12px); } +} + +/* Inline at rest, so the ellipsis cuts between characters; a transform needs a box. */ +.text[data-marquee] > .travel { + display: inline-block; + animation: dsh-marquee-travel var(--dsh-marquee-duration) linear forwards; +} + +@keyframes dsh-marquee-travel { + to { transform: translateX(calc(-1 * var(--dsh-marquee-range))); } +} + +/* Reduced motion shows the far edge at once, so only the start edge hides text. */ +@media (prefers-reduced-motion: reduce) { + .text[data-marquee] { + mask-image: linear-gradient(to right, transparent, #000 12px); + animation: none; + } + + .text[data-marquee] > .travel { + animation: none; + transform: translateX(calc(-1 * var(--dsh-marquee-range))); + } +} diff --git a/packages/client/ui-primitives/src/Marquee.tsx b/packages/client/ui-primitives/src/Marquee.tsx new file mode 100644 index 0000000000..0bbf0d3b3d --- /dev/null +++ b/packages/client/ui-primitives/src/Marquee.tsx @@ -0,0 +1,109 @@ +// Hover marquee for single-line text that its cell clips: while the pointer is +// on the owning row, a CSS animation carries the text to its far edge, and +// leaving returns it to the start. + +import { forwardRef, useCallback, useEffect, useMemo, useRef } from 'react' +import type { HTMLAttributes, PointerEvent, RefObject } from 'react' +import clsx from 'clsx' +import css from './Marquee.module.css' + +/* Overflow this small hides no meaningful tail; travelling for it reads as an + accidental jitter, so the text stays put. */ +const MIN_REVEAL_PX = 8 + +/* Travel speed: slow enough to read the text as it passes. */ +const PX_PER_MS = 0.03 + +/** Pointer handlers of the row whose hover marquees one text; spread them onto the row. */ +export interface HoverMarquee { + /** Start the travel; touch pointers and text that fits do nothing. */ + readonly onPointerEnter: (event: PointerEvent) => void + /** Return the text to its start in one step, unless the marquee is held. */ + readonly onPointerLeave: () => void +} + +/** Options of {@link useHoverMarquee}. */ +export interface HoverMarqueeOptions { + /** Marquee the text while true, with or without the pointer on the row, such as while the row's menu is open. */ + readonly hold?: boolean | undefined +} + +/** + * Start the text's travel unless it already marquees: measure how far the text + * overflows its cell, and hand the stylesheet that distance and the time it + * takes at the constant speed. + * @param text - the clipping text element. + */ +function travel(text: HTMLElement): void { + if (text.dataset.marquee !== undefined) return + const range = text.scrollWidth - text.clientWidth + if (range <= MIN_REVEAL_PX) return + text.style.setProperty('--dsh-marquee-range', `${range}px`) + text.style.setProperty('--dsh-marquee-duration', `${Math.round(range / PX_PER_MS)}ms`) + text.dataset.marquee = '' +} + +/** + * Return the text to its resting state: at its start, with the ellipsis and + * without fades. + * @param text - the clipping text element. + */ +function rest(text: HTMLElement): void { + delete text.dataset.marquee + text.style.removeProperty('--dsh-marquee-range') + text.style.removeProperty('--dsh-marquee-duration') +} + +/** + * Marquee one-line text wider than its cell while the pointer is on its row: + * the text travels at 30px/s until its far edge is in view, then rests there + * under the pointer. Overflow of at most 8px stays put. Leaving returns the + * text to the start in one step, because the resting ellipsis and the narrowed + * cell would otherwise meet the text while it travelled back. The stylesheet + * animates the travel and its fades, so the script only measures the overflow + * once per entry; reduced motion shows the far edge at once. + * @param text - ref to the clipping text element, a {@link MarqueeText}. + * @param options - whether the marquee is held without the pointer. + * @returns stable pointer enter and leave handlers for the row. + */ +export function useHoverMarquee(text: RefObject, { hold = false }: HoverMarqueeOptions = {}): HoverMarquee { + const hovered = useRef(false) + const held = useRef(hold) + const sync = useCallback((): void => { + const element = text.current + if (element === null) return + if (hovered.current || held.current) travel(element) + else rest(element) + }, [text]) + useEffect(() => { + held.current = hold + sync() + }, [hold, sync]) + return useMemo(() => ({ + onPointerEnter: (event: PointerEvent): void => { + if (event.pointerType === 'touch') return + hovered.current = true + sync() + }, + onPointerLeave: (): void => { + hovered.current = false + sync() + }, + }), [sync]) +} + +/** Props of single-line text that a {@link useHoverMarquee} can marquee. */ +export type MarqueeTextProps = HTMLAttributes + +/** + * Render single-line text that clips with an ellipsis at rest and, while a + * {@link useHoverMarquee} marquees it, drops the ellipsis and fades whichever + * edge still hides text. The children sit in an inner span, which travels. + */ +export const MarqueeText = forwardRef(function MarqueeText({ className, children, ...attributes }, ref) { + return ( + + {children} + + ) +}) diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index 47b31bb407..8af49993dc 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -119,9 +119,11 @@ export function MenuItemButton({ onSelect, ...props }: MenuItemButtonProps) { * @param props.selectedId - row shown as selected. * @param props.selectedIds - rows shown as selected when a menu contains independent option groups. * @param props.onSelect - data-row activation callback (not called for disabled rows or submenu parents that only open children). - * @param props.onClose - invoked on outside click, Escape, or a window blur - * that moved focus into an iframe (the only signal a pointerdown inside a - * cross-origin iframe leaves). + * @param props.onClose - invoked on outside click, on activating another popup + * trigger (an `aria-haspopup` control outside this menu that + * `isExternalTrigger` does not claim) even when that trigger stops its + * pointer presses, on Escape, or on a window blur that moved focus into an + * iframe (the only signal a pointerdown inside a cross-origin iframe leaves). * @param props.align - list alignment against the anchor (default 'start'). * @param props.side - open below (`bottom`, default) or above (`top`) the anchor. * @param props.portal - render the list into document.body, fixed-positioned @@ -337,6 +339,17 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel if (listRef.current?.contains(e.target) === true || submenuEvents.current.contains(e.target)) return onClose() } + // Activating another popup trigger closes this menu even when that trigger + // isolates its presses from its owners, as the shared context-menu button + // does: its pointerdown never reaches the listener above, so the + // activating click is caught in the capture phase instead. + const onOtherTrigger = (e: MouseEvent) => { + const trigger = e.target instanceof Element ? e.target.closest('[aria-haspopup]') : null + if (trigger === null || rootRef.current?.contains(trigger) === true || anchorRef?.current?.contains(trigger) === true) return + if (isExternalTrigger?.(trigger) === true) return + if (listRef.current?.contains(trigger) === true || submenuEvents.current.contains(trigger)) return + onClose() + } const onKeyDown = (e: KeyboardEvent) => { if (composition.guards(e) || isBehindModal(triggerRef.current ?? rootRef.current) || e.defaultPrevented || e.ctrlKey || e.altKey || e.metaKey) return @@ -435,6 +448,7 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel if (document.activeElement instanceof HTMLIFrameElement) onClose() } document.addEventListener('pointerdown', onPointerDown) + document.addEventListener('click', onOtherTrigger, true) const onEscape = (event: KeyboardEvent): void => { if (event.key === 'Escape') onKeyDown(event) } const onOtherKey = (event: KeyboardEvent): void => { if (event.key !== 'Escape') onKeyDown(event) } document.addEventListener('keydown', onOtherKey) @@ -443,6 +457,7 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel return () => { composition.dispose() document.removeEventListener('pointerdown', onPointerDown) + document.removeEventListener('click', onOtherTrigger, true) document.removeEventListener('keydown', onOtherKey) document.removeEventListener('keydown', onEscape, true) window.removeEventListener('blur', onWindowBlur) diff --git a/packages/client/ui-primitives/src/Modal.module.css b/packages/client/ui-primitives/src/Modal.module.css index d1a67e6a61..8a1662e8e3 100644 --- a/packages/client/ui-primitives/src/Modal.module.css +++ b/packages/client/ui-primitives/src/Modal.module.css @@ -66,14 +66,13 @@ width: 100%; } -/* Header row (figma Title row): pad l24/t22/r14/b12, SPACE_BETWEEN — - * title left, close button right. */ +/* Header controls and footer actions share the content column's trailing edge. */ .header { display: flex; align-items: center; justify-content: space-between; gap: 8px; - padding: 22px 14px 12px 24px; + padding: 22px 24px 12px; } .title { @@ -96,7 +95,7 @@ color: var(--dsw-alias-state-warn-primary); } -.warning .body { +.warning .header + .body { margin-top: 0; } @@ -107,6 +106,7 @@ justify-content: center; width: 28px; height: 28px; + padding: 0; border: none; border-radius: var(--dsw-radius-sm); background: transparent; @@ -138,6 +138,10 @@ padding: 0 24px; } +.header + .body { + margin-top: 8px; +} + .footer { display: flex; align-items: center; diff --git a/packages/client/ui-primitives/src/PermissionIcon.tsx b/packages/client/ui-primitives/src/PermissionIcon.tsx index ee480c8c2d..065d1e44ab 100644 --- a/packages/client/ui-primitives/src/PermissionIcon.tsx +++ b/packages/client/ui-primitives/src/PermissionIcon.tsx @@ -9,8 +9,8 @@ interface PermissionIconArtworkProps extends IconProps { function ReadOnlyArtwork({ size = 16, className, strokeWidth }: PermissionIconArtworkProps): ReactNode { return ( ) } @@ -18,11 +18,9 @@ function ReadOnlyArtwork({ size = 16, className, strokeWidth }: PermissionIconAr function WorkspaceWriteArtwork({ size = 16, className, strokeWidth }: PermissionIconArtworkProps): ReactNode { return ( ) } @@ -30,9 +28,9 @@ function WorkspaceWriteArtwork({ size = 16, className, strokeWidth }: Permission function FullAccessArtwork({ size = 16, className, strokeWidth }: PermissionIconArtworkProps): ReactNode { return ( ) } @@ -40,8 +38,8 @@ function FullAccessArtwork({ size = 16, className, strokeWidth }: PermissionIcon function AutoReviewArtwork({ size = 16, className, strokeWidth }: PermissionIconArtworkProps): ReactNode { return ( ) } diff --git a/packages/client/ui-primitives/src/Pill.module.css b/packages/client/ui-primitives/src/Pill.module.css index 7295f702b8..ae9bcb066b 100644 --- a/packages/client/ui-primitives/src/Pill.module.css +++ b/packages/client/ui-primitives/src/Pill.module.css @@ -18,7 +18,7 @@ } @media (hover: hover) { - .interactive:hover { + .interactive:hover:where(:not(:disabled):not(.active)) { background: var(--dsw-alias-interactive-bg-hover); } } @@ -28,3 +28,13 @@ background: var(--dsw-alias-button-ghost-active-fill); box-shadow: inset 0 0 0 1px var(--dsw-alias-button-ghost-active-border); } + +.interactive:disabled { + cursor: default; + opacity: 0.4; +} + +.interactive:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 2px; +} diff --git a/packages/client/ui-primitives/src/RiskConfirmation.module.css b/packages/client/ui-primitives/src/RiskConfirmation.module.css index 6a7db49ffa..208553f121 100644 --- a/packages/client/ui-primitives/src/RiskConfirmation.module.css +++ b/packages/client/ui-primitives/src/RiskConfirmation.module.css @@ -25,6 +25,7 @@ .confirmation .acknowledgement { align-items: flex-start; + gap: 6px; margin-top: 16px; color: var(--dsw-alias-label-secondary); font-size: 14px; @@ -32,10 +33,14 @@ line-height: 20px; } +.confirmation .acknowledgement > :first-child { + margin-top: 3px; +} + .confirmation .acknowledgement input { width: 14px; height: 14px; - margin-top: 3px; + margin: 0; } .modalAction { diff --git a/packages/client/ui-primitives/src/SegmentedTabs.module.css b/packages/client/ui-primitives/src/SegmentedTabs.module.css index a4edb7ada9..35e4a5a5a3 100644 --- a/packages/client/ui-primitives/src/SegmentedTabs.module.css +++ b/packages/client/ui-primitives/src/SegmentedTabs.module.css @@ -38,14 +38,14 @@ } @media (hover: hover) { - .tab:hover { + .tab:hover:not(:disabled) { background: transparent; color: var(--dsw-alias-label-primary); } } .tab[aria-selected='true'] { - font-weight: 600; + font-weight: 500; } .tabs[data-size='sm'] { @@ -58,15 +58,9 @@ height: 30px; } -.tabs[data-size='sm'] .tab[aria-selected='true'] { - font-weight: 500; -} - .tab:focus-visible { - outline: none; - text-decoration: underline; - text-decoration-thickness: 1px; - text-underline-offset: 4px; + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -2px; } @media (prefers-reduced-motion: reduce) { diff --git a/packages/client/ui-primitives/src/TitleMarquee.module.css b/packages/client/ui-primitives/src/TitleMarquee.module.css deleted file mode 100644 index 7fa7e1ca34..0000000000 --- a/packages/client/ui-primitives/src/TitleMarquee.module.css +++ /dev/null @@ -1,17 +0,0 @@ -/* While the marquee travels, both clipping edges fade in over 12px instead of - hard-cutting a character: the left once the title has moved off its start - (data-scrolled), the right while text still remains beyond the cell - (data-clipped). At the far edge the right fade lifts so the final character - reads at full strength. The mask rides the title element itself, so cells - beside it keep their full color. */ -.marquee[data-scrolled] { - mask-image: linear-gradient(to right, transparent, #000 12px); -} - -.marquee[data-clipped] { - mask-image: linear-gradient(to left, transparent, #000 12px); -} - -.marquee[data-scrolled][data-clipped] { - mask-image: linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent); -} diff --git a/packages/client/ui-primitives/src/icons/artwork.ts b/packages/client/ui-primitives/src/icons/artwork.ts index 76e4235739..4f6f1e3b26 100644 --- a/packages/client/ui-primitives/src/icons/artwork.ts +++ b/packages/client/ui-primitives/src/icons/artwork.ts @@ -20,101 +20,102 @@ interface IconArtwork { /** Default artwork keyed by glyph name; symbol ids derive from these keys. */ export const ICON_ARTWORK = { - 'mail-unread-outline': { size: 16, svg: strokeWidth => `` }, - 'mail-read-outline': { size: 16, svg: strokeWidth => `` }, - 'layers-outline': { size: 16, svg: strokeWidth => `` }, + 'mail-unread-outline': { size: 16, svg: strokeWidth => `` }, + 'mail-read-outline': { size: 16, svg: strokeWidth => `` }, + 'layers-outline': { size: 16, svg: strokeWidth => `` }, 'save-outline': { size: 16, svg: strokeWidth => `` }, - 'new-chat-outline': { size: 16, svg: strokeWidth => `` }, - 'search-outline': { size: 16, svg: strokeWidth => `` }, - 'eye-outline': { size: 16, svg: strokeWidth => `` }, - 'eye-off-outline': { size: 16, svg: strokeWidth => `` }, - 'globe-outline': { size: 14, svg: strokeWidth => `` }, - 'settings-outline': { size: 16, svg: strokeWidth => `` }, - 'panel-left-outline': { size: 16, svg: strokeWidth => `` }, + 'new-chat-outline': { size: 16, svg: strokeWidth => `` }, + 'search-outline': { size: 16, svg: strokeWidth => `` }, + 'eye-outline': { size: 16, svg: strokeWidth => `` }, + 'eye-off-outline': { size: 16, svg: strokeWidth => `` }, + 'globe-outline': { size: 14, svg: strokeWidth => `` }, + 'settings-outline': { size: 16, svg: strokeWidth => `` }, + 'panel-left-outline': { size: 16, svg: strokeWidth => `` }, 'ellipsis-outline': { size: 16, svg: strokeWidth => `` }, - 'plus-outline': { size: 16, svg: strokeWidth => `` }, - 'check-outline': { size: 16, svg: strokeWidth => `` }, - 'branch-outline': { size: 16, svg: strokeWidth => `` }, - 'chevron-down-outline': { size: 14, svg: strokeWidth => `` }, - 'chevron-left-outline': { size: 14, svg: strokeWidth => `` }, - 'chevron-right-outline': { size: 14, svg: strokeWidth => `` }, + 'plus-outline': { size: 16, svg: strokeWidth => `` }, + 'check-outline': { size: 16, svg: strokeWidth => `` }, + 'branch-outline': { size: 16, svg: strokeWidth => `` }, + 'chevron-down-outline': { size: 14, svg: strokeWidth => `` }, + 'chevron-left-outline': { size: 14, svg: strokeWidth => `` }, + 'chevron-right-outline': { size: 14, svg: strokeWidth => `` }, 'triangle-right-fill': { size: 14, svg: strokeWidth => `` }, - 'chevron-up-outline': { size: 14, svg: strokeWidth => `` }, - 'close-outline': { size: 16, svg: strokeWidth => `` }, - 'close-fill': { size: 14, svg: strokeWidth => `` }, + 'chevron-up-outline': { size: 14, svg: strokeWidth => `` }, + 'close-outline': { size: 16, svg: strokeWidth => `` }, + 'close-fill': { size: 14, svg: strokeWidth => `` }, 'close-circle-fill': { size: 16, svg: strokeWidth => `` }, - 'copy-outline': { size: 16, svg: strokeWidth => `` }, - 'refresh-outline': { size: 16, svg: strokeWidth => `` }, - 'like-outline': { size: 16, svg: strokeWidth => `` }, - 'like-fill': { size: 16, svg: strokeWidth => `` }, - 'dislike-outline': { size: 16, svg: strokeWidth => `` }, - 'dislike-fill': { size: 16, svg: strokeWidth => `` }, - 'share-outline': { size: 16, svg: strokeWidth => `` }, - 'deliver-doc': { size: 16, svg: strokeWidth => `` }, - 'edit-outline': { size: 16, svg: strokeWidth => `` }, - 'think-outline': { size: 16, svg: strokeWidth => `` }, - 'agent-preset-outline': { size: 16, svg: strokeWidth => `` }, - 'browse-outline': { size: 16, svg: strokeWidth => `` }, - 'context-injection-outline': { size: 16, svg: strokeWidth => `` }, - 'link-outline': { size: 16, svg: strokeWidth => `` }, - 'right-up-outline': { size: 16, svg: strokeWidth => `` }, - 'enhance-outline': { size: 16, svg: strokeWidth => `` }, - 'trash-outline': { size: 16, svg: strokeWidth => `` }, - 'warning-outline': { size: 16, svg: strokeWidth => `` }, - 'check-circle-fill': { size: 16, svg: strokeWidth => `` }, - 'warning-triangle-outline': { size: 16, svg: strokeWidth => `` }, - 'user-outline': { size: 16, svg: strokeWidth => `` }, + 'copy-outline': { size: 16, svg: strokeWidth => `` }, + 'refresh-outline': { size: 16, svg: strokeWidth => `` }, + 'like-outline': { size: 16, svg: strokeWidth => `` }, + 'like-fill': { size: 16, svg: strokeWidth => `` }, + 'dislike-outline': { size: 16, svg: strokeWidth => `` }, + 'dislike-fill': { size: 16, svg: strokeWidth => `` }, + 'share-outline': { size: 16, svg: strokeWidth => `` }, + 'deliver-doc': { size: 16, svg: strokeWidth => `` }, + 'edit-outline': { size: 16, svg: strokeWidth => `` }, + 'think-outline': { size: 16, svg: strokeWidth => `` }, + 'agent-preset-outline': { size: 16, svg: strokeWidth => `` }, + 'browse-outline': { size: 16, svg: strokeWidth => `` }, + 'context-injection-outline': { size: 16, svg: strokeWidth => `` }, + 'link-outline': { size: 16, svg: strokeWidth => `` }, + 'right-up-outline': { size: 16, svg: strokeWidth => `` }, + 'enhance-outline': { size: 16, svg: strokeWidth => `` }, + 'trash-outline': { size: 16, svg: strokeWidth => `` }, + 'warning-outline': { size: 16, svg: strokeWidth => `` }, + 'check-circle-fill': { size: 16, svg: strokeWidth => `` }, + 'warning-triangle-outline': { size: 16, svg: strokeWidth => `` }, + 'user-outline': { size: 16, svg: strokeWidth => `` }, // Users has inset contours in the 16px box; only coordinates, never stroke widths, carry the inset. - 'users-outline': { size: 16, svg: strokeWidth => `` }, - 'paper-plane-outline': { size: 14, svg: strokeWidth => `` }, + 'users-outline': { size: 16, svg: strokeWidth => `` }, + 'paper-plane-outline': { size: 14, svg: strokeWidth => `` }, 'stop-fill': { size: 16, svg: strokeWidth => `` }, - 'paperclip-outline': { size: 16, svg: strokeWidth => `` }, - 'loading-outline': { size: 16, svg: strokeWidth => `` }, - 'download-outline': { size: 16, svg: strokeWidth => `` }, - 'upload-outline': { size: 16, svg: strokeWidth => `` }, - 'play-outline': { size: 16, svg: strokeWidth => `` }, - 'pause-outline': { size: 16, svg: strokeWidth => `` }, - 'fullscreen-outline': { size: 16, svg: strokeWidth => `` }, - 'code-outline': { size: 16, svg: strokeWidth => `` }, - 'cordis-plugin-outline': { size: 14, svg: strokeWidth => `` }, - 'api-outline': { size: 14, svg: strokeWidth => `` }, - 'personalization-outline': { size: 16, svg: strokeWidth => `` }, - 'project-add-outline': { size: 16, svg: strokeWidth => `` }, - 'folder-open-outline': { size: 16, svg: strokeWidth => `` }, + 'paperclip-outline': { size: 16, svg: strokeWidth => `` }, + 'loading-outline': { size: 16, svg: strokeWidth => `` }, + 'download-outline': { size: 16, svg: strokeWidth => `` }, + 'upload-outline': { size: 16, svg: strokeWidth => `` }, + 'play-outline': { size: 16, svg: strokeWidth => `` }, + 'pause-outline': { size: 16, svg: strokeWidth => `` }, + 'fullscreen-outline': { size: 16, svg: strokeWidth => `` }, + 'code-outline': { size: 16, svg: strokeWidth => `` }, + 'cordis-plugin-outline': { size: 14, svg: strokeWidth => `` }, + 'api-outline': { size: 14, svg: strokeWidth => `` }, + 'personalization-outline': { size: 16, svg: strokeWidth => `` }, + 'project-add-outline': { size: 16, svg: strokeWidth => `` }, + 'folder-open-outline': { size: 16, svg: strokeWidth => `` }, 'folder-open': { size: 16, svg: strokeWidth => `` }, - 'folder-close': { size: 16, svg: strokeWidth => `` }, - 'tree-corner': { size: 10, aspect: [8, 10], svg: strokeWidth => `` }, - 'light-outline': { size: 16, svg: strokeWidth => `` }, - 'dark-outline': { size: 16, svg: strokeWidth => `` }, - 'followsystem-outline': { size: 16, svg: strokeWidth => `` }, - 'data-outline': { size: 16, svg: strokeWidth => `` }, - 'database-outline': { size: 16, svg: strokeWidth => `` }, - 'clock-outline': { size: 16, svg: strokeWidth => `` }, - 'gauge-outline': { size: 16, svg: strokeWidth => `` }, - 'send-outline': { size: 14, svg: strokeWidth => `` }, - 'queue-outline': { size: 14, svg: strokeWidth => `` }, - 'checklist-outline': { size: 14, svg: strokeWidth => `` }, - 'list-pen-outline': { size: 16, svg: strokeWidth => `` }, - 'goal-outline': { size: 16, svg: strokeWidth => `` }, - 'sparkle': { size: 16, svg: strokeWidth => `` }, - 'inspect-outline': { size: 12, svg: strokeWidth => `` }, - 'skill-outline': { size: 16, svg: strokeWidth => `` }, - 'question-outline': { size: 14, svg: strokeWidth => `` }, - 'info-outline': { size: 14, svg: strokeWidth => `` }, - 'plugin-pinwheel-outline': { size: 16, svg: strokeWidth => `` }, - 'alarm-clock-outline': { size: 16, svg: strokeWidth => `` }, - 'archive-outline': { size: 20, svg: strokeWidth => `` }, - 'wrap-lines-outline': { size: 16, svg: strokeWidth => `` }, + 'folder-close': { size: 16, svg: strokeWidth => `` }, + 'tree-corner': { size: 10, aspect: [8, 10], svg: strokeWidth => `` }, + 'light-outline': { size: 16, svg: strokeWidth => `` }, + 'dark-outline': { size: 16, svg: strokeWidth => `` }, + 'followsystem-outline': { size: 16, svg: strokeWidth => `` }, + 'data-outline': { size: 16, svg: strokeWidth => `` }, + 'database-outline': { size: 16, svg: strokeWidth => `` }, + 'clock-outline': { size: 16, svg: strokeWidth => `` }, + 'gauge-outline': { size: 16, svg: strokeWidth => `` }, + 'send-outline': { size: 14, svg: strokeWidth => `` }, + 'queue-outline': { size: 14, svg: strokeWidth => `` }, + 'checklist-outline': { size: 14, svg: strokeWidth => `` }, + 'list-pen-outline': { size: 16, svg: strokeWidth => `` }, + 'files-diff-outline': { size: 16, svg: strokeWidth => `` }, + 'goal-outline': { size: 16, svg: strokeWidth => `` }, + 'sparkle': { size: 16, svg: strokeWidth => `` }, + 'inspect-outline': { size: 12, svg: strokeWidth => `` }, + 'skill-outline': { size: 16, svg: strokeWidth => `` }, + 'question-outline': { size: 14, svg: strokeWidth => `` }, + 'info-outline': { size: 14, svg: strokeWidth => `` }, + 'plugin-pinwheel-outline': { size: 16, svg: strokeWidth => `` }, + 'alarm-clock-outline': { size: 16, svg: strokeWidth => `` }, + 'archive-outline': { size: 20, svg: strokeWidth => `` }, + 'wrap-lines-outline': { size: 16, svg: strokeWidth => `` }, 'nowrap-fill': { size: 16, svg: () => '' }, 'wrap-fill': { size: 16, svg: () => '' }, - 'compare-split-outline': { size: 16, svg: strokeWidth => `` }, - 'plan-outline': { size: 14, svg: strokeWidth => `` }, - 'compact-outline': { size: 16, svg: strokeWidth => `` }, - 'shield-outline': { size: 16, svg: strokeWidth => `` }, - 'check-circle-outline': { size: 16, svg: strokeWidth => `` }, - 'unarchive-outline': { size: 20, svg: strokeWidth => `` }, - 'pin-outline': { size: 16, svg: strokeWidth => `` }, - 'pin-fill': { size: 16, svg: strokeWidth => `` }, + 'compare-split-outline': { size: 16, svg: strokeWidth => `` }, + 'plan-outline': { size: 14, svg: strokeWidth => `` }, + 'compact-outline': { size: 16, svg: strokeWidth => `` }, + 'shield-outline': { size: 16, svg: strokeWidth => `` }, + 'check-circle-outline': { size: 16, svg: strokeWidth => `` }, + 'unarchive-outline': { size: 20, svg: strokeWidth => `` }, + 'pin-outline': { size: 16, svg: strokeWidth => `` }, + 'pin-fill': { size: 16, svg: strokeWidth => `` }, 'flat-list-outline': { size: 16, svg: strokeWidth => `` }, 'workspace-tree-outline': { size: 16, svg: strokeWidth => `` }, 'chevrons-up-down-outline': { size: 16, svg: strokeWidth => `` }, @@ -123,7 +124,7 @@ export const ICON_ARTWORK = { ? `` : `` }, 'archive-check-outline': { size: 16, svg: strokeWidth => `` }, - 'sliders-two-outline': { size: 16, svg: strokeWidth => `` }, + 'sliders-two-outline': { size: 16, svg: strokeWidth => `` }, 'microphone-outline': { size: 16, svg: strokeWidth => strokeWidth === ICON_MEDIUM_STROKE ? `` : `` }, diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 1b4aa7eca7..ba85cf3631 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -264,10 +264,10 @@ export const IconWarningOutlineRegular = productIcon('warning-outline', 'regular /** Medium IconWarningOutline artwork with a 1.3px stroke. */ export const IconWarningOutlineMedium = productIcon('warning-outline', 'medium') -/** Regular IconCheckCircleFill artwork (circled check); its fill-only geometry is weight-independent. */ +/** Regular one-pixel IconCheckCircleFill artwork. */ export const IconCheckCircleFillRegular = productIcon('check-circle-fill', 'regular') -/** Medium IconCheckCircleFill artwork; it matches Regular because the geometry is fill-only. */ +/** Medium IconCheckCircleFill artwork with a fixed 1.3px stroke. */ export const IconCheckCircleFillMedium = productIcon('check-circle-fill', 'medium') /** Regular rounded warning triangle with an exclamation mark. */ @@ -462,6 +462,12 @@ export const IconListPenOutlineRegular = productIcon('list-pen-outline', 'regula /** Medium IconListPenOutline artwork with a 1.3px stroke. */ export const IconListPenOutlineMedium = productIcon('list-pen-outline', 'medium') +/** Regular one-pixel IconFilesDiffOutline artwork. */ +export const IconFilesDiffOutlineRegular = productIcon('files-diff-outline', 'regular') + +/** Medium IconFilesDiffOutline artwork with a 1.3px stroke. */ +export const IconFilesDiffOutlineMedium = productIcon('files-diff-outline', 'medium') + /** Regular one-pixel IconGoalOutline artwork. */ export const IconGoalOutlineRegular = productIcon('goal-outline', 'regular') @@ -492,10 +498,10 @@ export const IconQuestionOutlineRegular = productIcon('question-outline', 'regul /** Medium IconQuestionOutline artwork with a 1.3px stroke. */ export const IconQuestionOutlineMedium = productIcon('question-outline', 'medium') -/** Regular IconInfoOutline artwork; its fill-only geometry is weight-independent. */ +/** Regular one-pixel IconInfoOutline artwork. */ export const IconInfoOutlineRegular = productIcon('info-outline', 'regular') -/** Medium IconInfoOutline artwork; its fill-only geometry is weight-independent. */ +/** Medium IconInfoOutline artwork with a fixed 1.3px stroke. */ export const IconInfoOutlineMedium = productIcon('info-outline', 'medium') /** Regular one-pixel plugin pinwheel artwork. */ @@ -561,7 +567,7 @@ export const IconShieldOutlineMedium = productIcon('shield-outline', 'medium') /** Regular one-pixel IconCheckCircleOutline artwork. */ export const IconCheckCircleOutlineRegular = productIcon('check-circle-outline', 'regular') -/** Medium IconCheckCircleOutline artwork with a 1.3px stroke. */ +/** Medium IconCheckCircleOutline artwork with a fixed 1.3px stroke. */ export const IconCheckCircleOutlineMedium = productIcon('check-circle-outline', 'medium') /** Regular one-pixel IconUnarchiveOutline artwork. */ diff --git a/packages/client/ui-primitives/src/icons/props.ts b/packages/client/ui-primitives/src/icons/props.ts index 560adbeb1e..85a599f7be 100644 --- a/packages/client/ui-primitives/src/icons/props.ts +++ b/packages/client/ui-primitives/src/icons/props.ts @@ -1,6 +1,6 @@ /** Shared props for every product icon component. */ export interface IconProps { - /** Square edge in px; defaults to the glyph's own drawn size. */ + /** Rendered height in CSS px; stroked geometry retains its Regular or Medium width. */ size?: number | undefined /** Extra class for layout placement; color rides currentColor. * (`| undefined` for exactOptionalPropertyTypes: callers forward their own optional prop.) */ diff --git a/packages/client/ui-primitives/src/icons/shared-artwork.tsx b/packages/client/ui-primitives/src/icons/shared-artwork.tsx index 3bd29f7a6f..e3a0255f6f 100644 --- a/packages/client/ui-primitives/src/icons/shared-artwork.tsx +++ b/packages/client/ui-primitives/src/icons/shared-artwork.tsx @@ -12,9 +12,9 @@ interface WeightedArtworkProps extends IconProps { */ export const ChatLinesOutlineArtwork = ({ size = 16, className, strokeWidth }: WeightedArtworkProps) => ( ) @@ -25,10 +25,10 @@ export const ChatLinesOutlineArtwork = ({ size = 16, className, strokeWidth }: W */ export const GlobeOutlineArtwork = ({ size = 14, className, strokeWidth }: WeightedArtworkProps) => ( ) @@ -39,9 +39,9 @@ export const GlobeOutlineArtwork = ({ size = 14, className, strokeWidth }: Weigh */ export const CodeBracketsArtwork = ({ size = 14, className, strokeWidth }: WeightedArtworkProps) => ( ) @@ -52,8 +52,8 @@ export const CodeBracketsArtwork = ({ size = 14, className, strokeWidth }: Weigh */ export const BrowseOutlineArtwork = ({ size = 16, className, strokeWidth }: WeightedArtworkProps) => ( ) @@ -65,7 +65,7 @@ export const BrowseOutlineArtwork = ({ size = 16, className, strokeWidth }: Weig */ export const FolderCloseArtwork = ({ size = 16, className, strokeWidth }: WeightedArtworkProps) => ( ) diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 755c9a1120..c8b7bf521e 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -26,6 +26,8 @@ export type { SegmentedTab } from './SegmentedTabs.tsx' export { Tag } from './Tag.tsx' export type { TagTone } from './Tag.tsx' export { PathLabel } from './PathLabel.tsx' +export { MarqueeText, useHoverMarquee } from './Marquee.tsx' +export type { HoverMarquee, HoverMarqueeOptions, MarqueeTextProps } from './Marquee.tsx' export { Switch } from './Switch.tsx' export { SegmentedControl } from './SegmentedControl.tsx' export type { SegmentedControlOption } from './SegmentedControl.tsx' @@ -41,7 +43,6 @@ export { useAnchoredMaxHeight } from './useAnchoredMaxHeight.ts' export { useDismissOnOutsidePointer } from './useDismissOnOutsidePointer.ts' export { HoverCard } from './HoverCard.tsx' export { HoverCardGroup } from './HoverCardGroup.tsx' -export { titleMarqueeClass, useTitleMarquee } from './title-marquee.ts' export { usePointerGrace } from './pointer-grace.ts' export { ShortcutKeys } from './ShortcutKeys.tsx' export { observeComposition } from './keyboard-composition.ts' diff --git a/packages/client/ui-primitives/src/markdown/MarkdownText.module.css b/packages/client/ui-primitives/src/markdown/MarkdownText.module.css index a13f0a6a40..069d5645f3 100644 --- a/packages/client/ui-primitives/src/markdown/MarkdownText.module.css +++ b/packages/client/ui-primitives/src/markdown/MarkdownText.module.css @@ -93,17 +93,18 @@ box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); } -/* Leading link-category glyph inside anchors, file mentions, and - URL-promoted inline code: outline glyphs ride the link's currentColor. - 1.1em keeps the glyph proportional to the surrounding text's size (it - shrinks with the code chip's 0.875em); the small negative offset seats - its optical center on the cap height. */ +/* Inline icon boxes follow the text middle, preserving their internal whitespace. + Separate the link from preceding prose more than the icon from its label. */ .linkIcon { flex: none; width: 1.1em; height: 1.1em; - vertical-align: -0.25em; - margin-right: 5px; + vertical-align: calc(0.5cap - 0.55em); + margin-inline: 0.25em 0.125em; +} + +.markdown code .linkIcon { + margin-inline-start: 0; } .markdown :where(ul, ol) { diff --git a/packages/client/ui-primitives/src/title-marquee.ts b/packages/client/ui-primitives/src/title-marquee.ts deleted file mode 100644 index db2acf2ead..0000000000 --- a/packages/client/ui-primitives/src/title-marquee.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Marquee of a one-line title that clips its own text: while its row is hovered, a title wider than its cell crawls to - * its far edge, and its clipping edges fade through the `data-scrolled` and `data-clipped` hooks that - * {@link titleMarqueeClass} styles. - */ - -import { useEffect, useMemo, useRef } from 'react' -import type { PointerEvent, RefObject } from 'react' -import css from './TitleMarquee.module.css' - -/** Class that fades a marquee title's clipping edges while it travels; add it to the title element. */ -/* v8 ignore next -- the stylesheet defines .marquee; were it missing, the title would carry no class and lose only its edge fades. */ -export const titleMarqueeClass: string = css.marquee ?? '' - -/* Overflow this small hides no meaningful tail; scrolling for it reads as an - accidental jitter, so the title stays put. */ -const MIN_TITLE_REVEAL_PX = 8 - -/* Marquee travel speed: slow enough to read the text as it passes. */ -const TITLE_MARQUEE_PX_PER_MS = 0.03 - -/** - * Place the title's scroll position and publish the stylesheet's fade-mask - * hooks: `data-scrolled` while the title has left its start (left fade) and - * `data-clipped` while text remains beyond the right edge (right fade). - * @param title - the clipping title element. - * @param left - scroll offset in CSS pixels. - * @param range - the title's maximum scroll offset in CSS pixels. - */ -function placeTitle(title: HTMLSpanElement, left: number, range: number): void { - // jsdom implements no scrollTo; the lane's direct assignment is instant there - // anyway, so both paths land on the same position. - if (typeof title.scrollTo === 'function') title.scrollTo({ left, behavior: 'instant' }) - else title.scrollLeft = left - if (left > 0) title.dataset.scrolled = '' - else delete title.dataset.scrolled - if (left < range) title.dataset.clipped = '' - else delete title.dataset.clipped -} - -/** - * Return the title to its resting state: scrolled to the start with both fade - * masks off, so the resting ellipsis renders at full strength. - * @param title - the clipping title element. - */ -function restTitle(title: HTMLSpanElement): void { - if (typeof title.scrollTo === 'function') title.scrollTo({ left: 0, behavior: 'instant' }) - else title.scrollLeft = 0 - delete title.dataset.scrolled - delete title.dataset.clipped -} - -/** - * Marquee a title wider than its one-line cell while its row is hovered: the - * title clips its own text, so entering crawls it at a constant speed until the - * far edge (a fork's incremented title, for example) is in view, then rests - * there under the pointer. Overflow of at most {@link MIN_TITLE_REVEAL_PX} - * stays put — a barely-clipped title moving a few pixels reads as jitter, not a - * reveal. Leaving returns the title to the start in one step, because the - * resting ellipsis and the narrowed cell would otherwise meet the text while it - * travelled back. Reduced motion jumps to the far edge instead of crawling. - * @param title - ref to the clipping title element. - * @returns stable pointer enter/leave handlers for the row. - */ -export function useTitleMarquee(title: RefObject): { - enter: (event?: PointerEvent) => void - leave: () => void -} { - const frame = useRef(0) - const revealing = useRef(false) - useEffect(() => () => { cancelAnimationFrame(frame.current) }, []) - return useMemo(() => ({ - enter: (event?: PointerEvent): void => { - if (event?.pointerType === 'touch') return - /* v8 ignore next -- defensive: the title span renders unconditionally. */ - if (title.current === null) return - if (revealing.current) return - revealing.current = true - const element = title.current - const range = element.scrollWidth - element.clientWidth - if (range <= MIN_TITLE_REVEAL_PX) return - if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { - placeTitle(element, range, range) - return - } - cancelAnimationFrame(frame.current) - let previous: number | undefined - let position = 0 - const step = (now: DOMHighResTimeStamp): void => { - position += previous === undefined ? 0 : (now - previous) * TITLE_MARQUEE_PX_PER_MS - previous = now - placeTitle(element, Math.min(position, range), range) - if (position < range) frame.current = requestAnimationFrame(step) - } - frame.current = requestAnimationFrame(step) - }, - leave: (): void => { - revealing.current = false - cancelAnimationFrame(frame.current) - /* v8 ignore next -- defensive: the title span renders unconditionally. */ - if (title.current === null) return - restTitle(title.current) - }, - }), [title]) -} diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.settled.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.settled.txt index ee3cf3638e..7e5273146b 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.settled.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.settled.txt @@ -11,10 +11,10 @@ diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.streaming.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.streaming.txt index ee3cf3638e..7e5273146b 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.streaming.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/cjk-strong-and-inline-code-url.streaming.txt @@ -11,10 +11,10 @@ diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/footnotes.settled.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/footnotes.settled.txt index eafe1678ab..e00b22574d 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/footnotes.settled.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/footnotes.settled.txt @@ -19,10 +19,10 @@ #text "Footnote a body with "

    #text "relative dropped and js dropped and "

    #text "中文 "

    #text "[spaces encoded]("

    diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/links-and-autolinks.streaming.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/links-and-autolinks.streaming.txt index 0f674a580a..0e71fc99e7 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/links-and-autolinks.streaming.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/links-and-autolinks.streaming.txt @@ -2,65 +2,65 @@

    #text "relative dropped and js dropped and "

    #text "中文 "

    #text "[spaces encoded]("

    diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.settled.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.settled.txt index 741f29e03d..636af55cab 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.settled.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.settled.txt @@ -3,26 +3,26 @@ #text "A "

    diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.streaming.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.streaming.txt index 741f29e03d..636af55cab 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.streaming.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/reference-links-and-images.streaming.txt @@ -3,26 +3,26 @@ #text "A "

    diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.settled.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.settled.txt index 67d874bb19..5b419eb641 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.settled.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.settled.txt @@ -26,10 +26,10 @@ diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.streaming.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.streaming.txt index 67d874bb19..5b419eb641 100644 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.streaming.txt +++ b/packages/client/ui-primitives/tests/fixtures/markdown-dom/table-with-alignment.streaming.txt @@ -26,10 +26,10 @@ diff --git a/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts b/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts new file mode 100644 index 0000000000..8897727435 --- /dev/null +++ b/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts @@ -0,0 +1,50 @@ +/** + * The compact HoverCard's placement as CSS text: the component suite sees CSS + * Modules as class-name maps and jsdom lays out nothing, so only the stylesheet + * proves which positions the browser tries, and in which order. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/HoverCard.module.css', import.meta.url)), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ' ') + +function declarations(selector: string): Map { + const found = new Map() + for (const [, selectorList = '', body = ''] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + if (!selectorList.split(',').map(value => value.trim()).includes(selector)) continue + for (const part of body.split(';')) { + const colon = part.indexOf(':') + if (colon !== -1) found.set(part.slice(0, colon).trim(), part.slice(colon + 1).trim().replace(/\s+/g, ' ')) + } + } + return found +} + +describe('HoverCard.module.css', () => { + it('places a compact card beside its anchor\'s end edge, top on the anchor\'s top, 8px from the anchor and the viewport', () => { + expect(declarations('.card').get('position')).toBe('fixed') + const compact = declarations('.compact') + expect([compact.get('position-area'), compact.get('inset')]).toEqual(['inline-end span-block-end', '0 8px 8px']) + }) + + it('tries the start side, then a bottom-held card on either side, then below the anchor and above it, then the viewport\'s corner', () => { + expect(declarations('.compact').get('position-try-fallbacks')).toBe( + 'flip-inline, --dsh-hover-card-low, --dsh-hover-card-low flip-inline, --dsh-hover-card-below, --dsh-hover-card-above, --dsh-hover-card-held', + ) + const low = declarations('@position-try --dsh-hover-card-low') + expect([low.get('position-area'), low.get('align-self')]).toEqual(['inline-end span-all', 'end']) + }) + + it('keeps a card that fits on neither side off its anchor: 8px below or above it, from the anchor\'s start edge', () => { + const below = declarations('@position-try --dsh-hover-card-below') + expect([below.get('position-area'), below.get('inset')]).toEqual(['block-end span-inline-end', '8px 8px 8px 0']) + const above = declarations('@position-try --dsh-hover-card-above') + expect([above.get('position-area'), above.get('inset')]).toEqual(['block-start span-inline-end', '8px 8px 8px 0']) + }) + + it('holds a card too tall to go below or above its anchor at the viewport\'s bottom and end margins, as the last fallback', () => { + const held = declarations('@position-try --dsh-hover-card-held') + expect([held.get('position-area'), held.get('justify-self'), held.get('align-self')]).toEqual(['span-all', 'end', 'end']) + }) +}) diff --git a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx index 56e4ef5044..a5ad226fab 100644 --- a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx +++ b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx @@ -137,8 +137,9 @@ describe('HoverCard', () => { expect(screen.getByText('card body')).toBeTruthy() }) - it('opens after the dwell delay, positioned right of the anchor', () => { + it('opens after the dwell delay, anchored to its wrapper by name for the stylesheet to place', () => { const { wrapper } = mount() + expect(wrapper.style.anchorName).toBe('') fireEvent.pointerEnter(wrapper) expect(screen.queryByText('card body')).toBeNull() act(() => { vi.advanceTimersByTime(499) }) @@ -146,8 +147,29 @@ describe('HoverCard', () => { act(() => { vi.advanceTimersByTime(1) }) const card = screen.getByText('card body').parentElement as HTMLElement expect(card.parentElement?.parentElement).toBe(document.body) - expect(card.style.left).toBe('208px') - expect(card.style.top).toBe('40px') + // The stylesheet places a compact card against the named anchor, so the script gives it no coordinates. + expect(wrapper.style.anchorName).toMatch(/^--dsh-hover-card-/) + expect(card.style.positionAnchor).toBe(wrapper.style.anchorName) + expect([card.style.left, card.style.top]).toEqual(['', '']) + // The name lasts as long as the card. + fireEvent.pointerLeave(wrapper) + act(() => { vi.advanceTimersByTime(POINTER_GRACE_MS) }) + expect(wrapper.style.anchorName).toBe('') + }) + + it('gives each compact card its own anchor name', () => { + render( + <> + first} content={

    } /> + second} content={
    second body
    } /> + , + ) + const wrappers = ['first', 'second'].map(text => screen.getByText(text).parentElement as HTMLElement) + for (const wrapper of wrappers) fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + const names = wrappers.map(wrapper => wrapper.style.anchorName) + expect(new Set(names).size).toBe(2) + expect(['first body', 'second body'].map(text => (screen.getByText(text).parentElement as HTMLElement).style.positionAnchor)).toEqual(names) }) it('insets a preview by 24px on each side and follows anchor resizing', () => { @@ -600,46 +622,18 @@ describe('HoverCard', () => { expect(screen.queryByText('card body')).toBeNull() }) - it('corrects the bottom-edge clamp once the mounted card height is measurable', () => { - // First placement reads height 0 (card not yet mounted) and keeps the - // anchor top; the post-mount correction re-clamps with the real height. - window.innerHeight = 300 - const offsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')! - Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, get: () => 120 }) - try { - const { wrapper } = mount() - stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) - fireEvent.pointerEnter(wrapper) - act(() => { vi.advanceTimersByTime(500) }) - const card = screen.getByText('card body').parentElement as HTMLElement - // 300 - 120 - 8 = 172, instead of the anchor top 280. - expect(card.style.top).toBe('172px') - } finally { - Object.defineProperty(HTMLElement.prototype, 'offsetHeight', offsetHeight) - } - }) - - it('clamps inside placement itself when the card is already measured (resize path)', () => { - window.innerHeight = 300 + it('measures nothing for a compact card: not at open, on scroll, or on resize', () => { const { wrapper } = mount() - stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) + const rect = vi.spyOn(wrapper, 'getBoundingClientRect') + const listen = vi.spyOn(window, 'addEventListener') fireEvent.pointerEnter(wrapper) act(() => { vi.advanceTimersByTime(500) }) const card = screen.getByText('card body').parentElement as HTMLElement - Object.defineProperty(card, 'offsetHeight', { value: 120 }) - act(() => { fireEvent.resize(window) }) - expect(card.style.top).toBe('172px') - }) - - it('repositions on capture-phase scroll while open and stops listening after close', () => { - const { wrapper } = mount() - fireEvent.pointerEnter(wrapper) - act(() => { vi.advanceTimersByTime(500) }) - stubAnchorRect(screen.getByText('row'), { top: 90, right: 300 }) act(() => { fireEvent.scroll(document) }) - const card = screen.getByText('card body').parentElement as HTMLElement - expect(card.style.left).toBe('308px') - expect(card.style.top).toBe('90px') + act(() => { fireEvent.resize(window) }) + expect(rect).not.toHaveBeenCalled() + expect(listen.mock.calls.map(([type]) => type).filter(type => type === 'scroll' || type === 'resize')).toEqual([]) + expect([card.style.left, card.style.top]).toEqual(['', '']) fireEvent.pointerLeave(wrapper) act(() => { vi.advanceTimersByTime(POINTER_GRACE_MS) }) expect(screen.queryByText('card body')).toBeNull() diff --git a/packages/client/ui-primitives/tests/icons.client.spec.tsx b/packages/client/ui-primitives/tests/icons.client.spec.tsx index 9c550e0949..b5522a4fd8 100644 --- a/packages/client/ui-primitives/tests/icons.client.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.client.spec.tsx @@ -94,10 +94,11 @@ describe('product icon set', () => { expect(svg.getAttribute('viewBox')).toBe('0 0 16 16') expect(svg.getAttribute('fill')).toBe('none') expect(svg.getAttribute('stroke-width')).toBe(String(stroke)) - expect(svg.querySelector('[transform], [vector-effect], [stroke-width]')).toBeNull() + expect(svg.querySelector('[transform], [stroke-width]')).toBeNull() expect(svg.hasAttribute('transform')).toBe(false) expect(svg.hasAttribute('vector-effect')).toBe(false) expect(paths.every(path => path.getAttribute('stroke') === 'currentColor')).toBe(true) + expect(paths.every(path => path.getAttribute('vector-effect') === 'non-scaling-stroke')).toBe(true) expect(primitives.ICON_SYMBOLS[`dsw-icon-users-outline-${weight}`]) .toBe(ICON_ARTWORK['users-outline'].svg(stroke)) const view = render() @@ -126,10 +127,11 @@ describe('product icon set', () => { expect(svg.getAttribute('stroke-width')).toBe(String(stroke)) expect(svg.getAttribute('stroke-linecap')).toBe('round') expect(svg.getAttribute('stroke-linejoin')).toBe('round') - expect(svg.querySelector('[transform], [vector-effect], [stroke-width], [stroke-linecap], [stroke-linejoin]')).toBeNull() + expect(svg.querySelector('[transform], [stroke-width], [stroke-linecap], [stroke-linejoin]')).toBeNull() expect(svg.hasAttribute('transform')).toBe(false) expect(svg.hasAttribute('vector-effect')).toBe(false) expect(paths.every(path => path.getAttribute('stroke') === 'currentColor')).toBe(true) + expect(paths.every(path => path.getAttribute('vector-effect') === 'non-scaling-stroke')).toBe(true) expect(primitives.ICON_SYMBOLS[`dsw-icon-layers-outline-${weight}`]) .toBe(ICON_ARTWORK['layers-outline'].svg(stroke)) const view = render() diff --git a/packages/client/ui-primitives/tests/marquee-styles.client.spec.ts b/packages/client/ui-primitives/tests/marquee-styles.client.spec.ts new file mode 100644 index 0000000000..b1e3fbed23 --- /dev/null +++ b/packages/client/ui-primitives/tests/marquee-styles.client.spec.ts @@ -0,0 +1,57 @@ +/** + * MarqueeText's clipping, travel, and fade masks as CSS text: the component + * suite sees CSS Modules as class-name maps, so only the stylesheet proves that + * a marqueeing text drops its ellipsis, travels by the measured distance and + * time, and fades the edges that still hide text. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const source = readFileSync(fileURLToPath(new URL('../src/Marquee.module.css', import.meta.url)), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ' ') +const reduced = /@media \(prefers-reduced-motion: reduce\) \{([\s\S]*)\}\s*$/.exec(source)?.[1] ?? '' +const base = source.replace(/@media \(prefers-reduced-motion: reduce\) \{[\s\S]*\}\s*$/, '') + +function declarations(css: string, selector: string): Map { + const found = new Map() + for (const [, selectorList = '', body = ''] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + if (!selectorList.split(',').map(value => value.trim()).includes(selector)) continue + for (const part of body.split(';')) { + const colon = part.indexOf(':') + if (colon !== -1) found.set(part.slice(0, colon).trim(), part.slice(colon + 1).trim().replace(/\s+/g, ' ')) + } + } + return found +} + +const START_FADE = 'linear-gradient(to right, transparent, #000 12px)' + +describe('Marquee.module.css', () => { + it('clips one line with an ellipsis at rest, with the travelling span inline so the ellipsis cuts between characters', () => { + const rest = declarations(base, '.text') + expect([rest.get('overflow'), rest.get('text-overflow'), rest.get('white-space')]).toEqual(['hidden', 'ellipsis', 'nowrap']) + expect(declarations(base, '.travel').size).toBe(0) + }) + + it('drops the ellipsis and fades both edges while the text travels, then only the start edge once the travel time has passed', () => { + const travelling = declarations(base, '.text[data-marquee]') + expect(travelling.get('text-overflow')).toBe('clip') + expect(travelling.get('mask-image')).toBe('linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent)') + expect(travelling.get('animation')).toBe('dsh-marquee-arrive 0s var(--dsh-marquee-duration) forwards') + expect(base.replace(/\s+/g, ' ')).toContain(`@keyframes dsh-marquee-arrive { to { mask-image: ${START_FADE}; } }`) + }) + + it('carries the span over the measured distance in the measured time at a constant speed and holds the far edge', () => { + const travel = declarations(base, '.text[data-marquee] > .travel') + expect(travel.get('display')).toBe('inline-block') + expect(travel.get('animation')).toBe('dsh-marquee-travel var(--dsh-marquee-duration) linear forwards') + expect(base.replace(/\s+/g, ' ')).toContain('@keyframes dsh-marquee-travel { to { transform: translateX(calc(-1 * var(--dsh-marquee-range))); } }') + }) + + it('shows the far edge at once under reduced motion, with the start fade alone', () => { + const text = declarations(reduced, '.text[data-marquee]') + expect([text.get('mask-image'), text.get('animation')]).toEqual([START_FADE, 'none']) + const travel = declarations(reduced, '.text[data-marquee] > .travel') + expect([travel.get('animation'), travel.get('transform')]).toEqual(['none', 'translateX(calc(-1 * var(--dsh-marquee-range)))']) + }) +}) diff --git a/packages/client/ui-primitives/tests/marquee.client.spec.tsx b/packages/client/ui-primitives/tests/marquee.client.spec.tsx new file mode 100644 index 0000000000..1e80d2e974 --- /dev/null +++ b/packages/client/ui-primitives/tests/marquee.client.spec.tsx @@ -0,0 +1,97 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { useRef } from 'react' +import { MarqueeText, useHoverMarquee } from '../src/Marquee.tsx' + +afterEach(cleanup) + +function Row({ text, hold }: { readonly text: string; readonly hold?: boolean }) { + const ref = useRef(null) + const marquee = useHoverMarquee(ref, { hold }) + return ( +
    + {text} +
    + ) +} + +/** The clipping element and the span inside it that travels. */ +function parts(): { text: HTMLElement; travel: HTMLElement } { + const text = document.querySelector('[data-cell]') as HTMLElement + return { text, travel: text.firstElementChild as HTMLElement } +} + +/** State the clipped text's geometry outright: jsdom lays out nothing. */ +function geometry(element: HTMLElement, scrollWidth: number, clientWidth: number): void { + Object.defineProperty(element, 'scrollWidth', { value: scrollWidth, configurable: true }) + Object.defineProperty(element, 'clientWidth', { value: clientWidth, configurable: true }) +} + +/** What the stylesheet reads: whether the text marquees, the travel distance, and its duration. */ +function marquee(text: HTMLElement): (string | undefined)[] { + return [text.dataset.marquee, text.style.getPropertyValue('--dsh-marquee-range'), text.style.getPropertyValue('--dsh-marquee-duration')] +} + +describe('useHoverMarquee', () => { + it('hands the stylesheet the overflow and its time at 30px/s while hovered, and rests at once on leave', () => { + render() + const row = screen.getByRole('row') + const { text, travel } = parts() + expect(text.className).toContain('cell') + expect(travel.textContent).toBe('A cell long enough to clip') + geometry(text, 320, 180) + fireEvent.pointerEnter(row, { pointerType: 'touch' }) + expect(marquee(text)).toEqual([undefined, '', '']) + fireEvent.pointerEnter(row) + expect(marquee(text)).toEqual(['', '140px', '4667ms']) + // A repeated entry while it marquees measures nothing again, so the travel does not restart. + geometry(text, 400, 180) + fireEvent.pointerEnter(row) + expect(marquee(text)).toEqual(['', '140px', '4667ms']) + fireEvent.pointerLeave(row) + expect(marquee(text)).toEqual([undefined, '', '']) + }) + + it('leaves text that fits or overflows by at most 8px at rest', () => { + render() + const row = screen.getByRole('row') + const { text } = parts() + for (const [scrollWidth, expected] of [[180, false], [188, false], [189, true]] as const) { + geometry(text, scrollWidth, 180) + fireEvent.pointerEnter(row) + expect(text.hasAttribute('data-marquee')).toBe(expected) + fireEvent.pointerLeave(row) + } + }) + + it('marquees while held, with or without the pointer, and rests when neither remains', () => { + const view = render() + const row = screen.getByRole('row') + const { text } = parts() + geometry(text, 300, 200) + view.rerender() + expect(marquee(text)).toEqual(['', '100px', '3333ms']) + fireEvent.pointerEnter(row) + fireEvent.pointerLeave(row) + expect(text.hasAttribute('data-marquee')).toBe(true) + view.rerender() + expect(text.hasAttribute('data-marquee')).toBe(false) + // The pointer keeps a marquee whose hold ends. + fireEvent.pointerEnter(row) + view.rerender() + view.rerender() + expect(text.hasAttribute('data-marquee')).toBe(true) + }) + + it('ignores hover before its text element mounts', () => { + function Detached() { + const ref = useRef(null) + return
    + } + render() + fireEvent.pointerEnter(screen.getByRole('row')) + fireEvent.pointerLeave(screen.getByRole('row')) + expect(screen.getByRole('row').childElementCount).toBe(0) + }) +}) diff --git a/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx b/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx index 798640da95..248725c85b 100644 --- a/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx +++ b/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx @@ -97,6 +97,35 @@ describe('Menu submenus', () => { expect(close).toHaveBeenCalledOnce() }) + it('closes when another popup trigger is activated, even one that stops its pointer presses', () => { + const close = vi.fn() + render(<> + + + Own} items={entries} onClose={close} /> + ) + fireEvent.click(screen.getByRole('button', { name: 'Own' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Applications' })) + fireEvent.click(screen.getByRole('button', { name: 'Plain' })) + expect(close).not.toHaveBeenCalled() + const isolated = screen.getByRole('button', { name: 'Isolated more' }) + fireEvent.pointerDown(isolated) + expect(close).not.toHaveBeenCalled() + fireEvent.click(isolated) + expect(close).toHaveBeenCalledOnce() + }) + + it('leaves other popup triggers the external-trigger rule claims to their own popup', () => { + const close = vi.fn() + render(<> + + node instanceof Element && node.hasAttribute('data-context-menu-trigger')} /> + ) + fireEvent.click(screen.getByRole('button', { name: 'Claimed' })) + expect(close).not.toHaveBeenCalled() + }) + it('does not activate an external popup trigger on ArrowRight', () => { render() const trigger = screen.getByRole('button', { name: 'External more' }) diff --git a/packages/client/ui-primitives/tests/title-marquee-styles.client.spec.ts b/packages/client/ui-primitives/tests/title-marquee-styles.client.spec.ts deleted file mode 100644 index 246c75d746..0000000000 --- a/packages/client/ui-primitives/tests/title-marquee-styles.client.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * The title marquee's fade masks as CSS text. CSS Modules resolve to class-name maps in the component suites, so only - * the stylesheet can show that each clipping edge fades while the title travels. - */ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' - -const css = readFileSync(fileURLToPath(new URL('../src/TitleMarquee.module.css', import.meta.url)), 'utf8') - .replace(/\/\*[\s\S]*?\*\//g, ' ') - -/** The mask image of the rule for one exact selector, with whitespace collapsed. */ -function mask(selector: string): string | undefined { - for (const [, selectors = '', body = ''] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { - if (selectors.trim() !== selector) continue - return /mask-image:\s*([^;]+);/.exec(body)?.[1]?.replace(/\s+/g, ' ').trim() - } - return undefined -} - -describe('TitleMarquee.module.css', () => { - it('fades the left edge once the title left its start, the right while text remains beyond it, and both mid-travel', () => { - expect(mask('.marquee[data-scrolled]')).toBe('linear-gradient(to right, transparent, #000 12px)') - expect(mask('.marquee[data-clipped]')).toBe('linear-gradient(to left, transparent, #000 12px)') - expect(mask('.marquee[data-scrolled][data-clipped]')) - .toBe('linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent)') - }) -}) diff --git a/packages/client/ui-primitives/tests/title-marquee.client.spec.tsx b/packages/client/ui-primitives/tests/title-marquee.client.spec.tsx deleted file mode 100644 index 56cf5028ff..0000000000 --- a/packages/client/ui-primitives/tests/title-marquee.client.spec.tsx +++ /dev/null @@ -1,157 +0,0 @@ -// @vitest-environment jsdom -/** - * The title marquee: while its row is hovered, a clipped title crawls to its far edge at a constant speed, or jumps - * there under reduced motion; touch and overflow too small to read stay put; leaving returns it to its start in one - * step. - */ -import { useRef, type ReactNode } from 'react' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { titleMarqueeClass, useTitleMarquee } from '../src/title-marquee.ts' -import css from '../src/TitleMarquee.module.css' - -const TITLE = 'A title long enough to be clipped' - -/** A one-line row whose title marquees while it is hovered. */ -function Row(): ReactNode { - const title = useRef(null) - const marquee = useTitleMarquee(title) - return ( - - ) -} - -/** Render the row with its title clipped to `clientWidth` of `scrollWidth` pixels. */ -function renderRow(scrollWidth: number, clientWidth: number) { - const view = render() - const row = screen.getByRole('button') - const title = screen.getByText(TITLE) - // jsdom lays out nothing: the title's clipped geometry is stated outright. - Object.defineProperty(title, 'scrollWidth', { value: scrollWidth, configurable: true }) - Object.defineProperty(title, 'clientWidth', { value: clientWidth, configurable: true }) - return { view, row, title } -} - -/** The fade-mask hooks the title publishes. */ -function fades(title: HTMLElement): { readonly scrolled: boolean; readonly clipped: boolean } { - return { scrolled: title.hasAttribute('data-scrolled'), clipped: title.hasAttribute('data-clipped') } -} - -let reducedMotion = false - -beforeEach(() => { - reducedMotion = false - vi.useFakeTimers() - // jsdom implements no matchMedia; the stub answers the reduced-motion probe. - vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: reducedMotion && query === '(prefers-reduced-motion: reduce)' }))) -}) - -afterEach(() => { - cleanup() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -describe('useTitleMarquee', () => { - it('crawls a clipped title to its far edge at a constant speed while its row is hovered, and rests there', () => { - const { row, title } = renderRow(320, 180) - expect(titleMarqueeClass).toBe(css.marquee) - fireEvent.pointerEnter(row) - // The first frame only records the clock; travel begins on the second. - vi.advanceTimersByTime(16) - expect(title.scrollLeft).toBe(0) - expect(fades(title)).toEqual({ scrolled: false, clipped: true }) - // 30px a second: 1600ms of frames crawl 48px, off the start and short of the far edge. - vi.advanceTimersByTime(1600) - expect(title.scrollLeft).toBeCloseTo(48, 5) - expect(fades(title)).toEqual({ scrolled: true, clipped: true }) - vi.advanceTimersByTime(10_000) - expect(title.scrollLeft).toBe(140) - expect(fades(title)).toEqual({ scrolled: true, clipped: false }) - }) - - it('keeps crawling when the pointer enters the row again mid-crawl', () => { - const { row, title } = renderRow(320, 180) - fireEvent.pointerEnter(row) - vi.advanceTimersByTime(1616) - fireEvent.pointerEnter(row) - vi.advanceTimersByTime(1600) - expect(title.scrollLeft).toBeCloseTo(96, 5) - }) - - it('leaves a title that fits or overflows by at most 8px at its start, and crawls one a pixel wider', () => { - const fits = renderRow(180, 180) - fireEvent.pointerEnter(fits.row) - vi.advanceTimersByTime(1000) - expect(fits.title.scrollLeft).toBe(0) - expect(fades(fits.title)).toEqual({ scrolled: false, clipped: false }) - cleanup() - - const jitter = renderRow(188, 180) - fireEvent.pointerEnter(jitter.row) - vi.advanceTimersByTime(1000) - expect(jitter.title.scrollLeft).toBe(0) - cleanup() - - const reveal = renderRow(189, 180) - fireEvent.pointerEnter(reveal.row) - vi.advanceTimersByTime(1000) - expect(reveal.title.scrollLeft).toBe(9) - }) - - it('ignores a touch, which hovers nothing', () => { - const { row, title } = renderRow(320, 180) - // jsdom lacks PointerEvent; a plain event keeps the pointer type React reads. - const touch = new Event('pointerover', { bubbles: true }) - Object.defineProperty(touch, 'pointerType', { value: 'touch' }) - fireEvent(row, touch) - vi.advanceTimersByTime(1000) - expect(title.scrollLeft).toBe(0) - expect(fades(title)).toEqual({ scrolled: false, clipped: false }) - }) - - it('jumps a clipped title to its far edge under reduced motion', () => { - reducedMotion = true - const { row, title } = renderRow(320, 180) - fireEvent.pointerEnter(row) - expect(title.scrollLeft).toBe(140) - expect(fades(title)).toEqual({ scrolled: true, clipped: false }) - fireEvent.pointerLeave(row) - expect(title.scrollLeft).toBe(0) - expect(fades(title)).toEqual({ scrolled: false, clipped: false }) - }) - - it('returns the title to its start in one instant step on leave and cancels the crawl', () => { - const { row, title } = renderRow(320, 180) - const scrollTo = vi.fn<(options: ScrollToOptions) => void>() - Object.defineProperty(title, 'scrollTo', { value: scrollTo, configurable: true }) - fireEvent.pointerEnter(row) - vi.advanceTimersByTime(1616) - expect(scrollTo.mock.lastCall?.[0].left).toBeCloseTo(48, 5) - expect(scrollTo.mock.lastCall?.[0].behavior).toBe('instant') - fireEvent.pointerLeave(row) - expect(scrollTo).toHaveBeenLastCalledWith({ left: 0, behavior: 'instant' }) - expect(fades(title)).toEqual({ scrolled: false, clipped: false }) - const calls = scrollTo.mock.calls.length - vi.advanceTimersByTime(1000) - expect(scrollTo).toHaveBeenCalledTimes(calls) - - // Once left, the next hover crawls from the start again. - fireEvent.pointerEnter(row) - vi.advanceTimersByTime(16) - expect(scrollTo).toHaveBeenLastCalledWith({ left: 0, behavior: 'instant' }) - expect(fades(title)).toEqual({ scrolled: false, clipped: true }) - }) - - it('stops the crawl when the row unmounts', () => { - const { view, row, title } = renderRow(320, 180) - fireEvent.pointerEnter(row) - vi.advanceTimersByTime(1616) - const reached = title.scrollLeft - view.unmount() - vi.advanceTimersByTime(1000) - expect(title.scrollLeft).toBe(reached) - }) -}) diff --git a/packages/client/ui-reference/README.i18n.yaml b/packages/client/ui-reference/README.i18n.yaml index 2386cfb242..8d66300915 100644 --- a/packages/client/ui-reference/README.i18n.yaml +++ b/packages/client/ui-reference/README.i18n.yaml @@ -18,8 +18,11 @@ en: 779a9a534eaad38b zh: 3dd159a2c35702d6 /deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts: - en: 0b41c33743e5b422 - zh: 551896094c03f57e + en: 43b5324fb871a3d1 + zh: 3d101edc38b60d39 +/deepseek-ai-dsh-client-ui-reference/use-this-package/sent-file-and-folder-mentions: + en: 87c27115eae5a660 + zh: a9a20431928072ec /deepseek-ai-dsh-client-ui-reference/use-this-package/failure-behavior: en: 386bbd9dc0a2c322 zh: 3014a367157532b7 @@ -30,8 +33,8 @@ en: 6c77da1e946f72e1 zh: b7b8e1e1d4f5a102 /deepseek-ai-dsh-client-ui-reference/understand-the-implementation/serialization: - en: c3fe8963ed80e403 - zh: ba3e057cd63e9189 + en: 1126dd5a1189cde8 + zh: 87866765edd7e343 /deepseek-ai-dsh-client-ui-reference/further-exploration: en: 157b1bcf84b5c11b zh: 6b7e4f3326b19036 @@ -42,8 +45,8 @@ en: ff23f8026f7c6050 zh: 6b0841800076bcd2 /deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work: - en: e79991a25b11e342 - zh: 15064e8374c8e63d + en: f51b285964650dd2 + zh: 5a237964dff7f98a /deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-reference/README.md b/packages/client/ui-reference/README.md index 1647f5b162..5b1e3c9eca 100644 --- a/packages/client/ui-reference/README.md +++ b/packages/client/ui-reference/README.md @@ -33,6 +33,12 @@ A file closes completion as an atomic inline reference displayed with a file gly A session pick inserts an atomic inline reference whose hidden `ref` and clipboard representation is the canonical `@[label](dsh-session:…)` mention returned by the Host; its visible form is a chat-bubble glyph plus the session title. Sending carries the mention through `session.prompt`, and the session-reference service validates it and captures model context at `agent/pre-step`. +The shared file context menu ends with **Add to chat**. It inserts the clicked file as the same kind of reference into that Session’s draft, preserves existing text and selection, and returns focus without sending. The reference captures the resolved absolute path; line numbers are not included. The action is disabled when the Session cannot be edited at the moment the menu opens or the path cannot use the mention grammar; a draft that becomes uneditable while the menu stays open makes the action report failure instead of inserting. An open menu updates its label and failure feedback when the interface language changes. + +### Sent file and folder mentions + +In sent messages, queued rows, and local echoes, an `@path` or `@"path"` token renders as a file or folder reference only after the Session's filesystem confirms the path exists. Until then, and for a path that does not exist, such as a hand-typed `@notes`, the original text stays verbatim; email addresses never match. A candidate picked and sent in the same Session during one page load counts as confirmed, so its echo shows the reference immediately. + ### Failure behavior One unavailable or failed candidate domain yields no rows for that domain while the other still lists. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn. @@ -61,7 +67,7 @@ Candidate requests require an existing retained Client Session and share one tem File picks preserve the natural text defined by the shared `@path` grammar as the hidden serialized and clipboard form. Session picks use the canonical `@[label](dsh-session:…)` mention; serialization never reconstructs identity from the visible title. -The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Interactive file nodes receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels. +The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete candidate reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Both node renderers subscribe to a Session-bound `pathPresence` keyed Hook backed by `workspaceFiles/stat`: a stat result or a `workspace-file/not-regular-file` failure (a directory, a symbolic link whatever it points to, or another non-regular entry) confirms the path, `workspace-file/not-found` rejects it, and any other failure leaves it unconfirmed for the next subscriber to retry. The plugin owns these answers, keeps one per Session and path, and aborts outstanding stats on disposal; a settling pick records its path as confirmed. Presence does not read the [`file` resource](../../api/workspace-files/README.md) through `useResource`: that provider keeps one Host change subscription open per Session and path while a reader is mounted, and a mention needs a single answer. Interactive file nodes also receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels.
    @@ -97,6 +103,7 @@ These limits define when the reference source cannot help; they are current pack - **Candidate failure is intentionally quiet** — one unavailable or failed Remote discovery call yields no rows for that domain. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn. - **No browser-side file scan** — Web completion requires a mounted Host `ctx.fileReferences` provider; the browser cannot fall back to its own filesystem. +- **Sent references do not follow file changes** — a path's confirmed or missing answer lasts for the page load; creating or removing the path later changes how its mentions render only after reload. - **Session search remains metadata-only** — discovery filters session id, cwd, and the latest log-backed title through `ctx.sessionReferenceResolver`; message bodies and full transcripts are not searched. diff --git a/packages/client/ui-reference/README.zh.md b/packages/client/ui-reference/README.zh.md index 9b16dd48d7..2dbbc7b76d 100644 --- a/packages/client/ui-reference/README.zh.md +++ b/packages/client/ui-reference/README.zh.md @@ -33,6 +33,12 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。 +共享文件右键菜单最底部提供**添加到对话**。它将所选文件作为同类引用插入该 Session 的草稿,保留现有文字和选中内容,恢复输入焦点但不发送。引用记录解析后的绝对路径,不包含行号。打开菜单时 Session 不可编辑,或路径无法用 mention 语法表示时,此入口不可用;菜单打开期间草稿变为不可编辑时,点击会提示失败而不插入。切换界面语言时,已打开菜单的标题和失败提示随之更新。 + +### 已发送的文件与目录引用 + +在已发送消息、排队行和本地回显中,`@path` 或 `@"path"` token 只有在 Session 的文件系统确认该路径存在后才渲染为文件或目录引用。确认之前,以及路径不存在时(例如手写的 `@notes`),原文保持不变;邮箱地址永远不会匹配。在同一 Session、同一次页面加载内从候选中选择并发送的路径视为已确认,因此其回显会立即显示引用。 + ### 失败行为 某个候选领域不可用或失败时,该领域不产生任何行,另一领域仍正常列出。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。 @@ -61,7 +67,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 文件选择把共享 `@path` 语法所定义的自然文本保留为隐藏的序列化与剪贴板形式。会话选择使用规范的 `@[label](dsh-session:…)` mention;序列化永远不会根据可见标题重建身份。 -插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整引用,不执行文件发现;共享计算器按原文位置裁定重叠。可交互的文件节点通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。 +插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整候选引用,不执行文件发现;共享计算器按原文位置裁定重叠。两个节点 renderer 都订阅绑定 Session 的 `pathPresence` 键控 Hook,其背后是 `workspaceFiles/stat`:stat 成功或 `workspace-file/not-regular-file` 失败(目录、无论指向何处的符号链接或其他非普通条目)即确认路径存在,`workspace-file/not-found` 判定不存在,其他失败则保持未确认,由下一个订阅者重试。插件持有这些结果,每个 Session 与路径保留一份,并在卸载时中止未完成的 stat;选定 pick 会把其路径记为已确认。存在性不通过 `useResource` 读取 [`file` 资源](../../api/workspace-files/README.zh.md):该 provider 在有读取方挂载期间为每个 Session 与路径保持一个 Host 变更订阅,而一次提及只需要一个结果。可交互的文件节点还通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。
    @@ -97,6 +103,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 - **候选失败有意保持静默**:Remote 发现调用不可用或失败时,该领域不产生候选行。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。 - **浏览器侧不扫描文件**:Web 补全需要挂载宿主 `ctx.fileReferences` 提供方;浏览器无法回退到自身文件系统。 +- **已发送引用不跟随文件变化**:路径的确认或不存在结果在一次页面加载内保持不变;之后创建或删除该路径,只有刷新页面后才会改变其引用的渲染。 - **会话搜索仍仅使用元数据**:发现流程通过 `ctx.sessionReferenceResolver` 筛选 session id、cwd 与以日志为依据的最新标题;不搜索消息主体或完整 transcript。 diff --git a/packages/client/ui-reference/src/client/FileReference.tsx b/packages/client/ui-reference/src/client/FileReference.tsx index ceeb7cc6fc..4049a467b0 100644 --- a/packages/client/ui-reference/src/client/FileReference.tsx +++ b/packages/client/ui-reference/src/client/FileReference.tsx @@ -1,13 +1,22 @@ /** File navigation feedback belongs to the individual inline reference that requested it. */ import { useState } from 'react' import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' -import { Button, Modal, ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives' +import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import { Button, Modal, ReferenceChip, UserTextRun } from '@deepseek-ai/dsh-client-ui-primitives' import type { NS } from './locales.ts' +import type { PathPresence } from './path-presence.ts' import type {} from './user-text-rules.ts' +/** Host-confirmed presence of mention paths in the rendering Session. */ +export interface PathPresenceInjected { + readonly keyedHooks: { + /** Presence of one decoded mention path; subscribing starts its Host stat. */ + readonly pathPresence: (path: string) => HostObservable + } +} + /** Session-authorized synchronous navigation; document reading belongs to the preview host. */ -export interface FileReferenceInjected { +export interface FileReferenceInjected extends PathPresenceInjected { /** * Open or reveal a file in the current Sidebar using the originating Session's authority. * @param path - decoded path from the reference. @@ -20,15 +29,21 @@ export interface FileReferenceInjected { type FileReferenceProps = UserTextNodeProps<'file'> & InjectFace & PropsLocale +type FolderReferenceProps = UserTextNodeProps<'folder'> & InjectFace + /** - * Render a file chip and contain synchronous navigation failures without hiding the reference. - * @param props - JSON node, interaction policy, Session-authorized navigation, and locale seat. - * @returns an inline chip and, after a navigation failure, its body-portaled dialog. + * Render a file chip once the Host confirms its path exists, and contain synchronous navigation failures without hiding the reference. + * @param props - JSON node, interaction policy, Session-authorized navigation and presence, and locale seat. + * @returns the original spelling until confirmation; afterwards an inline chip and, after a navigation failure, its body-portaled dialog. */ -export function FileReference({ node, raw, interactive, openFile, resolveFilePath, sessionId, useContextMenu, t }: FileReferenceProps) { +export function FileReference({ + node, raw, interactive, openFile, resolveFilePath, sessionId, useContextMenu, usePathPresence, t, +}: FileReferenceProps) { const { getTriggerProps } = useContextMenu() const [failedPath, setFailedPath] = useState(null) const { path, label } = node.data + const presence = usePathPresence(path) + if (presence !== 'present') return const close = () => { setFailedPath(null) } const open = () => { try { @@ -62,10 +77,12 @@ export function FileReference({ node, raw, interactive, openFile, resolveFilePat } /** - * Render a directory as a label, even when the containing text permits file navigation. - * @param props - resolved directory data and the original reference spelling. - * @returns an inline non-interactive chip. + * Render a directory as a label once the Host confirms its path exists, even when the containing text permits file navigation. + * @param props - directory data, the original reference spelling, and Session-scoped presence. + * @returns the original spelling until confirmation, then an inline non-interactive chip. */ -export function FolderReference({ node, raw }: UserTextNodeProps<'folder'>) { - return +export function FolderReference({ node, raw, usePathPresence }: FolderReferenceProps) { + return usePathPresence(node.data.path) === 'present' + ? + : } diff --git a/packages/client/ui-reference/src/client/context-menu.ts b/packages/client/ui-reference/src/client/context-menu.ts new file mode 100644 index 0000000000..7e13b3d876 --- /dev/null +++ b/packages/client/ui-reference/src/client/context-menu.ts @@ -0,0 +1,50 @@ +/** File references contributed to the shared file menu. */ +import type { Context } from '@deepseek-ai/cordis' +import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import { IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { formatFileMention } from '@deepseek-ai/dsh-file-reference/grammar' +import { resolveWorkspacePath, workspaceTitleOf } from '@deepseek-ai/dsh-util-workspace-path' +import type { ReferenceKey } from './locales.ts' + +/** + * Add the captured file to its Session draft without submitting or replacing selected text. + * @param ctx - reference plugin's menu and conversation dependencies. + * @param t - localized labels and failure feedback. + */ +export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => string): void { + ctx.slots.inject('contextMenu.icon', () => ctx.slots.register({ + name: 'contextMenu.icon', key: 'reference.addToChat', + }, IconPlusOutlineRegular)) + const targetInput = ({ sessionId }: ContextMenuTargetMap['file']) => { + const binding = ctx.sessions.binding(sessionId) + if (binding === undefined) return undefined + const input = ctx.conversation.input.for(binding.ctx) + // A released or replaced binding must not receive the reference captured for its predecessor. + const editable = (): boolean => ctx.sessions.binding(sessionId) === binding && input.canInsertReferences() + return { input, editable } + } + ctx.effect(() => ctx.contextMenus.register({ + id: 'reference.file', target: 'file', order: 300, + // Draft editability is read when the menu opens; run rechecks it before inserting. + observe: () => [ctx.locale], + resolve: (target) => { + const current = targetInput(target) + const path = resolveWorkspacePath(ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd, target.path) + const mention = formatFileMention({ path, kind: 'file' }, false) + return [{ + id: 'addToChat', label: t('menu.addToChat'), icon: { key: 'reference.addToChat' }, separatorBefore: true, + disabled: mention === undefined || current === undefined || !current.editable(), + failureLabel: t('menu.addToChatFailed'), + run: () => { + if (mention === undefined || current === undefined || !current.editable() + || !current.input.addReferences([{ + source: 'reference', ref: mention, label: workspaceTitleOf(path), + appearance: 'file', clipboardText: mention, + }])) throw new Error('File reference insertion unavailable') + current.input.focus() + }, + }] + }, + }), 'ui-reference: file context menu') +} diff --git a/packages/client/ui-reference/src/client/index.ts b/packages/client/ui-reference/src/client/index.ts index ab66cffa5e..85a18ce72b 100644 --- a/packages/client/ui-reference/src/client/index.ts +++ b/packages/client/ui-reference/src/client/index.ts @@ -11,6 +11,11 @@ * workspace is not the current one. A session is dated from the Host session * list, so the `@` menu and the session list never disagree about its age. * + * A file or folder mention in sent text renders as a chip only after the + * Session's filesystem confirms the path exists; picking a listed candidate + * confirms it, and any other mention stays original text until a Host stat + * answers. + * * @module @deepseek-ai/dsh-client-ui-reference/client */ // Type-only: pulls the generated Remote API and ctx.remote merge through the Client assembly boundary. @@ -23,8 +28,11 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client' import { relativeTime } from '@deepseek-ai/dsh-client-ui-primitives' import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { FileReference, FolderReference, type FileReferenceInjected } from './FileReference.tsx' -import { fileReferenceRule, folderReferenceRule } from './user-text-rules.ts' +import { + FileReference, FolderReference, type FileReferenceInjected, type PathPresenceInjected, +} from './FileReference.tsx' +import { createPathPresence, type MentionSessionId } from './path-presence.ts' +import { fileReferenceRule, folderReferenceRule, mentionPath } from './user-text-rules.ts' export type {} from './user-text-rules.ts' import type { ClientSessionContext, InputTriggerCrumb, InputTriggerServiceContract, InputTriggerSource, @@ -34,6 +42,7 @@ import type { FileReferenceCandidate } from '@deepseek-ai/dsh-file-reference/typ import type { SessionReferenceMentionCandidate } from '@deepseek-ai/dsh-session-reference/types' import { abbreviateHomePath, fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import { en, ja, es, fr, de, ru, pt, NS, zh, type ReferenceKey } from './locales.ts' +import { registerReferenceMenu } from './context-menu.ts' declare module '@deepseek-ai/dsh-api-session-controller/client' { interface SessionReferenceSourceMap { @@ -45,7 +54,7 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' { /** Required services: the trigger registry, the Remote namespaces, and the copy. */ export const inject = [ 'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences', - 'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation', + 'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation', ] /** @@ -55,13 +64,20 @@ export const inject = [ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-reference: dictionaries') const t = ctx.locale.bind(NS) + ctx.inject(['contextMenus', 'conversation'], (menuCtx) => { registerReferenceMenu(menuCtx, t) }) const sessions = ctx.get('sessions') as ISessions + const presence = createPathPresence((sessionId, path, signal) => ctx.remote.workspaceFiles.stat(sessionId, path, signal)) + ctx.effect(() => () => { presence.dispose() }, 'ui-reference: mention path stats') + const presenceFor = (sessionId: MentionSessionId): PathPresenceInjected => ({ + keyedHooks: { pathPresence: path => presence.source(sessionId, path) }, + }) ctx.uiConversation.userText.register(fileReferenceRule) ctx.uiConversation.userText.register(folderReferenceRule) ctx.slots.inject('conversation.user.text.node', function* () { yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', priority: 100, locale: NS, inject: (sessionId: UserTextNodeProps<'file'>['sessionId']): FileReferenceInjected => ({ + ...presenceFor(sessionId), resolveFilePath: path => resolveWorkspacePath(sessions.list.getSnapshot().byId[sessionId]?.cwd, path), openFile: (path) => { const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd @@ -69,7 +85,9 @@ export function apply(ctx: ClientContext): void { }, }), }, FileReference) - yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', priority: 100 }, FolderReference) + yield ctx.slots.register({ + name: 'conversation.user.text.node', key: 'folder', priority: 100, inject: presenceFor, + }, FolderReference) }) const source: InputTriggerSource = { trigger: '@', @@ -129,7 +147,7 @@ export function apply(ctx: ClientContext): void { header(_session: ClientSessionContext, req) { return crumbsFor(req.query, req.quoted === true, req.drilled, t) }, - onPick({ candidate, action }) { + onPick({ candidate, session, action }) { const value = parseCandidate(candidate.value) if (value?.kind === 'file') { // A directory row carries two verbs: the settling pick resolves the @@ -139,6 +157,8 @@ export function apply(ctx: ClientContext): void { if (value.fileKind === 'directory' && action === 'drill') { return { text: value.mention, continue: true } } + // The Host has just listed this path, so its sent echo renders as a chip without a stat. + presence.confirm(session.sessionId, mentionPath(value.mention)) return { insert: { source: 'reference', @@ -164,7 +184,7 @@ export function apply(ctx: ClientContext): void { }, openReference(session, { ref, appearance }) { if (appearance !== 'file') return false - const path = ref.startsWith('@"') ? ref.slice(2, -1) : ref.slice(1) + const path = mentionPath(ref) const cwd = sessions.list.getSnapshot().byId[session.sessionId]?.cwd ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, cwd, path)) return true diff --git a/packages/client/ui-reference/src/client/locales.ts b/packages/client/ui-reference/src/client/locales.ts index a742c82eca..e4b4ad2f76 100644 --- a/packages/client/ui-reference/src/client/locales.ts +++ b/packages/client/ui-reference/src/client/locales.ts @@ -13,6 +13,8 @@ export const NS = 'reference' * bucketing they name is the one shared {@link relativeTime} in ui-primitives. */ export const zh = { + 'menu.addToChat': '添加到对话', + 'menu.addToChatFailed': '无法添加文件,请返回对话后重试', 'section.files': '文件与文件夹', 'section.subagents': '子智能体', 'section.sessions': '对话', @@ -42,6 +44,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { /** English dictionary, checked complete against the zh key set. */ export const en = { + 'menu.addToChat': 'Add to chat', + 'menu.addToChatFailed': 'Couldn’t add file. Return to the chat and try again.', 'section.files': 'Files & folders', 'section.subagents': 'Subagents', 'section.sessions': 'Sessions', @@ -61,6 +65,8 @@ export const en = { /** Japanese copy, checked against the English keys. */ export const ja = { + 'menu.addToChat': 'チャットに追加', + 'menu.addToChatFailed': 'ファイルを追加できませんでした。チャットに戻って再試行してください。', 'section.files': 'ファイルとフォルダ', 'section.subagents': 'サブエージェント', 'section.sessions': 'セッション', @@ -80,6 +86,8 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { + 'menu.addToChat': 'Añadir al chat', + 'menu.addToChatFailed': 'No se pudo añadir el archivo. Vuelve al chat e inténtalo de nuevo.', 'section.files': 'Archivos y carpetas', 'section.subagents': 'Subagentes', 'section.sessions': 'Sesiones', @@ -99,6 +107,8 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { + 'menu.addToChat': 'Ajouter au chat', + 'menu.addToChatFailed': 'Impossible d’ajouter le fichier. Revenez au chat et réessayez.', 'section.files': 'Fichiers et dossiers', 'section.subagents': 'Sous-agents', 'section.sessions': 'Séances', @@ -118,6 +128,8 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { + 'menu.addToChat': 'Zum Chat hinzufügen', + 'menu.addToChatFailed': 'Datei konnte nicht hinzugefügt werden. Kehren Sie zum Chat zurück und versuchen Sie es erneut.', 'section.files': 'Dateien und Ordner', 'section.subagents': 'Subagenten', 'section.sessions': 'Sitzungen', @@ -137,6 +149,8 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { + 'menu.addToChat': 'Добавить в чат', + 'menu.addToChatFailed': 'Не удалось добавить файл. Вернитесь в чат и повторите попытку.', 'section.files': 'Файлы и папки', 'section.subagents': 'Субагенты', 'section.sessions': 'Сессии', @@ -156,6 +170,8 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { + 'menu.addToChat': 'Adicionar ao chat', + 'menu.addToChatFailed': 'Não foi possível adicionar o arquivo. Volte ao chat e tente novamente.', 'section.files': 'Arquivos e pastas', 'section.subagents': 'Subagentes', 'section.sessions': 'Sessões', diff --git a/packages/client/ui-reference/src/client/path-presence.ts b/packages/client/ui-reference/src/client/path-presence.ts new file mode 100644 index 0000000000..886bb2db10 --- /dev/null +++ b/packages/client/ui-reference/src/client/path-presence.ts @@ -0,0 +1,140 @@ +/** + * Session-scoped Host confirmation that a mentioned path exists. + * + * Each Session and path pair is stat'ed at most once while the owning plugin + * is live. Only a definitive Host answer is retained; any other failure leaves + * the pair unconfirmed, and the next subscriber asks again. Retained answers + * are not refreshed when the path is created or removed later. Entries live as + * long as the plugin, one per distinct mention the client has rendered. Each + * unconfirmed pair starts its own Host request when first subscribed; nothing + * bounds how many are outstanding at once. + */ +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' + +/** Session whose filesystem resolves a mention. */ +export type MentionSessionId = UserTextNodeProps<'file'>['sessionId'] + +/** Host answer for one mentioned path; `undefined` means unconfirmed. */ +export type PathPresence = 'present' | 'absent' + +/** + * Session-authorized stat of one path, absolute or relative to the Session's workspace root. + * @param sessionId - Session whose filesystem resolves the path. + * @param path - path as the mention spells it. + * @param signal - cancellation owned by the presence sources. + * @returns the regular file's metadata, or the Host's typed failure. + */ +export type PathStat = ( + sessionId: MentionSessionId, + path: string, + signal: AbortSignal, +) => Promise> + +/** Presence sources shared by every mention one plugin instance renders. */ +export interface PathPresenceSources { + /** + * Observe one path; the first subscription to an unconfirmed path starts its Host stat. + * @param sessionId - Session whose filesystem resolves the path. + * @param path - decoded mention path. + * @returns the same source for the same pair until disposal. + */ + source(sessionId: MentionSessionId, path: string): HostObservable + /** + * Record a path the Host has just listed, such as a picked completion candidate. + * @param sessionId - Session whose filesystem listed the path. + * @param path - decoded mention path. + */ + confirm(sessionId: MentionSessionId, path: string): void + /** Abort outstanding stats; later subscriptions start none. */ + dispose(): void +} + +interface Entry { + presence: PathPresence | undefined + probing: boolean + readonly listeners: Set<() => void> + readonly source: HostObservable +} + +/** + * Classify one stat. A directory, a symbolic link whatever it points to, or + * another non-regular entry still exists; failures that do not describe the + * path leave it unconfirmed. + * @param result - Host stat result. + * @returns the definitive presence, or undefined. + */ +function presenceOf(result: RemoteResult): PathPresence | undefined { + if (result.ok) return 'present' + switch (result.error.code) { + case 'workspace-file/not-regular-file': + return 'present' + case 'workspace-file/not-found': + return 'absent' + default: + return undefined + } +} + +/** + * Create presence sources over one stat function. + * @param stat - Session-authorized Host stat. + * @returns sources the caller disposes with its plugin. + */ +export function createPathPresence(stat: PathStat): PathPresenceSources { + const lifetime = new AbortController() + const entries = new Map() + + const publish = (entry: Entry, presence: PathPresence) => { + entry.presence = presence + for (const listener of [...entry.listeners]) listener() + } + + const probe = (entry: Entry, sessionId: MentionSessionId, path: string) => { + if (entry.probing || entry.presence !== undefined || lifetime.signal.aborted) return + entry.probing = true + // Cancellation and carrier faults resolve as failures. Only a Remote + // assembly fault rejects: it stays an unhandled rejection so the fault is + // reported, and the pair stays unconfirmed for the next subscriber. + void stat(sessionId, path, lifetime.signal).then((result) => { + const presence = presenceOf(result) + // A confirmation recorded while this stat was outstanding is newer. + if (presence === undefined || entry.presence !== undefined || lifetime.signal.aborted) return + publish(entry, presence) + }).finally(() => { entry.probing = false }) + } + + const entryFor = (sessionId: MentionSessionId, path: string): Entry => { + const key = JSON.stringify([sessionId, path]) + const existing = entries.get(key) + if (existing !== undefined) return existing + const entry: Entry = { + presence: undefined, + probing: false, + listeners: new Set(), + source: { + getSnapshot: () => entry.presence, + subscribe: (listener) => { + entry.listeners.add(listener) + probe(entry, sessionId, path) + return () => { entry.listeners.delete(listener) } + }, + }, + } + entries.set(key, entry) + return entry + } + + return { + source: (sessionId, path) => entryFor(sessionId, path).source, + confirm(sessionId, path) { + const entry = entryFor(sessionId, path) + if (entry.presence !== 'present') publish(entry, 'present') + }, + dispose() { + lifetime.abort() + }, + } +} diff --git a/packages/client/ui-reference/src/client/user-text-rules.ts b/packages/client/ui-reference/src/client/user-text-rules.ts index b227660c86..060918ba6c 100644 --- a/packages/client/ui-reference/src/client/user-text-rules.ts +++ b/packages/client/ui-reference/src/client/user-text-rules.ts @@ -1,4 +1,7 @@ -/** Forward file and folder recognition in original text, without Facts or discovery. */ +/** + * Forward file and folder mention candidates in original text, without Facts or discovery. + * The node components decide whether a candidate names an existing path. + */ import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' interface PathReferenceData { @@ -13,6 +16,15 @@ declare module '@deepseek-ai/dsh-client-ui-conversation/client' { } } +/** + * Decode the path a complete `@path` or `@"quoted path"` mention names. + * @param mention - mention spelling starting with `@`, without trailing sentence punctuation. + * @returns the path that file and folder nodes carry. + */ +export function mentionPath(mention: string): string { + return mention.slice(1).replace(/^"|"$/gu, '') +} + function nextPath(text: string, from: number, folder: boolean) { const tokens = /(? = {}, opening: Pick = {}, + stat: PathStat = vi.fn(() => new Promise(() => {})), ) { const ctx = new Context() ctx.provide('sidebarRight', { openResource: vi.fn() }) @@ -119,6 +123,7 @@ async function bench( new RemoteService(ctx) ctx.provide('remote.fileReferences', { list: files }) ctx.provide('remote.sessionReferenceResolver', { candidates: sessions }) + ctx.provide('remote.workspaceFiles', { stat }) ctx.provide('locale', new LocaleRuntime(ctx)) const sessionStore = new TestSessions(async (action) => { await action() }, ctx) onTestFinished(async () => { @@ -139,11 +144,17 @@ async function bench( return { ctx, fiber, source, sessions: sessionStore, owner } } +/** The Session-bound presence face a file or folder text node entry injects. */ +function injectedPresence(ctx: Context, key: 'file' | 'folder'): (id: SessionId) => PathPresenceInjected { + const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === key)! + return entry.inject as NonNullable & ((id: SessionId) => PathPresenceInjected) +} + describe('apply', () => { it('declares its services and releases the @ reference registration on disposal', async () => { expect(inject).toEqual([ 'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences', - 'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation', + 'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation', ]) const { fiber } = await bench() let registered: InputTriggerSource | undefined @@ -166,6 +177,7 @@ describe('apply', () => { new RemoteService(ctx) ctx.provide('remote.fileReferences', { list: () => Promise.resolve({ ok: true, value: [] }) }) ctx.provide('remote.sessionReferenceResolver', { candidates: () => Promise.resolve({ ok: true, value: [] }) }) + ctx.provide('remote.workspaceFiles', { stat: vi.fn() }) ctx.provide('locale', new LocaleRuntime(ctx)) const sessions = new TestSessions(async (action) => { await action() }, ctx) onTestFinished(() => sessions.disposeScopes()) @@ -671,6 +683,23 @@ describe('pick and codec', () => { await expect(source.codec?.serialize(mention, new AbortController().signal)).resolves.toBe(mention) }) + it('confirms settled file and folder picks for the picking Session; a drill confirms nothing', async () => { + const stat = vi.fn(() => new Promise(() => {})) + const { ctx, source } = await bench(undefined, undefined, {}, {}, stat) + const [directory, file] = await source.candidates(session, request('')) + const folderFace = injectedPresence(ctx, 'folder') + const fileFace = injectedPresence(ctx, 'file') + drill(source, directory!) + expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined() + pick(source, directory!) + pick(source, file!) + expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBe('present') + expect(fileFace(session.sessionId).keyedHooks.pathPresence('docs/a b.md').getSnapshot()).toBe('present') + expect(folderFace(sid('other')).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined() + folderFace(session.sessionId).keyedHooks.pathPresence('src/').subscribe(vi.fn()) + expect(stat).not.toHaveBeenCalled() + }) + it('ignores candidates that do not carry a source-owned value', async () => { const { source } = await bench() expect(pick(source, { name: 'foreign candidate' })).toBeUndefined() @@ -678,6 +707,17 @@ describe('pick and codec', () => { }) describe('reference preview', () => { + it('stats each mention through its rendering Session and aborts outstanding stats on disposal', async () => { + const stat = vi.fn(() => new Promise(() => {})) + const { ctx, fiber } = await bench(undefined, undefined, {}, {}, stat) + injectedPresence(ctx, 'file')(session.sessionId).keyedHooks.pathPresence('LICENSE').subscribe(vi.fn()) + injectedPresence(ctx, 'folder')(sid('other')).keyedHooks.pathPresence('docs/').subscribe(vi.fn()) + expect(stat.mock.calls.map(([id, path]) => [id, path])).toEqual([['target', 'LICENSE'], ['other', 'docs/']]) + expect(stat.mock.calls.some(([, , signal]) => signal.aborted)).toBe(false) + await fiber.dispose() + expect(stat.mock.calls.every(([, , signal]) => signal.aborted)).toBe(true) + }) + it('binds each inline file action to its originating Session', async () => { const { ctx, sessions } = await bench() const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === 'file')! diff --git a/packages/client/ui-reference/tests/context-menu.client.spec.ts b/packages/client/ui-reference/tests/context-menu.client.spec.ts new file mode 100644 index 0000000000..aa67881729 --- /dev/null +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -0,0 +1,212 @@ +// @vitest-environment jsdom +/** Shared file menus insert references through the Session's real draft editor. */ +import { expect, it, onTestFinished, vi } from 'vitest' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' +import { SessionInputShell } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/facade.ts' +import { ComposerBlockRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/blocks.ts' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import { registerReferenceMenu } from '../src/client/context-menu.ts' +import { en, zh } from '../src/client/locales.ts' + +const id = 'target' as SessionId +const actionId = 'reference.file/addToChat' + +async function bench() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + runtime.ctx.provide('locale', locale) + runtime.ctx.effect(() => locale.register('reference', { en, zh })) + locale.setLocale('en') + await runtime.declare({ 'contextMenu.icon': { kind: 'keyed', scope: 'root', inline: true } }) + await runtime.sessions.add({ id, summary: { cwd: '/workspace' } }) + const owner = runtime.sessions.retain(id) + onTestFinished(() => { owner.release() }) + const binding = runtime.sessions.binding(id)! + const sink = vi.fn(async () => ({ kind: 'success' as const })) + const blocks = new ComposerBlockRegistry() + const shell = new SessionInputShell({ + actx: binding.ctx, defaultSink: sink, + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, + session: () => binding.session.getSnapshot(), + composerBlock: () => blocks.storeFor(id).getSnapshot(), + }) + onTestFinished(() => { shell.dispose() }) + const focus = vi.spyOn(shell, 'focus').mockImplementation(() => {}) + const resolveInput = vi.fn(() => shell) + runtime.ctx.provide('conversation', { input: { for: resolveInput } }) + const failed = vi.fn() + const menus = new MenuRegistry(failed) + onTestFinished(() => { menus.dispose() }) + runtime.ctx.provide('contextMenus', { register: menus.register.bind(menus) }) + const fiber = runtime.ctx.plugin({ + inject: ['slots', 'sessions', 'conversation', 'contextMenus', 'locale'], + apply: (ctx) => { registerReferenceMenu(ctx, locale.bind('reference')) }, + }) + await fiber.await() + const menu = async (value: Partial = {}) => { + const result = menus.resolve({ kind: 'file', value: { sessionId: id, path: 'docs/a b.md', ...value } }) + onTestFinished(() => { result.dispose() }) + await result.ready + return result + } + return { runtime, locale, owner, binding, shell, sink, focus, blocks, resolveInput, failed, menus, fiber, menu } +} + +it('appends the final action after other providers and inserts the captured file without sending', async () => { + const b = await bench() + const ready = Promise.withResolvers() + b.menus.register({ id: 'open', target: 'file', order: 100, resolve: async () => { + await ready.promise + return [{ id: 'preview', label: 'Preview' }] + } }) + b.menus.register({ id: 'save', target: 'file', order: 200, resolve: () => [{ id: 'download', label: 'Download' }] }) + b.shell.setDraft('Review this') + const pending = b.menu({ line: 24 }) + ready.resolve(undefined) + const menu = await pending + expect(menu.source.getSnapshot().map(row => row.label)).toEqual(['Preview', 'Download', en['menu.addToChat']]) + expect(menu.source.getSnapshot().at(-1)).toMatchObject({ separatorBefore: true, disabled: false }) + menu.select(actionId) + expect(b.resolveInput).toHaveBeenCalledWith(b.binding.ctx) + expect(b.shell.snapshot.draft).toBe('Review this @"/workspace/docs/a b.md" ') + expect(b.shell.snapshot.occurrences).toMatchObject([{ + source: 'reference', ref: '@"/workspace/docs/a b.md"', label: 'a b.md', appearance: 'file', + }]) + expect(b.shell.snapshot.attachmentIds).toEqual([]) + expect(b.focus).toHaveBeenCalledOnce() + expect(b.sink).not.toHaveBeenCalled() + expect(b.failed).not.toHaveBeenCalled() +}) + +it.each(['bad"name.txt', 'bad\nname.txt'])('disables paths outside the mention grammar: %j', async (path) => { + const b = await bench() + const menu = await b.menu({ path }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + menu.select(actionId) + expect(b.shell.snapshot.draft).toBe('') + expect(b.focus).not.toHaveBeenCalled() +}) + +it('disables an unretained Session and never opens it or targets another draft', async () => { + const b = await bench() + const menu = await b.menu({ sessionId: 'absent' as SessionId }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + expect(b.resolveInput).not.toHaveBeenCalled() + menu.select(actionId) + expect(b.shell.snapshot.draft).toBe('') +}) + +it('reads composer blocks when the menu opens and rechecks them at execution', async () => { + const b = await bench() + b.blocks.set(id, { reason: 'Unavailable' }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) + b.blocks.set(id, undefined) + const menu = await b.menu() + expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + b.blocks.set(id, { reason: 'Unavailable' }) + // An open menu keeps the state read when it opened; execution refuses the stale action. + expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) + expect(b.shell.snapshot.draft).toBe('') + expect(b.focus).not.toHaveBeenCalled() +}) + +it('rejects a stale Session binding at execution', async () => { + const b = await bench() + const menu = await b.menu() + b.owner.release() + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) + expect(b.focus).not.toHaveBeenCalled() +}) + +it('disables removed and one-shot Sessions but permits continuable Sessions', async () => { + const b = await bench() + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = true }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { + state.removed = false + state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'one-shot' } } + }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { + state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'continuable' } } + }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false) +}) + +it('disables the action while a submission owns the draft but not while a turn runs', async () => { + const b = await bench() + const pending = Promise.withResolvers<{ kind: 'success' }>() + b.sink.mockImplementation(() => pending.promise) + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.running = true }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false) + b.shell.setDraft('Sending') + b.shell.submit() + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) + pending.resolve({ kind: 'success' }) + await vi.waitFor(() => { expect(b.shell.snapshot.phase).toBe('plain') }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false) +}) + +it('reports insertion refusal without focusing or sending', async () => { + const b = await bench() + vi.spyOn(b.shell, 'addReferences').mockReturnValue(false) + const menu = await b.menu() + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) + expect(b.focus).not.toHaveBeenCalled() + expect(b.sink).not.toHaveBeenCalled() +}) + +it('withdraws open menu actions and their icon on plugin disposal', async () => { + const b = await bench() + const menu = await b.menu() + expect(b.runtime.ctx.slots.entries('contextMenu.icon').map(row => row.options.key)).toEqual(['reference.addToChat']) + await b.fiber.dispose() + expect(menu.source.getSnapshot()).toEqual([]) + expect(b.runtime.ctx.slots.entries('contextMenu.icon')).toEqual([]) + menu.select(actionId) + expect(b.focus).not.toHaveBeenCalled() + expect(zh['menu.addToChat']).toBe('添加到对话') +}) + +it('refreshes open labels and failure feedback when the locale changes', async () => { + const b = await bench() + const menu = await b.menu() + const unavailable = await b.menu({ sessionId: 'absent' as SessionId }) + expect(menu.source.getSnapshot()[0]?.label).toBe(en['menu.addToChat']) + expect(unavailable.source.getSnapshot()[0]?.label).toBe(en['menu.addToChat']) + b.locale.setLocale('zh') + expect(menu.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat']) + expect(unavailable.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat']) + vi.spyOn(b.shell, 'addReferences').mockReturnValue(false) + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(zh['menu.addToChatFailed']) + await b.fiber.dispose() + b.locale.setLocale('en') + expect(unavailable.source.getSnapshot()).toEqual([]) +}) + +it.each(['/work/a b.md', 'C:\\work\\a b.md', '\\\\server\\share\\a b.md', '/work/a b.md/'])( + 'uses the final nonempty path segment as the reference label: %j', async (path) => { + const b = await bench() + const menu = await b.menu({ path }) + menu.select(actionId) + expect(b.shell.snapshot.occurrences).toMatchObject([{ label: 'a b.md', ref: `@"${path}"` }]) + }, +) + +it('disables the action and refuses direct insertion after the draft editor is disposed', async () => { + const b = await bench() + b.shell.setDraft('Keep this') + b.shell.dispose() + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) + expect(b.shell.addReferences([{ source: 'reference', ref: '@file.txt', label: 'file.txt', clipboardText: '@file.txt' }])).toBe(false) + expect(b.shell.snapshot.draft).toBe('Keep this') +}) diff --git a/packages/client/ui-reference/tests/file-reference.client.spec.tsx b/packages/client/ui-reference/tests/file-reference.client.spec.tsx index d033443112..aac310c2ca 100644 --- a/packages/client/ui-reference/tests/file-reference.client.spec.tsx +++ b/packages/client/ui-reference/tests/file-reference.client.spec.tsx @@ -12,17 +12,41 @@ import { brandString } from '@deepseek-ai/dsh-brand' afterEach(cleanup) type Props = ComponentProps +type Presence = ReturnType -function props(openFile: Props['openFile']): Props { +function presenceHook(presence: Record): Props['usePathPresence'] { + const hook = (path: string) => presence[path] + return hook as Props['usePathPresence'] +} + +const PRESENT = presenceHook({ 'docs/a b.md': 'present', 'docs/': 'present' }) + +function props(openFile: Props['openFile'], usePathPresence = PRESENT): Props { return { node: { id: 'file', start: 0, end: 14, data: { path: 'docs/a b.md', label: 'a b.md' } }, - raw: '@"docs/a b.md"', interactive: true, openFile, t: makeTranslate(en), + raw: '@"docs/a b.md"', interactive: true, openFile, usePathPresence, t: makeTranslate(en), useContextMenu: contextMenuHook(), sessionId: brandString('original'), resolveFilePath: path => `/workspace/${path}`, } as Props } describe('FileReference', () => { + it('keeps the original spelling until the Host confirms the path exists', () => { + const openFile = vi.fn() + const folder = { id: 'folder', start: 0, end: 6, data: { path: 'docs/', label: 'docs' } } as const + for (const presence of [undefined, 'absent'] as const) { + const usePathPresence = presenceHook({ 'docs/a b.md': presence, 'docs/': presence }) + const view = render(<> + + + ) + expect(view.container.textContent).toBe('@"docs/a b.md"@docs/') + expect(view.container.querySelector('[data-ref-chip]')).toBeNull() + view.unmount() + } + expect(openFile).not.toHaveBeenCalled() + }) + it('opens the decoded path and leaves summaries and folders non-interactive', () => { const openFile = vi.fn() const input = props(openFile) diff --git a/packages/client/ui-reference/tests/path-presence.client.spec.ts b/packages/client/ui-reference/tests/path-presence.client.spec.ts new file mode 100644 index 0000000000..cc13fa4659 --- /dev/null +++ b/packages/client/ui-reference/tests/path-presence.client.spec.ts @@ -0,0 +1,136 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client' +import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { createPathPresence, type MentionSessionId, type PathStat } from '../src/client/path-presence.ts' + +const sid = (value: string): MentionSessionId => value as MentionSessionId +const STAT: WorkspaceFileStat = { absolutePath: '/w/LICENSE', version: 'v1' } + +interface StatCall { + readonly sessionId: MentionSessionId + readonly path: string + readonly signal: AbortSignal + readonly resolve: (result: RemoteResult) => void +} + +function deferredStat() { + const calls: StatCall[] = [] + const stat = vi.fn((sessionId, path, signal) => new Promise((resolve) => { + calls.push({ sessionId, path, signal, resolve }) + })) + return { stat, calls } +} + +const failure = (error: RemoteFailure): RemoteResult => ({ ok: false, error }) + +describe('createPathPresence', () => { + it('shares one stat per Session and path and publishes the Host answer to every subscriber', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'LICENSE') + expect(presence.source(sid('a'), 'LICENSE')).toBe(source) + expect(presence.source(sid('b'), 'LICENSE')).not.toBe(source) + expect(source.getSnapshot()).toBeUndefined() + expect(stat).not.toHaveBeenCalled() + const first = vi.fn() + const second = vi.fn() + const unsubscribe = source.subscribe(first) + source.subscribe(second) + expect(calls.map(call => [call.sessionId, call.path])).toEqual([['a', 'LICENSE']]) + unsubscribe() + calls[0]!.resolve({ ok: true, value: STAT }) + await vi.waitFor(() => { expect(source.getSnapshot()).toBe('present') }) + expect(first).not.toHaveBeenCalled() + expect(second).toHaveBeenCalledOnce() + source.subscribe(vi.fn()) + expect(stat).toHaveBeenCalledOnce() + }) + + it('treats a non-regular entry as present, a missing entry as absent, and retries any other failure', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const folder = presence.source(sid('a'), 'docs/') + const missing = presence.source(sid('a'), 'ceshi') + const offline = presence.source(sid('a'), 'notes.md') + folder.subscribe(vi.fn()) + missing.subscribe(vi.fn()) + offline.subscribe(vi.fn()) + calls[0]!.resolve(failure(new RemoteError('workspace-file/not-regular-file', 'directory', { path: 'docs/', kind: 'directory' }))) + calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'ceshi' }))) + calls[2]!.resolve(failure(new RemoteError('gateway/internal', 'offline', {}))) + await vi.waitFor(() => { expect(missing.getSnapshot()).toBe('absent') }) + expect(folder.getSnapshot()).toBe('present') + expect(offline.getSnapshot()).toBeUndefined() + offline.subscribe(vi.fn()) + expect(calls.map(call => call.path)).toEqual(['docs/', 'ceshi', 'notes.md', 'notes.md']) + calls[3]!.resolve({ ok: true, value: STAT }) + await vi.waitFor(() => { expect(offline.getSnapshot()).toBe('present') }) + }) + + it('lets a picked confirmation stand over an older outstanding stat and over an earlier absence', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'new.md') + const listener = vi.fn() + source.subscribe(listener) + presence.confirm(sid('a'), 'new.md') + presence.confirm(sid('a'), 'new.md') + expect(source.getSnapshot()).toBe('present') + expect(listener).toHaveBeenCalledOnce() + calls[0]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'new.md' }))) + await Promise.resolve() + await Promise.resolve() + expect(source.getSnapshot()).toBe('present') + + const created = presence.source(sid('a'), 'later.md') + created.subscribe(vi.fn()) + calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'later.md' }))) + await vi.waitFor(() => { expect(created.getSnapshot()).toBe('absent') }) + presence.confirm(sid('a'), 'later.md') + expect(created.getSnapshot()).toBe('present') + const picked = presence.source(sid('a'), 'picked.md') + presence.confirm(sid('a'), 'picked.md') + picked.subscribe(vi.fn()) + expect(stat).toHaveBeenCalledTimes(2) + }) + + it('reports a rejected stat as an unhandled rejection and asks again for the next subscriber', async () => { + const fault = new Error('client api: workspaceFiles/stat has no active Connection') + const stat = vi.fn() + .mockRejectedValueOnce(fault) + .mockResolvedValueOnce({ ok: true, value: STAT }) + const rejections: unknown[] = [] + const onUnhandled = (reason: unknown): void => { rejections.push(reason) } + process.on('unhandledRejection', onUnhandled) + try { + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'LICENSE') + source.subscribe(vi.fn()) + await vi.waitFor(() => { expect(rejections).toEqual([fault]) }) + expect(source.getSnapshot()).toBeUndefined() + source.subscribe(vi.fn()) + expect(stat).toHaveBeenCalledTimes(2) + await vi.waitFor(() => { expect(source.getSnapshot()).toBe('present') }) + } finally { + process.off('unhandledRejection', onUnhandled) + } + }) + + it('aborts outstanding stats on disposal, drops their answers, and starts no further stats', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'LICENSE') + const listener = vi.fn() + source.subscribe(listener) + presence.dispose() + expect(calls[0]!.signal.aborted).toBe(true) + calls[0]!.resolve({ ok: true, value: STAT }) + await Promise.resolve() + await Promise.resolve() + expect(source.getSnapshot()).toBeUndefined() + expect(listener).not.toHaveBeenCalled() + presence.source(sid('a'), 'other.md').subscribe(vi.fn()) + expect(stat).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 1371e74c19..dd29125519 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -15,20 +15,20 @@ en: d152484eb41ac6b4 zh: 405b30feaf48c087 /deepseek-ai-dsh-client-ui-schedule/use-this-package: - en: 68526e7df25338d4 - zh: 3bfdfa01dc9afaec + en: dcae1793d89a2976 + zh: 9c66f7f4a1120023 /deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source: en: 4005b800e930f581 zh: ccb9318dad7f7e8f /deepseek-ai-dsh-client-ui-schedule/understand-the-implementation: - en: 73e3c0f06c7381e8 - zh: 4b83f0eb8da65ce1 + en: 5fde04ee7c0331ee + zh: 00fef5c10412079c /deepseek-ai-dsh-client-ui-schedule/further-exploration: en: 2fd968202916b197 zh: f1ab66194846562b /deepseek-ai-dsh-client-ui-schedule/model-experience: - en: 6f528a72fe45af1b - zh: 8272529f6e324315 + en: b75d2a967fdce99c + zh: f1464a27481329f2 /deepseek-ai-dsh-client-ui-schedule/model-experience/kv-cache-effect: en: 52239e5688dfebe1 zh: 37343f5dbde010e8 diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index fbd7582bd2..fed1d20837 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -25,9 +25,11 @@ The Automation tasks page and right Sidebar task tab use the same editor for tas ## Use this package +Without recommendations, catalog empty states center within the space below the page controls and remain scrollable on short viewports. With recommendations, the empty state and recommendation tiles stay in normal flow. Filters, input fields, multi-line task rows, and nested rule groups use the shared radius appropriate to their role. + Below 768px, the task list uses 20px horizontal insets, matching the Plugins page. -The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. +The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. Below the empty Enabled and All views, eight built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill. Enabled, Paused, Ended, and All filters combine with text search over the title, prompt, and linked Session id; the page starts on Enabled. The search-row menu clears all ended tasks after confirmation, preserving active and paused tasks. Selecting a task opens its editable Rules / Records page. Save is enabled only for valid, meaningful changes and sends only changed fields with `expectedUpdatedAt`, or `null` when no stored revision exists. The fields stay editable after saving. Unsaved drafts survive navigation between tasks and away from the page. A conflict retains the whole draft and disables Save. Review with my edits reapplies the changed field groups to the latest values for review before saving; Discard replaces the draft with the latest stored values. For a new task, Discard closes the editor. Late responses cannot change another task's detail. Coarse-pointer search, instruction, and timing fields use 16px text to prevent focus zoom on iOS Safari. @@ -41,7 +43,7 @@ The list, detail, header, and Session hover show the later of the scheduled occu Records lazily requests 20 saved deliveries, supports newest-first pagination, retains loaded records after failure, and ignores superseded or unmounted requests. Each record shows its occurrence and saved prompt, with Expand / Collapse for long prompts; legacy records without prompt text never substitute the current instruction. A receipt's actual destination has a conversation link when the Session is available. Confirmed pruning is stated only after the final saved page and offers the current retention explanation. These records acknowledge inbox delivery, not model execution success. -An open conversation's header clock remains hidden before the first successful read or while no active related tasks exist. One task opens its right Sidebar tab; several open the existing popover. Idle, unarchived Session rows with active related tasks retain their clock mark and hover list. `schedule_create` continues to render a Turn-level card with a task title, repeat description, and Open action. Persisted legacy and current tool results both render; an authoritative read newer than the card resolves later edits or deletion. +The conversation header shows a clock after the first successful catalog read if the conversation is the fixed delivery target of an active task. One task opens its right Sidebar tab. Several open the existing popover. Idle, unarchived Session rows with those tasks show a clock mark and hover list. `schedule_create` continues to render a Turn-level card with a task title, repeat description, and Open action. Persisted legacy and current tool results both render; an authoritative read newer than the card resolves later edits or deletion. ### Time-zone data source @@ -55,11 +57,13 @@ Task menus use the [standard menu geometry](../../../docs/ui-radius.md#nested-ho
    Implementation details — click to expand +Schedule group headings, field labels and hints share an inset text column inside the detail view. + While the Peer may read `schedule/catalog`, the plugin registers the existing `schedules` main panel, Session header utility, Turn tail card, Session row mark and hover entries, and `scheduleTask` right Sidebar tab. Slot injection supplies framework readers and action callbacks; components own selection, search, and paging state. Entry-declared stores retain each task draft and its CAS baseline across navigation within their root or Session scope; the main panel and Session tabs have independent drafts. Pristine forms follow the catalog. A dirty form retains all fields and its original revision. A newer catalog revision prevents saving until the user discards the draft or explicitly reapplies changed title, prompt, timing, and target groups to that revision. Reapplying does not write; the user reviews the resulting form and saves with the new CAS baseline. Untouched groups follow the newer record. Missing tasks retain editable local drafts while Host mutations stay disabled. Drafts are not persisted; a Client reload or disposal of the owning entry or Session scope drops them. The Host owns task storage and execution. Browsing catalogs does not activate a Session. Conflict feedback reuses the catalog notice style; its outlined review action wraps below the message in narrow panes. Edits to typed calendar timing use the shared recurrence evaluator to find the first valid future occurrence while preserving interval alignment across daylight-saving gaps. Successful edits use Schedule’s existing [current-format write path](../../schedule/schedule/README.md); a content-only edit retains the timing kind, precision, expression, and committed occurrence. -The manager, task tabs, row marks, and conversation-header projections share one observable `schedule.catalog` source. Header and row views filter active records by involvement and delivery target. Mutations use task-id-based `schedule.create`, `schedule.edit`, and `schedule.run`; history uses task identity and cursor without a Session ownership parameter. A mutation acknowledgment triggers a fresh authoritative read; a failed read remains a catalog error rather than changing the acknowledged write into a failure. +The manager, task tabs, row marks, and conversation-header projections share one observable `schedule.catalog` source. Header and row views select active records by their fixed delivery target. Mutations use task-id-based `schedule.create`, `schedule.edit`, and `schedule.run`; history uses task identity and cursor without a Session ownership parameter. A mutation acknowledgment triggers a fresh authoritative read; a failed read remains a catalog error rather than changing the acknowledged write into a failure. Sidebar layout records omit opener parameters. `TaskTabBindings` therefore persists task identity by Session and tab id in localStorage, without storing task content. Closed tab bindings are pruned. Observable catalog requests subscribe only while read, invalidate on Schedule changes and connection reset, and retire outstanding reads after the final subscriber leaves. @@ -74,7 +78,7 @@ Sidebar layout records omit opener parameters. `TaskTabBindings` therefore persi ## Model Experience -None, as this browser package registers no model tools or automatic messages; the creation prompt stays an unsent draft. +None, as this browser package registers no model tools or automatic messages; the creation prompt and recommended-task requests stay unsent drafts. #### KV Cache effect diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index 51b523d0b9..feeb07f771 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -25,9 +25,11 @@ kind: "package-reference" ## 使用本包 +没有推荐任务时,清单空状态在页面控件下方的剩余空间内居中,矮视口仍可滚动阅读。有推荐任务时,空状态与推荐卡片保持普通文档流。筛选、输入框、多行任务条目和嵌套规则组分别使用对应角色的统一圆角。 + 宽度小于 768px 时,任务列表使用 20px 的左右内边距,与插件页一致。 -发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。 +发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出八个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。 “已开启”“已暂停”“已结束”“全部”筛选结合标题、指令和关联会话 id 搜索,默认显示已开启任务。搜索行菜单在确认后清除全部已结束任务,保留已开启和已暂停任务。选择任务直接打开可编辑的“规则 / 任务运行记录”页面。只有字段有效且有实际修改时才能保存;保存只发送变更字段及 `expectedUpdatedAt`,存储版本缺失时发送 `null`。保存后字段保持可编辑。切换任务或离开页面时保留未保存的草稿。冲突保留整份草稿并禁用保存。“保留修改并复核”将改过的字段组应用到最新值,供保存前复核;“放弃”用最新存储值替换草稿。对于新任务,“放弃”关闭编辑页。迟到响应不会改变其他任务详情。粗指针设备的搜索、指令和时间字段使用 16px 字号,避免 iOS Safari 聚焦时缩放。 @@ -41,7 +43,7 @@ kind: "package-reference" “任务运行记录”按需请求 20 条已保存投递,支持从新到旧分页,失败时保留已加载记录,并忽略被刷新替代或卸载后的请求。每条记录显示投递发生时间与已保存指令,长指令可展开、收起;缺少指令的旧记录不使用当前指令替代。回执的实际执行会话可用时提供入口。仅在最后一页且确认裁剪后显示清理提示,并提供当前保留规则说明。这些记录确认收件箱投递,不表示模型执行成功。 -打开会话的页头时钟在首次读取成功之前或没有活动关联任务时保持隐藏。一个任务直接打开右侧栏页签;多个任务打开现有弹层。空闲、未归档且有活动关联任务的会话行保留时钟标记和悬浮列表。`schedule_create` 继续在轮次末尾渲染任务卡片,显示标题、重复描述和“打开”操作。持久化的旧工具结果与当前结果均可渲染;比卡片更新的权威读取同步后续修改或删除。 +目录首次读取成功后,如果会话是活动任务的固定投递目标,页头会显示时钟。只有一个任务时打开右侧栏页签,有多个任务时打开弹层。空闲且未归档的会话行有此类任务时显示时钟标记和悬浮列表。`schedule_create` 继续在轮次末尾渲染任务卡片,显示标题、重复描述和“打开”操作。持久化的旧工具结果与当前结果均可渲染;比卡片更新的权威读取同步后续修改或删除。 ### 时区数据来源 @@ -55,11 +57,13 @@ kind: "package-reference"
    实现内部细节 — 点击展开 +自动化详情内的分组标题、字段标签与提示共用内缩文字列。 + Peer 可读取 `schedule/catalog` 时,插件注册现有 `schedules` 主面板、会话页头功能位、轮次尾部卡片、会话行标记与悬浮内容,以及 `scheduleTask` 右侧栏页签。槽位注入提供框架读取器与操作回调;组件拥有选择、搜索和分页状态。入口声明的存储在根或会话作用域中按任务保留草稿和 CAS 基线,支持导航后恢复;主面板与会话页签的草稿相互独立。未修改的表单跟随目录更新。已修改的表单保留全部字段及原版本。目录出现新版本后,须放弃草稿,或由用户明确将改过的名称、内容、时间和目标字段组重新应用到该版本,才能保存。此操作不写入任务;用户复核结果后,以新版本作为 CAS 基线保存。未修改的字段组采用新记录的值。任务缺失时保留可编辑的本地草稿,宿主修改操作仍禁用。草稿不持久化;客户端重新加载,或所属入口、会话作用域销毁时,草稿随之释放。宿主拥有任务存储与执行。浏览目录不会激活会话。冲突反馈沿用目录提示样式;复核按钮采用描边样式,在窄面板中换到提示下方。 修改类型化日历时间时,通过共享重复规则求值器查找首个有效未来发生时点,并保留跨夏令时缺口的间隔对齐。成功编辑沿用 Schedule 的[当前格式写入路径](../../schedule/schedule/README.zh.md);仅修改内容时保留时间类型、精度、表达式及已提交发生时点。 -管理页、任务页签、行标记和会话页头投影共享一个可观察的 `schedule.catalog` 数据源。页头与会话行根据关联关系和执行目标筛选活动记录。修改使用基于任务 id 的 `schedule.create`、`schedule.edit` 和 `schedule.run`;历史使用任务标识和游标,不携带会话所有权参数。修改确认后发起新的权威读取;回读失败仍是目录错误,不将已经确认的写入改判为失败。 +管理页、任务页签、行标记和会话页头投影共享一个可观察的 `schedule.catalog` 数据源。页头与会话行按固定投递目标筛选活动记录。修改使用基于任务 id 的 `schedule.create`、`schedule.edit` 和 `schedule.run`;历史使用任务标识和游标,不携带会话所有权参数。修改确认后发起新的权威读取;回读失败仍是目录错误,不将已经确认的写入改判为失败。 侧栏布局记录不保存打开参数,因此 `TaskTabBindings` 按会话和页签 id 在 localStorage 中保存任务标识,不保存任务内容,并清理已关闭页签的关联。可观察目录仅在被读取时订阅,在 Schedule 变更或连接重置时刷新,最后一个订阅退出后使未完成读取失效。 @@ -74,7 +78,7 @@ Peer 可读取 `schedule/catalog` 时,插件注册现有 `schedules` 主面板 ## 模型体验 -无:本浏览器包不注册模型工具或自动消息;创建提示保留为未发送的草稿。 +无:本浏览器包不注册模型工具或自动消息;创建提示和推荐任务的请求都保留为未发送的草稿。 #### KV Cache 影响 diff --git a/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx new file mode 100644 index 0000000000..0c5ad0ebde --- /dev/null +++ b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx @@ -0,0 +1,154 @@ +/** + * Tile glyphs for recommended tasks: a 20px grid drawn 1:1 at 20px with 1.25px + * `currentColor` strokes, the shared icons' Regular weight (one unit on their + * 16-unit grid) at this size, with round caps and round joins. Each glyph marks + * its main shape with `data-fill`; the page stylesheet supplies that fill color. + */ +import type { ReactNode } from 'react' + +/** Props every tile glyph accepts. */ +export interface TileGlyphProps { + readonly className?: string | undefined +} + +function Glyph({ className, children }: TileGlyphProps & { readonly children: ReactNode }): ReactNode { + return ( + + ) +} + +/** + * Half sun over a horizon: a morning brief. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function SunriseGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + + ) +} + +/** + * Calendar page with a check: a week in review. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function CalendarCheckGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + ) +} + +/** + * Open-issue mark: a ring with a center dot. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function IssueGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + ) +} + +/** + * Puzzle piece with a check: plugins that still fit. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function PluginCheckGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + ) +} + +/** + * Newspaper page: an image block, short headlines and a body line. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function NewspaperGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + ) +} + +/** + * Branch: a trunk with a side branch joining it. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function BranchGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + ) +} + +/** + * Sun partly behind a cloud: weather. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function CloudSunGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + + + ) +} + +/** + * Dumbbell: a bar between two plates and two collars. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function DumbbellGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + ) +} diff --git a/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx new file mode 100644 index 0000000000..8f3accdd29 --- /dev/null +++ b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx @@ -0,0 +1,75 @@ +/** Built-in task recommendations under the empty task catalog; choosing one prefills a new Session. */ +import { useId, type ReactNode } from 'react' +import { Button, IconClockOutlineRegular, IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import type { TaskManagerKey } from './task-manager-locales.ts' +import { + BranchGlyph, CalendarCheckGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph, + SunriseGlyph, type TileGlyphProps, +} from './RecommendationArtwork.tsx' +import css from './TaskManagerPage.module.css' + +const RECOMMENDATIONS = [ + { id: 'dailyBrief', Glyph: SunriseGlyph }, + { id: 'weeklyReview', Glyph: CalendarCheckGlyph }, + { id: 'issueScan', Glyph: IssueGlyph }, + { id: 'pluginCompat', Glyph: PluginCheckGlyph }, + { id: 'topicTracking', Glyph: NewspaperGlyph }, + { id: 'branchCleanup', Glyph: BranchGlyph }, + { id: 'weather', Glyph: CloudSunGlyph }, + { id: 'workout', Glyph: DumbbellGlyph }, +] as const satisfies readonly { readonly id: string; readonly Glyph: (props: TileGlyphProps) => ReactNode }[] + +/** Props of the recommendation section. */ +export interface ScheduleRecommendationsProps { + /** Task-manager copy. */ + readonly t: (key: TaskManagerKey) => string + /** + * Start a new Session with a recommendation's request prefilled. + * @param prompt - the recommendation's localized request. + */ + readonly onUse: (prompt: string) => void +} + +/** + * Render the built-in recommendations as a two-column grid of tiles, each with + * its title, description, and default run time. + * @param props - copy and the prefill action. + * @returns the section listing every recommendation. + */ +export function ScheduleRecommendations({ t, onUse }: ScheduleRecommendationsProps): ReactNode { + const baseId = useId() + return ( +
    +

    {t('recommend.heading')}

    +
      + {RECOMMENDATIONS.map(({ id, Glyph }) => ( +
    • + +
    • + ))} +
    +
    + ) +} diff --git a/packages/client/ui-schedule/src/client/TaskManagerPage.module.css b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css index 6abf1a18f8..754b5e4620 100644 --- a/packages/client/ui-schedule/src/client/TaskManagerPage.module.css +++ b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css @@ -36,11 +36,15 @@ /* Matches the Plugins page's 960px column and responsive inline insets. */ .pageContent { - max-width: 960px; + max-width: calc(960px + 2 * clamp(24px, 4vw, 48px)); margin: 0 auto; /* Inline and bottom insets only: the 28px top inset belongs to the heading row, which starts at the window's top edge. */ padding: 0 clamp(24px, 4vw, 48px) 48px; + display: flex; + flex-direction: column; + box-sizing: border-box; + min-height: 100%; } @media (max-width: 767px) { @@ -91,14 +95,13 @@ white-space: nowrap; } -/* The Plugins toolbar's steps: New and the bulk cleanup share one 32px - capsule with a 13px label. */ +/* Header actions use the standard-control radius at their compact page height. */ .headerAction { height: 32px; font-size: 13px; line-height: 20px; padding: 0 12px; - border-radius: 16px; + border-radius: var(--dsw-radius-md); } /* The existing Plugins page's adjacent creation menu. */ @@ -108,7 +111,7 @@ height: 32px; width: 32px; padding: 0; - border-radius: 0 var(--dsw-radius-lg) var(--dsw-radius-lg) 0; + border-radius: 0 var(--dsw-radius-md) var(--dsw-radius-md) 0; border-left: 0.5px solid color-mix(in srgb, var(--dsw-alias-label-primary-foreground) 30%, transparent); } .createMenu [role='menuitem'] { gap: 10px; padding: 6px 12px; } @@ -157,9 +160,7 @@ gap: 8px 12px; } -/* The mock's `.tab`: the filter chip's 28px box, 10px sides, 14px radius, and - the mock's 14px label. The selected chip takes the mock's `--hover` fill at - the chip's own weight instead of the atom's bordered capsule. */ +/* Filter chips use the compact-control radius and retain a stable footprint. */ .filterTab { display: inline-flex; flex: none; @@ -167,7 +168,7 @@ height: 28px; padding: 0 10px; border: 0; - border-radius: 14px; + border-radius: var(--dsw-radius-sm); background: transparent; color: var(--dsw-alias-label-tertiary); font: inherit; @@ -220,7 +221,7 @@ margin: 0; padding: 0 10px; border: 0.5px solid var(--dsw-alias-border-l3); - border-radius: 12px; + border-radius: var(--dsw-radius-md); color: var(--dsw-alias-label-tertiary); transition: border-color 0.15s; } @@ -257,7 +258,7 @@ } .searchField input::placeholder { - color: var(--dsw-alias-label-caption); + color: var(--dsw-alias-label-tertiary); } .searchField input:focus-visible { @@ -288,7 +289,9 @@ /* The mock's `#rule-list`: the catalog notices and the rows share one column with no box of their own. */ .list { - display: block; + display: flex; + flex-direction: column; + flex: 1 0 auto; } /* The Plugins page's `.cards` column: 2px between rows. */ @@ -311,7 +314,7 @@ width: 100%; height: auto; padding: 8px; - border-radius: 12px; + border-radius: var(--dsw-radius-lg); text-align: left; white-space: normal; } @@ -417,7 +420,7 @@ gap: 9px; margin: 0 0 20px; padding: 12px 14px; - border-radius: 10px; + border-radius: var(--dsw-radius-lg); background: var(--dsw-specific-sidebar-fill); color: var(--dsw-alias-label-secondary); font-size: 12px; @@ -786,7 +789,7 @@ .retentionRule { margin-top: 12px; padding: 12px 14px; - border-radius: 8px; + border-radius: var(--dsw-radius-lg); background: var(--dsw-alias-bg-layer-1); } @@ -804,7 +807,7 @@ min-width: 0; padding: 0 12px; border: 0.5px solid var(--dsw-alias-border-l3); - border-radius: 16px; + border-radius: var(--dsw-radius-lg); } /* The searchable zone inventory is intentionally shorter than a general menu: @@ -889,7 +892,7 @@ min-width: 0; min-height: 32px; padding: 0 8px; - border-radius: 18px; + border-radius: var(--dsw-radius-md); transition: background 0.15s; } @@ -936,7 +939,7 @@ width: 100%; padding: 6px 8px; border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: 7px; + border-radius: var(--dsw-radius-md); outline: none; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); @@ -963,7 +966,7 @@ padding: 5px 8px; margin-right: 0; border: none; - border-radius: 18px; + border-radius: var(--dsw-radius-md); background: transparent; color: var(--dsw-alias-label-primary); font: inherit; @@ -992,7 +995,7 @@ justify-content: center; min-width: 72px; height: 36px; - border-radius: 18px; + border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-module-platform); } @@ -1118,7 +1121,7 @@ margin: 0; padding: 12px; border: 0.5px solid var(--dsw-alias-border-l3); - border-radius: 16px; + border-radius: var(--dsw-radius-lg); outline: 0; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); @@ -1156,7 +1159,7 @@ gap: 12px; margin: 0 -8px; padding: 14px 8px; - border-radius: 8px; + border-radius: var(--dsw-radius-lg); font-size: 14px; line-height: 22px; } @@ -1365,8 +1368,18 @@ --dsh-button-outline-color: var(--dsw-alias-state-error-primary); } +/* The instruction only identifies the task here, so a long one stays a + three-line excerpt instead of growing the dialog. */ .confirmPrompt { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + line-clamp: 3; margin: 0; + overflow: hidden; + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 22px; white-space: pre-wrap; overflow-wrap: anywhere; } @@ -1441,3 +1454,143 @@ font-size: 16px; } } + +/* Recommended tasks under the empty Enabled and All views: a two-column grid, + one column below 600px of content width. The heading starts on the tiles' + 12px inset. */ +.recommendations { + container-type: inline-size; + margin-top: 8px; +} + +.recommendationsHeading { + margin: 0 0 6px; + padding: 0 12px; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + line-height: 20px; + font-weight: 500; +} + +.recommendationGrid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 4px 16px; + margin: 0; + padding: 0; + list-style: none; +} + +@container (max-width: 600px) { + .recommendationGrid { + grid-template-columns: minmax(0, 1fr); + } +} + +.recommendation { + display: flex; + align-items: flex-start; + justify-content: flex-start; + gap: 14px; + width: 100%; + height: auto; + padding: 12px; + border-radius: var(--dsw-radius-lg); + text-align: left; + white-space: normal; +} + +/* Tiles take the empty illustration's background. Glyphs draw in the blue + accent, and each glyph's main shape takes a 16% tint of that blue, which + stays visible against the tile in both themes. */ +.tile { + display: flex; + flex: none; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; + border-radius: var(--dsw-radius-md); + background: var(--dsw-alias-illustration-background); + color: var(--dsw-alias-state-business-primary); +} + +.tile [data-fill] { + fill: currentColor; + fill-opacity: 0.16; +} + +.tileGlyph { + flex: none; + width: 20px; + height: 20px; +} + +.tilePlus { + display: none; + flex: none; +} + +.recommendation:focus-visible .tileGlyph { + display: none; +} + +.recommendation:focus-visible .tilePlus { + display: block; +} + +@media (hover: hover) { + .recommendation:hover .tileGlyph { + display: none; + } + + .recommendation:hover .tilePlus { + display: block; + } +} + +.recommendationContent, +.recommendationDetails { + display: flex; + flex-direction: column; + min-width: 0; +} + +.recommendationContent { + flex: 1; +} + +.recommendationTitle { + font-weight: 500; + line-height: 22px; +} + +.recommendationDescription { + margin-top: 2px; + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 20px; +} + +.recommendationWhen { + display: flex; + align-items: center; + gap: 6px; + margin-top: 6px; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + line-height: 20px; +} + +.whenGlyph { + flex: none; + width: 14px; + height: 14px; +} + +.list:not(:has(.recommendations)) > .empty { + flex: 1; + justify-content: center; + min-height: 280px; + box-sizing: border-box; +} diff --git a/packages/client/ui-schedule/src/client/TaskManagerPage.tsx b/packages/client/ui-schedule/src/client/TaskManagerPage.tsx index a9a301f1bb..5ca57d5933 100644 --- a/packages/client/ui-schedule/src/client/TaskManagerPage.tsx +++ b/packages/client/ui-schedule/src/client/TaskManagerPage.tsx @@ -20,6 +20,7 @@ import { useRelativeClock } from './relative-clock.ts' import { formatScheduleFrequency, nextRunParts, taskName, zoneLabel } from './schedule-format.ts' import type { FrequencyZone } from './schedule-format.ts' import { ScheduleEmptyIllustration } from './ScheduleEmptyIllustration.tsx' +import { ScheduleRecommendations } from './ScheduleRecommendations.tsx' import css from './TaskManagerPage.module.css' /** Injected catalog and task actions for the management page. */ @@ -31,6 +32,12 @@ export interface TaskManagerInjected extends TaskDetailInjected { * schedule it, using the existing new-conversation action. */ readonly onNewTask: () => void + /** + * Start a new Session with a recommended task's request prefilled, through + * the same new-conversation action as `onNewTask`. + * @param prompt - the recommendation's localized request. + */ + readonly onUseRecommendation: (prompt: string) => void /** * Remove every ended Host task, after this page has confirmed the action. * @@ -59,7 +66,7 @@ type StatusFilter = 'all' | ScheduleCatalogEntry['status'] * @returns the searchable task list beside the selected task's detail. */ export function TaskManagerPage(props: TaskManagerPageProps) { - const { useCatalog, onNewTask, onClearEnded, onRetry, onCreateTask, t } = props + const { useCatalog, onNewTask, onUseRecommendation, onClearEnded, onRetry, onCreateTask, t } = props const [createMenuOpen, setCreateMenuOpen] = useState(false) const [manualOpen, setManualOpen] = useState(false) const catalog = useCatalog(snapshot => snapshot) @@ -101,6 +108,8 @@ export function TaskManagerPage(props: TaskManagerPageProps) { ), [records, statusFilter]) const rows = useMemo(() => rowIndex.search(search), [rowIndex, search]) + const showRecommendations = status === 'ready' && rows.length === 0 && search.trim() === '' + && (statusFilter === 'active' || statusFilter === 'all') const emptyTitle = search.trim() !== '' ? 'list.noMatches' : statusFilter === 'paused' ? 'list.emptyPaused' : statusFilter === 'ended' ? 'list.emptyInactive' @@ -285,6 +294,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) { {t('empty.action')} } + {showRecommendations && }
      {rows.map((record) => { // One pair per row: the same absolute stamp and distance reach diff --git a/packages/client/ui-schedule/src/client/index.ts b/packages/client/ui-schedule/src/client/index.ts index 5df353095f..8a6e92ee1c 100644 --- a/packages/client/ui-schedule/src/client/index.ts +++ b/packages/client/ui-schedule/src/client/index.ts @@ -215,6 +215,11 @@ export function apply(ctx: ClientContext): void { locale: MANAGER_NS, inject: (): ScheduleTaskCatalogInjected & ScheduleTaskBindingInjected => ({ hooks: detail.hooks, taskBindings }), }, ScheduleTaskTabTitle)) + // New and every recommendation open a new conversation with a request in its + // composer, appended to the draft of a reused blank conversation. + const startWithPrompt = (prompt: string): void => { + ctx.uiWorkspace.startSession(undefined, { prompt, whenDraftExists: 'append' }) + } yield ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID, @@ -222,7 +227,8 @@ export function apply(ctx: ClientContext): void { store: createEditorStore(), inject: (): TaskManagerInjected => ({ ...detail, - onNewTask: () => { ctx.uiWorkspace.startSession(undefined, { prompt: t('host.createPrompt'), whenDraftExists: 'append' }) }, + onNewTask: () => { startWithPrompt(t('host.createPrompt')) }, + onUseRecommendation: startWithPrompt, onClearEnded: async () => { const outcome = await clearEnded() deleteToast.reportClear(outcome) diff --git a/packages/client/ui-schedule/src/client/recent-time-zones.ts b/packages/client/ui-schedule/src/client/recent-time-zones.ts index ae7474f48b..409ab1e40b 100644 --- a/packages/client/ui-schedule/src/client/recent-time-zones.ts +++ b/packages/client/ui-schedule/src/client/recent-time-zones.ts @@ -38,7 +38,7 @@ export function rememberTimeZone(recent: readonly string[], zone: string): reado if (typeof localStorage !== 'undefined') { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)) - } catch { + } catch (_storageUnavailable) { // A private or full browser store must not block editing the rule. } } diff --git a/packages/client/ui-schedule/src/client/recommendation-locales.ts b/packages/client/ui-schedule/src/client/recommendation-locales.ts new file mode 100644 index 0000000000..c7c685dac7 --- /dev/null +++ b/packages/client/ui-schedule/src/client/recommendation-locales.ts @@ -0,0 +1,297 @@ +/** Copy for the recommended tasks shown in the empty task catalog. */ + +/** English recommendation copy. */ +export const recommendationEn = { + 'recommend.heading': 'Recommended', + 'recommend.dailyBrief.title': 'Daily brief', + 'recommend.dailyBrief.description': 'Recent changes in the workspace and what needs follow-up, with what to do first today.', + 'recommend.dailyBrief.schedule': 'Weekdays at 9:00', + 'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.', + 'recommend.weeklyReview.title': 'Weekly review', + 'recommend.weeklyReview.description': 'Your work in the workspace this week, with loose ends and what to do first next week.', + 'recommend.weeklyReview.schedule': 'Fridays at 16:00', + 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review what I did in the current workspace this week and list what is still unfinished and what to do first next week; when the workspace is a code repository, look only at my commits this week and the pull requests I opened that were merged this week or are still open. Summarize here only; do not change files in the workspace.', + 'recommend.issueScan.title': 'Issue scan', + 'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.', + 'recommend.issueScan.schedule': 'Weekdays at 10:00', + 'recommend.issueScan.prompt': 'Create an automation task named "Issue scan": every weekday at 10:00, scan new issues in the current workspace repository, sort them into bugs, requests, and questions, and flag duplicates and ones that need my reply. Summarize here only; do not reply on GitHub.', + 'recommend.pluginCompat.title': 'Plugin compatibility check', + 'recommend.pluginCompat.description': 'When a new DSH version ships, check whether installed and self-made plugins need changes.', + 'recommend.pluginCompat.schedule': 'Daily at 10:00', + 'recommend.pluginCompat.prompt': 'Create an automation task named "Plugin compatibility check": every day at 10:00, check whether a new DSH version is available; if so, read its upgrade guide, check whether each non-official or self-made plugin I have installed is affected, and list what to change and how.', + 'recommend.topicTracking.title': 'Topic and paper tracking', + 'recommend.topicTracking.description': 'Search for news and new arXiv papers on chosen topics and list the key points.', + 'recommend.topicTracking.schedule': 'Daily at 9:00', + 'recommend.topicTracking.prompt': 'Create an automation task named "Topic and paper tracking": every day at 9:00, search for new articles and arXiv papers on the topics I follow and list a few key points for each. Before creating it, ask me for the topics, keywords, and sources.', + 'recommend.branchCleanup.title': 'Branch and worktree cleanup', + 'recommend.branchCleanup.description': 'List local branches and worktrees whose pull requests merged or closed, and delete them after confirmation.', + 'recommend.branchCleanup.schedule': 'Fridays at 17:00', + 'recommend.branchCleanup.prompt': 'Create an automation task named "Branch and worktree cleanup": every Friday at 17:00, list local branches and worktrees in the current workspace whose pull requests are merged or closed, and delete them only after I confirm.', + 'recommend.weather.title': 'Weather and travel', + 'recommend.weather.description': 'Weather for today and the next three days, with a note when an umbrella or warmer clothes are needed.', + 'recommend.weather.schedule': 'Daily at 7:30', + 'recommend.weather.prompt': 'Create an automation task named "Weather and travel": every day at 7:30, tell me the weather in my city for today and the next three days, and call out when I should bring an umbrella, dress warmer, or expect travel disruption. Before creating it, ask me for my city.', + 'recommend.workout.title': 'Weekly workout plan', + 'recommend.workout.description': 'Plan next week\'s workouts around your goals and training days.', + 'recommend.workout.schedule': 'Sundays at 20:00', + 'recommend.workout.prompt': 'Create an automation task named "Weekly workout plan": every Sunday at 20:00, plan my workouts for next week around my goals and the days I can train, without asking me anything when it runs. Before creating it, ask me about my goals, how many days a week I can train, which days I am free, and where I train.', +} as const + +/** Simplified Chinese recommendation copy. */ +export const recommendationZh: Record = { + 'recommend.heading': '推荐', + 'recommend.dailyBrief.title': '每日简报', + 'recommend.dailyBrief.description': '汇总工作区最近的变化和待跟进的事,列出今天先做什么。', + 'recommend.dailyBrief.schedule': '工作日 9:00', + 'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。', + 'recommend.weeklyReview.title': '每周回顾', + 'recommend.weeklyReview.description': '回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。', + 'recommend.weeklyReview.schedule': '周五 16:00', + 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾我这一周在当前工作区做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,只看我这周的提交,以及我提的、这周合入或还开着的 PR。只在这里汇总,不改工作区里的文件。', + 'recommend.issueScan.title': 'Issue 扫描', + 'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。', + 'recommend.issueScan.schedule': '工作日 10:00', + 'recommend.issueScan.prompt': '创建一个名为「Issue 扫描」的自动化任务:每个工作日 10:00 扫描当前工作区仓库新开的 issue,分成 bug、需求、提问,标出重复的和需要我回复的,只在这里汇总,不在 GitHub 上回复。', + 'recommend.pluginCompat.title': '插件兼容检查', + 'recommend.pluginCompat.description': 'DSH 出新版本时,检查已装的插件和自己做的插件要不要改。', + 'recommend.pluginCompat.schedule': '每天 10:00', + 'recommend.pluginCompat.prompt': '创建一个名为「插件兼容检查」的自动化任务:每天 10:00 检查 DSH 有没有新版本;有的话读这个版本的升级指引,逐个检查我装的非官方插件和自己做的插件会不会受影响,列出要改的地方和改法。', + 'recommend.topicTracking.title': '主题和论文追踪', + 'recommend.topicTracking.description': '搜索关注主题的新消息和 arXiv 新论文,各列几条要点。', + 'recommend.topicTracking.schedule': '每天 9:00', + 'recommend.topicTracking.prompt': '创建一个名为「主题和论文追踪」的自动化任务:每天 9:00 搜索我关注主题的新消息和 arXiv 新论文,各列几条要点。创建前先问我主题、关键词和来源。', + 'recommend.branchCleanup.title': '分支和 worktree 清理', + 'recommend.branchCleanup.description': '列出 PR 已合并或关闭的本地分支和 worktree,确认后再删。', + 'recommend.branchCleanup.schedule': '周五 17:00', + 'recommend.branchCleanup.prompt': '创建一个名为「分支和 worktree 清理」的自动化任务:每周五 17:00 列出当前工作区里 PR 已合并或关闭的本地分支和 worktree,我确认后再删。', + 'recommend.weather.title': '天气和出行', + 'recommend.weather.description': '今天和接下来三天的天气,要带伞或加衣时提一句。', + 'recommend.weather.schedule': '每天 7:30', + 'recommend.weather.prompt': '创建一个名为「天气和出行」的自动化任务:每天 7:30 告诉我所在城市今天和接下来三天的天气,要带伞、加衣或出行受影响时单独提一句。创建前先问我城市。', + 'recommend.workout.title': '一周运动计划', + 'recommend.workout.description': '按目标和每周能练的日子排好下周的运动计划。', + 'recommend.workout.schedule': '周日 20:00', + 'recommend.workout.prompt': '创建一个名为「一周运动计划」的自动化任务:每周日 20:00 按我的目标和每周能练的日子排好下周的运动计划,运行时不再问我。创建前先问我目标、每周能练几天、哪几天有空、在哪练。', +} + +/** Japanese recommendation copy. */ +export const recommendationJa: Record = { + 'recommend.heading': 'おすすめ', + 'recommend.dailyBrief.title': 'デイリーブリーフィング', + 'recommend.dailyBrief.description': 'ワークスペースの最近の変化とフォローが必要なことをまとめ、今日最初にやることを挙げます。', + 'recommend.dailyBrief.schedule': '平日 9:00', + 'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。', + 'recommend.weeklyReview.title': '週次レビュー', + 'recommend.weeklyReview.description': '今週ワークスペースで自分がしたことを振り返り、やり残したことと来週最初にやることを挙げます。', + 'recommend.weeklyReview.schedule': '毎週金曜日 16:00', + 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、今週私が現在のワークスペースでしたことを振り返り、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週の私のコミットと、私が作成したプルリクエストのうち今週マージされたものとまだオープンのものだけを確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', + 'recommend.issueScan.title': 'Issue スキャン', + 'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。', + 'recommend.issueScan.schedule': '平日 10:00', + 'recommend.issueScan.prompt': '「Issue スキャン」という名前の自動化タスクを作成してください。平日は毎日 10:00 に、現在のワークスペースのリポジトリで新しい Issue をスキャンし、バグ・要望・質問に分類して、重複しているものと私の返信が必要なものを指摘してください。まとめはここでだけ行い、GitHub では返信しないでください。', + 'recommend.pluginCompat.title': 'プラグイン互換性チェック', + 'recommend.pluginCompat.description': 'DSH の新しいバージョンが出たら、インストール済みのプラグインや自作のプラグインに変更が必要か確認します。', + 'recommend.pluginCompat.schedule': '毎日 10:00', + 'recommend.pluginCompat.prompt': '「プラグイン互換性チェック」という名前の自動化タスクを作成してください。毎日 10:00 に DSH の新しいバージョンが出ているか確認し、出ていればそのアップグレードガイドを読んで、私がインストールした非公式プラグインや自作プラグインが影響を受けるかを一つずつ調べ、変更が必要な箇所と変更方法を挙げてください。', + 'recommend.topicTracking.title': 'トピックと論文の追跡', + 'recommend.topicTracking.description': '選んだトピックのニュースと arXiv の新しい論文を検索し、要点を挙げます。', + 'recommend.topicTracking.schedule': '毎日 9:00', + 'recommend.topicTracking.prompt': '「トピックと論文の追跡」という名前の自動化タスクを作成してください。毎日 9:00 に、私がフォローしているトピックについて新しい記事と arXiv の新しい論文を検索し、それぞれ要点をいくつか挙げてください。作成する前に、トピック、キーワード、情報源を私に聞いてください。', + 'recommend.branchCleanup.title': 'ブランチと worktree の整理', + 'recommend.branchCleanup.description': 'プルリクエストがマージまたはクローズされたローカルブランチと worktree を一覧にし、確認後に削除します。', + 'recommend.branchCleanup.schedule': '毎週金曜日 17:00', + 'recommend.branchCleanup.prompt': '「ブランチと worktree の整理」という名前の自動化タスクを作成してください。毎週金曜日の 17:00 に、現在のワークスペースで、プルリクエストがマージ済みまたはクローズ済みのローカルブランチと worktree を一覧にし、削除は私が確認してから行ってください。', + 'recommend.weather.title': '天気とお出かけ', + 'recommend.weather.description': '今日と今後3日間の天気を伝え、傘や暖かい服装が必要なときはひと言添えます。', + 'recommend.weather.schedule': '毎日 7:30', + 'recommend.weather.prompt': '「天気とお出かけ」という名前の自動化タスクを作成してください。毎日 7:30 に、私のいる都市の今日と今後3日間の天気を教えてください。傘を持っていくべきとき、暖かい服装にすべきとき、交通の乱れが予想されるときは、そのことをひと言添えてください。作成する前に、私のいる都市を聞いてください。', + 'recommend.workout.title': '1週間の運動プラン', + 'recommend.workout.description': '目標と運動できる曜日に合わせて、翌週の運動プランを立てます。', + 'recommend.workout.schedule': '毎週日曜日 20:00', + 'recommend.workout.prompt': '「1週間の運動プラン」という名前の自動化タスクを作成してください。毎週日曜日の 20:00 に、私の目標と運動できる曜日に合わせて翌週の運動プランを立ててください。実行時には私に質問しないでください。作成する前に、目標、週に何日運動できるか、何曜日が空いているか、どこで運動するかを私に聞いてください。', +} + +/** Spanish recommendation copy. */ +export const recommendationEs: Record = { + 'recommend.heading': 'Recomendadas', + 'recommend.dailyBrief.title': 'Resumen diario', + 'recommend.dailyBrief.description': 'Cambios recientes en el espacio de trabajo y pendientes de seguimiento, con lo primero que hacer hoy.', + 'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00', + 'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.', + 'recommend.weeklyReview.title': 'Revisión semanal', + 'recommend.weeklyReview.description': 'Tu trabajo de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', + 'recommend.weeklyReview.schedule': 'Los viernes a las 16:00', + 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa lo que hice esta semana en el espacio de trabajo actual y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, revisa solo mis commits de esta semana y los pull requests que abrí que se fusionaron esta semana o siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', + 'recommend.issueScan.title': 'Revisión de issues', + 'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.', + 'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00', + 'recommend.issueScan.prompt': 'Crea una tarea de automatización llamada «Revisión de issues»: de lunes a viernes a las 10:00, revisa los issues nuevos del repositorio del espacio de trabajo actual, clasifícalos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan mi respuesta. Haz el resumen solo aquí; no respondas en GitHub.', + 'recommend.pluginCompat.title': 'Compatibilidad de complementos', + 'recommend.pluginCompat.description': 'Cuando sale una nueva versión de DSH, comprueba si los complementos instalados y los que has creado necesitan cambios.', + 'recommend.pluginCompat.schedule': 'Diariamente a las 10:00', + 'recommend.pluginCompat.prompt': 'Crea una tarea de automatización llamada «Compatibilidad de complementos»: todos los días a las 10:00, comprueba si hay una nueva versión de DSH; si la hay, lee su guía de actualización, revisa uno por uno si los complementos no oficiales o creados por mí que tengo instalados se ven afectados, y enumera qué hay que cambiar y cómo.', + 'recommend.topicTracking.title': 'Seguimiento de temas y artículos', + 'recommend.topicTracking.description': 'Busca noticias y artículos nuevos de arXiv sobre los temas elegidos y enumera los puntos clave.', + 'recommend.topicTracking.schedule': 'Diariamente a las 9:00', + 'recommend.topicTracking.prompt': 'Crea una tarea de automatización llamada «Seguimiento de temas y artículos»: todos los días a las 9:00, busca noticias y artículos nuevos de arXiv sobre los temas que sigo y enumera algunos puntos clave de cada uno. Antes de crearla, pregúntame por los temas, las palabras clave y las fuentes.', + 'recommend.branchCleanup.title': 'Limpieza de ramas y worktrees', + 'recommend.branchCleanup.description': 'Enumera las ramas locales y los worktrees cuyos pull requests se fusionaron o cerraron, y los elimina previa confirmación.', + 'recommend.branchCleanup.schedule': 'Los viernes a las 17:00', + 'recommend.branchCleanup.prompt': 'Crea una tarea de automatización llamada «Limpieza de ramas y worktrees»: todos los viernes a las 17:00, enumera las ramas locales y los worktrees del espacio de trabajo actual cuyos pull requests están fusionados o cerrados, y elimínalos solo después de que yo lo confirme.', + 'recommend.weather.title': 'Clima y desplazamientos', + 'recommend.weather.description': 'El clima de hoy y de los próximos tres días, con un aviso cuando haga falta paraguas o más abrigo.', + 'recommend.weather.schedule': 'Diariamente a las 7:30', + 'recommend.weather.prompt': 'Crea una tarea de automatización llamada «Clima y desplazamientos»: todos los días a las 7:30, dime el clima de mi ciudad para hoy y los próximos tres días, y avísame cuando deba llevar paraguas, abrigarme más o esperar problemas en los desplazamientos. Antes de crearla, pregúntame cuál es mi ciudad.', + 'recommend.workout.title': 'Plan de entrenamiento semanal', + 'recommend.workout.description': 'Planifica los entrenamientos de la próxima semana según tus objetivos y tus días de entrenamiento.', + 'recommend.workout.schedule': 'Los domingos a las 20:00', + 'recommend.workout.prompt': 'Crea una tarea de automatización llamada «Plan de entrenamiento semanal»: todos los domingos a las 20:00, planifica mis entrenamientos de la próxima semana según mis objetivos y los días en que puedo entrenar, sin preguntarme nada cuando se ejecute. Antes de crearla, pregúntame por mis objetivos, cuántos días a la semana puedo entrenar, qué días tengo libres y dónde entreno.', +} + +/** French recommendation copy. */ +export const recommendationFr: Record = { + 'recommend.heading': 'Recommandées', + 'recommend.dailyBrief.title': 'Résumé quotidien', + 'recommend.dailyBrief.description': 'Changements récents dans l\'espace de travail et points à suivre, avec les priorités du jour.', + 'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00', + 'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.', + 'recommend.weeklyReview.title': 'Bilan hebdomadaire', + 'recommend.weeklyReview.description': 'Votre travail de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', + 'recommend.weeklyReview.schedule': 'Le vendredi à 16:00', + 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue ce que j\'ai fait cette semaine dans l\'espace de travail actuel et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, ne regarde que mes commits de la semaine et les pull requests que j\'ai ouvertes qui ont été fusionnées cette semaine ou sont encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', + 'recommend.issueScan.title': 'Analyse des issues', + 'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.', + 'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00', + 'recommend.issueScan.prompt': 'Crée une tâche d\'automatisation nommée « Analyse des issues » : du lundi au vendredi à 10:00, analyse les nouvelles issues du dépôt de l\'espace de travail actuel, trie-les en bugs, demandes et questions, et signale les doublons et celles qui nécessitent ma réponse. Fais le résumé ici uniquement ; ne réponds pas sur GitHub.', + 'recommend.pluginCompat.title': 'Compatibilité des plugins', + 'recommend.pluginCompat.description': 'Quand une nouvelle version de DSH sort, vérifie si les plugins installés et ceux faits maison doivent être modifiés.', + 'recommend.pluginCompat.schedule': 'Tous les jours à 10:00', + 'recommend.pluginCompat.prompt': 'Crée une tâche d\'automatisation nommée « Compatibilité des plugins » : tous les jours à 10:00, vérifie si une nouvelle version de DSH est disponible ; si oui, lis son guide de mise à niveau, examine pour chaque plugin non officiel ou fait maison que j\'ai installé s\'il est concerné, et liste ce qu\'il faut modifier et comment.', + 'recommend.topicTracking.title': 'Suivi de sujets et d\'articles', + 'recommend.topicTracking.description': 'Recherche les actualités et les nouveaux articles arXiv sur les sujets choisis, et liste les points clés.', + 'recommend.topicTracking.schedule': 'Tous les jours à 9:00', + 'recommend.topicTracking.prompt': 'Crée une tâche d\'automatisation nommée « Suivi de sujets et d\'articles » : tous les jours à 9:00, recherche les actualités et les nouveaux articles arXiv sur les sujets que je suis, et liste quelques points clés pour chacun. Avant de la créer, demande-moi les sujets, les mots-clés et les sources.', + 'recommend.branchCleanup.title': 'Nettoyage des branches et worktrees', + 'recommend.branchCleanup.description': 'Liste les branches et worktrees locaux dont les pull requests sont fusionnées ou fermées, et les supprime après confirmation.', + 'recommend.branchCleanup.schedule': 'Le vendredi à 17:00', + 'recommend.branchCleanup.prompt': 'Crée une tâche d\'automatisation nommée « Nettoyage des branches et worktrees » : tous les vendredis à 17:00, liste les branches locales et les worktrees de l\'espace de travail actuel dont les pull requests sont fusionnées ou fermées, et ne les supprime qu\'après ma confirmation.', + 'recommend.weather.title': 'Météo et déplacements', + 'recommend.weather.description': 'Météo du jour et des trois prochains jours, avec un rappel s\'il faut un parapluie ou des vêtements plus chauds.', + 'recommend.weather.schedule': 'Tous les jours à 7:30', + 'recommend.weather.prompt': 'Crée une tâche d\'automatisation nommée « Météo et déplacements » : tous les jours à 7:30, donne-moi la météo de ma ville pour aujourd\'hui et les trois prochains jours, et préviens-moi quand je dois prendre un parapluie, me couvrir davantage ou m\'attendre à des perturbations dans les transports. Avant de la créer, demande-moi ma ville.', + 'recommend.workout.title': 'Plan d\'entraînement hebdomadaire', + 'recommend.workout.description': 'Planifie les entraînements de la semaine prochaine selon tes objectifs et tes jours d\'entraînement.', + 'recommend.workout.schedule': 'Le dimanche à 20:00', + 'recommend.workout.prompt': 'Crée une tâche d\'automatisation nommée « Plan d\'entraînement hebdomadaire » : tous les dimanches à 20:00, planifie mes entraînements de la semaine suivante en fonction de mes objectifs et des jours où je peux m\'entraîner, sans me poser de question pendant l\'exécution. Avant de la créer, demande-moi mes objectifs, combien de jours par semaine je peux m\'entraîner, quels jours je suis libre et où je m\'entraîne.', +} + +/** German recommendation copy. */ +export const recommendationDe: Record = { + 'recommend.heading': 'Empfohlen', + 'recommend.dailyBrief.title': 'Tagesüberblick', + 'recommend.dailyBrief.description': 'Aktuelle Änderungen im Arbeitsbereich und offene Punkte, dazu, was heute zuerst ansteht.', + 'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00', + 'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.', + 'recommend.weeklyReview.title': 'Wochenrückblick', + 'recommend.weeklyReview.description': 'Die eigene Arbeit dieser Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', + 'recommend.weeklyReview.schedule': 'Freitags um 16:00', + 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr darauf zurück, was ich diese Woche im aktuellen Arbeitsbereich gemacht habe, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige nur meine Commits dieser Woche und die von mir eröffneten Pull Requests, die diese Woche gemergt wurden oder noch offen sind. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', + 'recommend.issueScan.title': 'Issue-Sichtung', + 'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.', + 'recommend.issueScan.schedule': 'Mo–Fr um 10:00', + 'recommend.issueScan.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Issue-Sichtung“: Sichte montags bis freitags um 10:00 Uhr die neuen Issues im Repository des aktuellen Arbeitsbereichs, sortiere sie in Bugs, Feature-Wünsche und Fragen und hebe Duplikate sowie Issues hervor, die meine Antwort brauchen. Fasse alles nur hier zusammen; antworte nicht auf GitHub.', + 'recommend.pluginCompat.title': 'Plugin-Kompatibilitätsprüfung', + 'recommend.pluginCompat.description': 'Prüft, sobald eine neue DSH-Version erscheint, ob installierte und selbst erstellte Plugins angepasst werden müssen.', + 'recommend.pluginCompat.schedule': 'Täglich um 10:00', + 'recommend.pluginCompat.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Plugin-Kompatibilitätsprüfung“: Prüfe täglich um 10:00 Uhr, ob eine neue DSH-Version verfügbar ist; falls ja, lies die zugehörige Upgrade-Anleitung, prüfe für jedes nicht offizielle oder selbst erstellte Plugin, das ich installiert habe, ob es betroffen ist, und liste auf, was zu ändern ist und wie.', + 'recommend.topicTracking.title': 'Themen- und Paper-Tracking', + 'recommend.topicTracking.description': 'Sucht Neuigkeiten und neue arXiv-Paper zu ausgewählten Themen und listet die wichtigsten Punkte auf.', + 'recommend.topicTracking.schedule': 'Täglich um 9:00', + 'recommend.topicTracking.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Themen- und Paper-Tracking“: Suche täglich um 9:00 Uhr neue Artikel und arXiv-Paper zu den Themen, die ich verfolge, und liste zu jedem ein paar Kernpunkte auf. Frag mich vor dem Erstellen nach den Themen, Stichwörtern und Quellen.', + 'recommend.branchCleanup.title': 'Branch- und Worktree-Bereinigung', + 'recommend.branchCleanup.description': 'Listet lokale Branches und Worktrees mit gemergten oder geschlossenen Pull Requests auf und löscht sie nach Bestätigung.', + 'recommend.branchCleanup.schedule': 'Freitags um 17:00', + 'recommend.branchCleanup.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Branch- und Worktree-Bereinigung“: Liste freitags um 17:00 Uhr die lokalen Branches und Worktrees im aktuellen Arbeitsbereich auf, deren Pull Requests gemergt oder geschlossen sind, und lösche sie erst, nachdem ich es bestätigt habe.', + 'recommend.weather.title': 'Wetter und Verkehr', + 'recommend.weather.description': 'Das Wetter für heute und die nächsten drei Tage, mit Hinweis, wenn ein Schirm oder wärmere Kleidung nötig ist.', + 'recommend.weather.schedule': 'Täglich um 7:30', + 'recommend.weather.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wetter und Verkehr“: Sag mir täglich um 7:30 Uhr das Wetter in meiner Stadt für heute und die nächsten drei Tage und weise mich darauf hin, wenn ich einen Schirm mitnehmen, mich wärmer anziehen oder mit Verkehrsbehinderungen rechnen sollte. Frag mich vor dem Erstellen nach meiner Stadt.', + 'recommend.workout.title': 'Wöchentlicher Trainingsplan', + 'recommend.workout.description': 'Plant die Trainingseinheiten der nächsten Woche passend zu deinen Zielen und Trainingstagen.', + 'recommend.workout.schedule': 'Sonntags um 20:00', + 'recommend.workout.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wöchentlicher Trainingsplan“: Plane sonntags um 20:00 Uhr meine Trainingseinheiten für die nächste Woche passend zu meinen Zielen und den Tagen, an denen ich trainieren kann, ohne mich bei der Ausführung etwas zu fragen. Frag mich vor dem Erstellen nach meinen Zielen, wie viele Tage pro Woche ich trainieren kann, an welchen Tagen ich frei bin und wo ich trainiere.', +} + +/** Russian recommendation copy. */ +export const recommendationRu: Record = { + 'recommend.heading': 'Рекомендуемые', + 'recommend.dailyBrief.title': 'Ежедневная сводка', + 'recommend.dailyBrief.description': 'Недавние изменения в рабочей области и то, что требует внимания, а также первоочередные дела на сегодня.', + 'recommend.dailyBrief.schedule': 'По будням в 9:00', + 'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.', + 'recommend.weeklyReview.title': 'Еженедельный обзор', + 'recommend.weeklyReview.description': 'Ваша работа за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', + 'recommend.weeklyReview.schedule': 'По пятницам в 16:00', + 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай мою работу за эту неделю в текущем рабочем пространстве и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай только мои коммиты за неделю и мои пул-реквесты, слитые на этой неделе или ещё открытые. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', + 'recommend.issueScan.title': 'Обзор issues', + 'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.', + 'recommend.issueScan.schedule': 'По будням в 10:00', + 'recommend.issueScan.prompt': 'Создай задачу автоматизации под названием «Обзор issues»: по будням в 10:00 просматривай новые issues в репозитории текущего рабочего пространства, дели их на баги, пожелания и вопросы и выделяй дубликаты и те, на которые нужен мой ответ. Сводку пиши только здесь; на GitHub не отвечай.', + 'recommend.pluginCompat.title': 'Проверка совместимости плагинов', + 'recommend.pluginCompat.description': 'При выходе новой версии DSH проверяет, нужно ли изменить установленные и созданные вами плагины.', + 'recommend.pluginCompat.schedule': 'Ежедневно в 10:00', + 'recommend.pluginCompat.prompt': 'Создай задачу автоматизации под названием «Проверка совместимости плагинов»: ежедневно в 10:00 проверяй, вышла ли новая версия DSH; если да, прочитай её руководство по обновлению, выясни, затронут ли каждый установленный у меня неофициальный или созданный мной плагин, и перечисли, что и как нужно изменить.', + 'recommend.topicTracking.title': 'Отслеживание тем и статей', + 'recommend.topicTracking.description': 'Ищет новости и новые статьи на arXiv по выбранным темам и перечисляет ключевые моменты.', + 'recommend.topicTracking.schedule': 'Ежедневно в 9:00', + 'recommend.topicTracking.prompt': 'Создай задачу автоматизации под названием «Отслеживание тем и статей»: ежедневно в 9:00 ищи новости и новые статьи на arXiv по темам, за которыми я слежу, и перечисляй по каждой несколько ключевых моментов. Перед созданием спроси у меня темы, ключевые слова и источники.', + 'recommend.branchCleanup.title': 'Очистка веток и worktrees', + 'recommend.branchCleanup.description': 'Перечисляет локальные ветки и worktrees, чьи пул-реквесты слиты или закрыты, и удаляет их после подтверждения.', + 'recommend.branchCleanup.schedule': 'По пятницам в 17:00', + 'recommend.branchCleanup.prompt': 'Создай задачу автоматизации под названием «Очистка веток и worktrees»: по пятницам в 17:00 перечисляй локальные ветки и worktrees в текущем рабочем пространстве, чьи пул-реквесты слиты или закрыты, и удаляй их только после моего подтверждения.', + 'recommend.weather.title': 'Погода и поездки', + 'recommend.weather.description': 'Погода на сегодня и ближайшие три дня, с пометкой, когда нужен зонт или одежда потеплее.', + 'recommend.weather.schedule': 'Ежедневно в 7:30', + 'recommend.weather.prompt': 'Создай задачу автоматизации под названием «Погода и поездки»: ежедневно в 7:30 сообщай мне погоду в моём городе на сегодня и ближайшие три дня и отдельно предупреждай, если стоит взять зонт, одеться теплее или ожидать проблем с транспортом. Перед созданием спроси у меня, в каком я городе.', + 'recommend.workout.title': 'План тренировок на неделю', + 'recommend.workout.description': 'Составляет план тренировок на следующую неделю с учётом целей и дней для тренировок.', + 'recommend.workout.schedule': 'По воскресеньям в 20:00', + 'recommend.workout.prompt': 'Создай задачу автоматизации под названием «План тренировок на неделю»: по воскресеньям в 20:00 составляй мне план тренировок на следующую неделю с учётом моих целей и дней, когда я могу тренироваться, ничего не спрашивая у меня во время запуска. Перед созданием спроси у меня о целях, сколько дней в неделю я могу тренироваться, в какие дни я свободен и где тренируюсь.', +} + +/** Portuguese recommendation copy. */ +export const recommendationPt: Record = { + 'recommend.heading': 'Recomendadas', + 'recommend.dailyBrief.title': 'Resumo diário', + 'recommend.dailyBrief.description': 'Mudanças recentes no espaço de trabalho e o que precisa de acompanhamento, com o que fazer primeiro hoje.', + 'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00', + 'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.', + 'recommend.weeklyReview.title': 'Revisão semanal', + 'recommend.weeklyReview.description': 'Seu trabalho da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', + 'recommend.weeklyReview.schedule': 'Sextas às 16:00', + 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise o que eu fiz esta semana no espaço de trabalho atual e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, veja só os meus commits da semana e os pull requests que eu abri que foram mesclados esta semana ou continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', + 'recommend.issueScan.title': 'Varredura de issues', + 'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.', + 'recommend.issueScan.schedule': 'Segunda a sexta às 10:00', + 'recommend.issueScan.prompt': 'Crie uma tarefa de automação chamada “Varredura de issues”: de segunda a sexta às 10:00, faça uma varredura nas novas issues do repositório do espaço de trabalho atual, classifique-as em bugs, solicitações e perguntas e destaque as duplicadas e as que precisam da minha resposta. Faça o resumo só aqui; não responda no GitHub.', + 'recommend.pluginCompat.title': 'Compatibilidade de plug-ins', + 'recommend.pluginCompat.description': 'Quando sai uma nova versão do DSH, verifica se os plug-ins instalados e os criados por você precisam de ajustes.', + 'recommend.pluginCompat.schedule': 'Diariamente às 10:00', + 'recommend.pluginCompat.prompt': 'Crie uma tarefa de automação chamada “Compatibilidade de plug-ins”: todos os dias às 10:00, verifique se há uma nova versão do DSH; se houver, leia o guia de atualização dessa versão, confira um a um se os plug-ins não oficiais ou criados por mim que tenho instalados são afetados e liste o que mudar e como.', + 'recommend.topicTracking.title': 'Acompanhamento de temas e artigos', + 'recommend.topicTracking.description': 'Busca notícias e novos artigos do arXiv sobre os temas escolhidos e lista os pontos principais.', + 'recommend.topicTracking.schedule': 'Diariamente às 9:00', + 'recommend.topicTracking.prompt': 'Crie uma tarefa de automação chamada “Acompanhamento de temas e artigos”: todos os dias às 9:00, busque notícias e novos artigos do arXiv sobre os temas que eu acompanho e liste alguns pontos principais de cada um. Antes de criá-la, me pergunte quais são os temas, as palavras-chave e as fontes.', + 'recommend.branchCleanup.title': 'Limpeza de branches e worktrees', + 'recommend.branchCleanup.description': 'Lista as branches locais e os worktrees cujos pull requests foram mesclados ou fechados e os exclui após confirmação.', + 'recommend.branchCleanup.schedule': 'Sextas às 17:00', + 'recommend.branchCleanup.prompt': 'Crie uma tarefa de automação chamada “Limpeza de branches e worktrees”: toda sexta-feira às 17:00, liste as branches locais e os worktrees do espaço de trabalho atual cujos pull requests foram mesclados ou fechados, e exclua-os só depois que eu confirmar.', + 'recommend.weather.title': 'Clima e deslocamentos', + 'recommend.weather.description': 'O clima de hoje e dos próximos três dias, com um aviso quando for preciso guarda-chuva ou mais agasalho.', + 'recommend.weather.schedule': 'Diariamente às 7:30', + 'recommend.weather.prompt': 'Crie uma tarefa de automação chamada “Clima e deslocamentos”: todos os dias às 7:30, me diga o clima da minha cidade para hoje e os próximos três dias e avise quando eu precisar levar guarda-chuva, me agasalhar mais ou me preparar para problemas nos deslocamentos. Antes de criá-la, me pergunte qual é a minha cidade.', + 'recommend.workout.title': 'Plano de treino semanal', + 'recommend.workout.description': 'Planeja os treinos da próxima semana de acordo com seus objetivos e dias de treino.', + 'recommend.workout.schedule': 'Domingos às 20:00', + 'recommend.workout.prompt': 'Crie uma tarefa de automação chamada “Plano de treino semanal”: todo domingo às 20:00, planeje meus treinos da próxima semana de acordo com meus objetivos e os dias em que posso treinar, sem me perguntar nada durante a execução. Antes de criá-la, me pergunte quais são meus objetivos, quantos dias por semana posso treinar, quais dias tenho livres e onde treino.', +} diff --git a/packages/client/ui-schedule/src/client/session-schedule-state.ts b/packages/client/ui-schedule/src/client/session-schedule-state.ts index cc27321f00..4f8bd03fe4 100644 --- a/packages/client/ui-schedule/src/client/session-schedule-state.ts +++ b/packages/client/ui-schedule/src/client/session-schedule-state.ts @@ -2,7 +2,7 @@ * One Session's scheduled-task state for its header, Sidebar row mark, and hover card. * * These views project the Host catalog the page already owns — `schedule/catalog()` - * returns every Host task with its target and involved Sessions — so N + * returns every Host task with its delivery target — so N * visible rows share one Remote read and follow one `schedule/changed` * invalidation instead of issuing a query per row or header. */ @@ -10,7 +10,6 @@ import type { HostObservable, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ScheduleCatalogEntry } from '@deepseek-ai/dsh-schedule/client' -import { taskInvolvesSession } from './task-record.ts' import type { CatalogSnapshot } from './catalog-source.ts' /** Selector hook the renderer binds from a slot's `hooks.catalog` observable. */ @@ -30,15 +29,11 @@ export interface SessionScheduleFacts { const NO_RECORDS: readonly ScheduleCatalogEntry[] = [] /** - * Project the shared Host catalog onto one Session's active tasks. + * Select active tasks whose fixed delivery target is this Session. + * A Session with only paused or ended tasks has an empty list. * - * `schedule/catalog()` returns every Host task in every lifecycle state, so - * both facts come from this one snapshot filtered to the tasks that target or - * involve the Session with `status === 'active'`. A read that never settled - * answers no active task; a refresh republishes `loading` over the records of - * the last successful read, and the Host emits `schedule/changed` after every - * delivery, so following `status` here would blank a Session's mark for each - * roundtrip. A Session whose tasks are all paused or ended lists nothing. + * Refreshes use the last successful catalog so the clock stays visible + * while a delivery-triggered read is pending. * @param snapshot - shared Host catalog snapshot. * @param sessionId - Session whose facts are selected. * @returns this Session's active-task facts. @@ -49,7 +44,7 @@ export function selectSessionScheduleFacts( ): SessionScheduleFacts { if (!snapshot.settled) return { hasActive: false, records: NO_RECORDS } const records = snapshot.records.filter( - record => taskInvolvesSession(record, sessionId) && record.status === 'active', + record => record.status === 'active' && record.target.kind !== 'new' && record.target.sessionId === sessionId, ) return { hasActive: records.length > 0, records } } diff --git a/packages/client/ui-schedule/src/client/task-manager-locales.ts b/packages/client/ui-schedule/src/client/task-manager-locales.ts index 13ef7c9052..627141661c 100644 --- a/packages/client/ui-schedule/src/client/task-manager-locales.ts +++ b/packages/client/ui-schedule/src/client/task-manager-locales.ts @@ -1,4 +1,8 @@ /** Copy for the retained-reminder task manager's `schedule.manager` namespace. */ +import { + recommendationDe, recommendationEn, recommendationEs, recommendationFr, recommendationJa, recommendationPt, recommendationRu, + recommendationZh, +} from './recommendation-locales.ts' import { frequencyEn, frequencyJa, frequencyEs, frequencyFr, frequencyDe, frequencyRu, frequencyPt, frequencyZh } from './frequency-locales.ts' /** English task-manager dictionary and key domain. */ @@ -102,6 +106,7 @@ export const en = { 'frequency.once': 'Once', 'frequency.every': 'Every {value} {unit}', ...frequencyEn, + ...recommendationEn, 'timing.date': 'Date', 'timing.time': 'Time', 'timing.hour': 'Hour', @@ -268,6 +273,7 @@ export const zh: Record = { 'frequency.once': '仅一次', 'frequency.every': '每 {value} {unit}', ...frequencyZh, + ...recommendationZh, 'timing.date': '日期', 'timing.time': '时间', 'timing.hour': '时', @@ -331,6 +337,7 @@ export const zh: Record = { /** Japanese copy, checked against the English keys. */ export const ja = { ...frequencyJa, + ...recommendationJa, 'host.create': '作成', 'host.createMethod': '作成方法を選択', 'host.chatCreate': '会話で作成', @@ -544,6 +551,7 @@ export const es = { 'frequency.once': 'una vez', 'frequency.every': 'Cada {value} {unit}', ...frequencyEs, + ...recommendationEs, 'timing.date': 'Fecha', 'timing.time': 'tiempo', 'timing.hour': 'Hora', @@ -705,6 +713,7 @@ export const fr = { 'frequency.once': 'Une fois', 'frequency.every': 'Chaque {value} {unit}', ...frequencyFr, + ...recommendationFr, 'timing.date': 'Date', 'timing.time': 'Temps', 'timing.hour': 'Heure', @@ -866,6 +875,7 @@ export const de = { 'frequency.once': 'Einmal', 'frequency.every': 'Jeder {value} {unit}', ...frequencyDe, + ...recommendationDe, 'timing.date': 'Datum', 'timing.time': 'Zeit', 'timing.hour': 'Stunde', @@ -1027,6 +1037,7 @@ export const ru = { 'frequency.once': 'Однажды', 'frequency.every': 'Каждый {value} {unit}', ...frequencyRu, + ...recommendationRu, 'timing.date': 'Дата', 'timing.time': 'Время', 'timing.hour': 'Час', @@ -1188,6 +1199,7 @@ export const pt = { 'frequency.once': 'Uma vez', 'frequency.every': 'A cada {value} {unit}', ...frequencyPt, + ...recommendationPt, 'timing.date': 'Data', 'timing.time': 'Hora', 'timing.hour': 'Hora', diff --git a/packages/client/ui-schedule/src/client/task-record.ts b/packages/client/ui-schedule/src/client/task-record.ts index abb6a965f6..9321cbc8c5 100644 --- a/packages/client/ui-schedule/src/client/task-record.ts +++ b/packages/client/ui-schedule/src/client/task-record.ts @@ -20,15 +20,6 @@ export function taskSessionId(task: Pick { } }) + it('starts each recommendation in a new conversation with its single-line request in every language', async () => { + const sidebar = sidebarStubs() + const ctx = await baseContext(undefined, sidebar) + const owner = ctx.slots.register({ + name: 'root', + children: { + 'sidebar.right.pane.tab': { kind: 'keyed', scope: 'session' }, + 'sidebar.right.pane.tab.title': { kind: 'keyed', scope: 'session' }, + main: { kind: 'keyed', scope: 'root' }, + }, + } as never, Empty) + const startSession = vi.spyOn(ctx.uiWorkspace, 'startSession') + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + try { + const panel = injectedFace(ctx.slots.entries('main')[0]!, undefined as never) as TaskManagerInjected + for (const dictionary of Object.values(managerLocales)) { + const prompts = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.prompt')) + expect(prompts).toHaveLength(8) + for (const [, prompt] of prompts) { + expect(prompt).not.toContain('\n') + panel.onUseRecommendation(prompt) + expect(startSession).toHaveBeenLastCalledWith(undefined, { prompt, whenDraftExists: 'append' }) + } + } + expect(startSession).toHaveBeenCalledTimes(64) + } finally { + await fiber.dispose() + owner() + await ctx.fiber.dispose() + } + }) + + it('states each recommendation\'s shown run time in its request in every language', () => { + for (const dictionary of Object.values(managerLocales)) { + const schedules = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.schedule')) + expect(schedules).toHaveLength(8) + for (const [key, schedule] of schedules) { + const times = schedule.match(/\d{1,2}:\d{2}/g) + expect(times).toHaveLength(1) + // A digit boundary keeps 0:00 from matching inside 20:00. + expect(dictionary[key.replace(/schedule$/, 'prompt') as keyof typeof dictionary]) + .toMatch(new RegExp(`(? { const sidebar = sidebarStubs() const ctx = await baseContext(undefined, sidebar) diff --git a/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx b/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx index 0e43769d41..5567afb9d5 100644 --- a/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx +++ b/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx @@ -67,7 +67,7 @@ function mount(rows: readonly ScheduleCatalogEntry[] = [task], overrides: Partia useSessionStatus: select => select(new Map()), useSessionRetainInfo: () => undefined, useResource: () => { throw new Error('Task editor loads no document resources') }, useContextMenu: contextMenuHook(), - onNewTask: vi.fn(), onClearEnded: vi.fn(async () => {}), + onNewTask: vi.fn(), onUseRecommendation: vi.fn(), onClearEnded: vi.fn(async () => {}), onCreateTask: vi.fn(async () => ({ created: task })), onDelete: vi.fn(async () => 'deleted'), onRetry: vi.fn(async () => {}), onOpenSession: vi.fn(), hostActions: hostActions(), diff --git a/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts b/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts index 8cf7e0d7d7..aaf5e1f121 100644 --- a/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts +++ b/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts @@ -19,7 +19,7 @@ function catalogEntry(taskId: string, sessionId: string, status: Entry['status'] } /** - * A task whose every delivery creates a fresh Session; the Host leaves created Sessions out of `involvedSessionIds`. + * Build a `new` task with no fixed delivery Session. * @param taskId - task identity. * @param latestRun - Session that the latest delivery created, if one ran. * @returns an active per-run task created from {@link CREATOR}. @@ -45,28 +45,39 @@ function hostSnapshot( describe('shared Host catalog projection', () => { it('selects only the given Session’s active tasks from every lifecycle state', () => { - const mine = catalogEntry('mine', SESSION, 'active') - const other = catalogEntry('other', 'other-session', 'active') + const mine = { ...catalogEntry('mine', SESSION, 'active'), involvedSessionIds: [CREATOR, SESSION] } + const otherSession = 'other-session' as SessionId + const other = { ...catalogEntry('other', otherSession, 'active'), involvedSessionIds: [SESSION, otherSession] } const paused = catalogEntry('paused', SESSION, 'paused') const ended = catalogEntry('ended', SESSION, 'ended') const catalog = hostSnapshot('ready', [mine, other, paused, ended]) expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: true, records: [mine] }) - expect(selectSessionScheduleFacts(catalog, 'other-session' as SessionId)) + expect(selectSessionScheduleFacts(catalog, otherSession)) .toEqual({ hasActive: true, records: [other] }) - expect(selectSessionScheduleFacts(catalog, 'empty-session' as SessionId)) + expect(selectSessionScheduleFacts(catalog, CREATOR)) .toEqual({ hasActive: false, records: [] }) }) - it('lists a per-run task under its creator and under the Session its latest delivery created', () => { + it('lists a new_once task only for its reserved Session before the first delivery', () => { + const waiting: Entry = { + ...catalogEntry('waiting', SESSION, 'active'), + target: { kind: 'new_once', sessionId: SESSION, create: {} }, + involvedSessionIds: [CREATOR, SESSION], + } + const catalog = hostSnapshot('ready', [waiting]) + + expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: true, records: [waiting] }) + expect(selectSessionScheduleFacts(catalog, CREATOR)).toEqual({ hasActive: false, records: [] }) + }) + + it('leaves the creator and latest delivery Session empty for per-run tasks', () => { const ran = perRunEntry('ran', SESSION) const waiting = perRunEntry('waiting') const catalog = hostSnapshot('ready', [ran, waiting]) - expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: true, records: [ran] }) - expect(selectSessionScheduleFacts(catalog, CREATOR)).toEqual({ hasActive: true, records: [ran, waiting] }) - expect(selectSessionScheduleFacts(catalog, 'other-session' as SessionId)) - .toEqual({ hasActive: false, records: [] }) + expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: false, records: [] }) + expect(selectSessionScheduleFacts(catalog, CREATOR)).toEqual({ hasActive: false, records: [] }) }) it('answers no active task for a Session whose tasks are all paused or ended', () => { diff --git a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx index 55447e823b..44a048d993 100644 --- a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx +++ b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx @@ -172,6 +172,7 @@ function mount( onDelete: vi.fn(async () => 'deleted'), onRetry: vi.fn(async () => {}), onNewTask: vi.fn(), + onUseRecommendation: vi.fn(), onClearEnded: vi.fn(async () => {}), onCreateTask: vi.fn(async () => ({ created: at })), onOpenSession: vi.fn(), @@ -839,6 +840,70 @@ describe('Task manager catalog', () => { expect(emptyNewTaskButton().textContent).toBe(en['empty.action']) }) + const RECOMMENDATION_IDS = ['dailyBrief', 'weeklyReview', 'issueScan', 'pluginCompat', 'topicTracking', + 'branchCleanup', 'weather', 'workout'] as const + + function recommendations(dictionary: Dictionary = en): HTMLElement | null { + return screen.queryByRole('region', { name: dictionary['recommend.heading'] }) + } + + it('lists the built-in recommendations under the empty Enabled view and prefills each request', () => { + const h = mount({ records: [] }, en, {}, { startAtAll: false }) + const buttons = within(recommendations()!).getAllByRole('button') + expect(buttons.map(button => button.getAttribute('aria-label'))) + .toEqual(RECOMMENDATION_IDS.map(id => en[`recommend.${id}.title`])) + for (const [index, id] of RECOMMENDATION_IDS.entries()) { + const button = buttons[index]! + // The description and the run time are separate references, so a screen reader pauses between them. + expect(button.getAttribute('aria-describedby')!.split(' ').map(ref => document.getElementById(ref)?.textContent)) + .toEqual([en[`recommend.${id}.description`], en[`recommend.${id}.schedule`]]) + expect(button.querySelectorAll('svg[aria-hidden="true"]')).toHaveLength(3) + fireEvent.click(button) + expect(h.props.onUseRecommendation).toHaveBeenLastCalledWith(en[`recommend.${id}.prompt`]) + } + expect(h.props.onUseRecommendation).toHaveBeenCalledTimes(RECOMMENDATION_IDS.length) + expect(h.props.onNewTask).not.toHaveBeenCalled() + expect(emptyNewTaskButton().textContent).toBe(en['empty.action']) + }) + + it('shows the recommendations under the empty All view in the active language', () => { + mount({ records: [] }, zh) + const section = recommendations(zh)! + expect(within(section).getByRole('button', { name: zh['recommend.weather.title'] })).toBeDefined() + expect(section.textContent).toContain(zh['recommend.weather.schedule']) + }) + + it.each([ + ['paused', 'list.emptyPaused'], + ['ended', 'list.emptyInactive'], + ] as const)('omits the recommendations from the empty %s view', (status, title) => { + mount({ records: [] }) + const statuses = screen.getByRole('group', { name: en['statusFilter.label'] }) + fireEvent.click(within(statuses).getByRole('button', { name: en[`status.${status}`] })) + expect(screen.getByRole('status').textContent).toContain(en[title]) + expect(recommendations()).toBeNull() + }) + + it('omits the recommendations while rows are listed, a search matches nothing, or the catalog loads', () => { + const h = mount({ records }) + expect(recommendations()).toBeNull() + fireEvent.change(screen.getByRole('searchbox', { name: en['search.label'] }), { target: { value: 'no such task' } }) + expect(screen.getByRole('status').textContent).toContain(en['list.noMatches']) + expect(recommendations()).toBeNull() + h.view.unmount() + mount({ records: [], status: 'loading' }) + expect(recommendations()).toBeNull() + }) + + it('lists every recommendation under the empty Enabled view while paused and ended tasks use their titles', () => { + mount({ records: [ + { ...paused, title: en['recommend.dailyBrief.title'] }, + { ...ended, title: en['recommend.weather.title'] }, + ] }, en, {}, { startAtAll: false }) + expect(within(recommendations()!).getAllByRole('button').map(button => button.getAttribute('aria-label'))) + .toEqual(RECOMMENDATION_IDS.map(id => en[`recommend.${id}.title`])) + }) + it('distinguishes an empty catalog, loading, and a failed read', () => { const h = mount({ records: [], status: 'loading' }) expect(screen.getByRole('status', { name: en['list.loading'] }).textContent).toBe('') @@ -1796,13 +1861,13 @@ describe('Task detail metrics', () => { expect(instruction).toMatch(/field-sizing:\s*content;/) expect(instruction).toMatch(/padding:\s*12px;/) expect(instruction).toMatch(/border:\s*0\.5px solid var\(--dsw-alias-border-l3\);/) - expect(instruction).toMatch(/border-radius:\s*16px;/) + expect(instruction).toMatch(/border-radius:\s*var\(--dsw-radius-lg\);/) // The mock inherits the instruction's 14px text and pins its own 24px leading. expect(instruction).toMatch(/font-size:\s*14px;/) expect(instruction).toMatch(/line-height:\s*24px;/) expect(stylesheet).toMatch(/\.instruction:hover\s*\{[^}]*border-color:\s*var\(--dsw-alias-border-l2\);/) expect(stylesheet).toMatch(/\.instruction:focus\s*\{[^}]*border-color:\s*var\(--dsw-alias-state-business-primary\);/) - expect(stylesheet).toMatch(/\.ruleRows\s*\{[^}]*border-radius:\s*16px;/) + expect(stylesheet).toMatch(/\.ruleRows\s*\{[^}]*border-radius:\s*var\(--dsw-radius-lg\);/) }) }) @@ -1825,7 +1890,7 @@ describe('Mock detail metrics shared with the task list', () => { expect(notice).toMatch(/gap:\s*9px;/) expect(notice).toMatch(/align-items:\s*flex-start;/) expect(notice).toMatch(/background:\s*var\(--dsw-specific-sidebar-fill\);/) - expect(notice).toMatch(/border-radius:\s*10px;/) + expect(notice).toMatch(/border-radius:\s*var\(--dsw-radius-lg\);/) expect(notice).toMatch(/margin:\s*0 0 20px;/) // The notice keeps the colour this box had before it took the mock's // surface fill; the retired deletion-failure variant leaves no rule behind. @@ -1866,7 +1931,7 @@ describe('Mock detail metrics shared with the task list', () => { // jsdom computes no layout, so the values are read from the applied // stylesheet the way the detail-metric assertions above read it. expect(rule('pageScroll')).toMatch(/overflow:\s*auto;/) - expect(rule('pageContent')).toMatch(/max-width:\s*960px;/) + expect(rule('pageContent')).toMatch(/max-width:\s*calc\(960px \+ 2 \* clamp\(24px, 4vw, 48px\)\);/) expect(rule('pageContent')).toMatch(/margin:\s*0 auto;/) // The Plugins page's own column inset, shared by both first-level pages: // inline and bottom only, because the heading row owns the top inset. @@ -1894,7 +1959,7 @@ describe('Mock detail metrics shared with the task list', () => { expect(headerAction).toMatch(/height:\s*32px;/) expect(headerAction).toMatch(/font-size:\s*13px;/) expect(headerAction).toMatch(/padding:\s*0 12px;/) - expect(headerAction).toMatch(/border-radius:\s*16px;/) + expect(headerAction).toMatch(/border-radius:\s*var\(--dsw-radius-md\);/) const headingTitle = /\.pageHeading h1\s*\{([^}]*)\}/.exec(stylesheet)?.[1] ?? '' // The first-level title step is the Plugins page's `pageTitle`, not the // mock's larger page heading; the equality case below pins that pair. @@ -1906,7 +1971,7 @@ describe('Mock detail metrics shared with the task list', () => { const tab = rule('filterTab') expect(tab).toMatch(/height:\s*28px;/) expect(tab).toMatch(/padding:\s*0 10px;/) - expect(tab).toMatch(/border-radius:\s*14px;/) + expect(tab).toMatch(/border-radius:\s*var\(--dsw-radius-sm\);/) expect(tab).toMatch(/font-size:\s*14px;/) // The selected chip keeps the chip's own weight; only the fill marks it. expect(rule('filterTabActive')).not.toMatch(/font-weight/) @@ -1920,12 +1985,12 @@ describe('Mock detail metrics shared with the task list', () => { expect(field).toMatch(/height:\s*var\(--task-search-height\);/) expect(field).toMatch(/padding:\s*0 10px;/) expect(field).toMatch(/border:\s*0\.5px solid var\(--dsw-alias-border-l3\);/) - expect(field).toMatch(/border-radius:\s*12px;/) + expect(field).toMatch(/border-radius:\s*var\(--dsw-radius-md\);/) expect(stylesheet).toMatch(/\.searchField:hover\s*\{[^}]*border-color:\s*var\(--dsw-alias-border-l2\);/) expect(stylesheet) .toMatch(/\.searchField:focus-within\s*\{[^}]*border-color:\s*var\(--dsw-alias-state-business-primary\);/) expect(stylesheet).toMatch(/\.searchField > :first-child svg\s*\{[^}]*width:\s*14px;/) - expect(stylesheet).toMatch(/\.searchField input::placeholder\s*\{[^}]*color:\s*var\(--dsw-alias-label-caption\);/) + expect(stylesheet).toMatch(/\.searchField input::placeholder\s*\{[^}]*color:\s*var\(--dsw-alias-label-tertiary\);/) expect(stylesheet).toMatch(/\.searchField input::-webkit-search-cancel-button\s*\{[^}]*display:\s*none;/) expect(rule('searchClear')).toMatch(/margin-right:\s*-6px;/) expect(rule('searchClear')).toMatch(/color:\s*var\(--dsw-alias-label-tertiary\);/) @@ -1939,7 +2004,7 @@ describe('Mock detail metrics shared with the task list', () => { expect(row).toMatch(/width:\s*100%;/) expect(row).not.toMatch(/margin:/) expect(row).toMatch(/padding:\s*8px;/) - expect(row).toMatch(/border-radius:\s*12px;/) + expect(row).toMatch(/border-radius:\s*var\(--dsw-radius-lg\);/) expect(row).not.toMatch(/border(?:-(?!radius)|:)/) expect(stylesheet) .toMatch(/\.row:hover\s*\{[^}]*background:\s*var\(--dsw-alias-interactive-bg-hover\);/) @@ -2062,7 +2127,7 @@ describe('Task manager deletion', () => { const dialog = openDelete() const cancel = within(dialog).getByRole('button', { name: en['delete.cancel'] }) const confirm = within(dialog).getByRole('button', { name: en['delete.confirm'] }) - const content = dialog.querySelector(`.${css.confirmContent}`)! + const content = dialog.querySelector(`.${css.confirmContent}`)! expect(dialog.classList.contains(css.confirmDialog!)).toBe(true) expect(content.textContent).toContain(at.prompt) expect(content.contains(cancel)).toBe(false) @@ -2075,9 +2140,16 @@ describe('Task manager deletion', () => { // installed. The dialog's cap must follow the padding of the Modal layer // that holds it, and the scrolling content must sit inside that cap instead // of pinning a number that a wrong layer padding could not contradict. - installStyles({ confirmDialog: css.confirmDialog, confirmContent: css.confirmContent }) + installStyles({ confirmDialog: css.confirmDialog, confirmContent: css.confirmContent, confirmPrompt: css.confirmPrompt }) expect(getComputedStyle(dialog).maxHeight).toBe(`calc(100dvh - ${MODAL_LAYER_PADDING * 2}px)`) expect(getComputedStyle(content).overflowY).toBe('auto') + // The instruction is a three-line excerpt, so a long one cannot stretch the dialog. + const prompt = within(content).getByText(/^Review release/) + const clamp = getComputedStyle(prompt) + expect(clamp.display).toBe('-webkit-box') + expect(clamp.getPropertyValue('-webkit-box-orient')).toBe('vertical') + expect(clamp.overflow).toBe('hidden') + expect(clamp.getPropertyValue('-webkit-line-clamp')).toBe('3') const footer = dialog.lastElementChild as HTMLElement expect(getComputedStyle(footer).flexShrink).toBe('0') fireEvent.click(confirm) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml new file mode 100644 index 0000000000..b2577faa28 --- /dev/null +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -0,0 +1,43 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-session-panel/README.md +/: + en: 8409e6477f312897 + zh: b982bc13dfe0e002 +/deepseek-ai-dsh-client-ui-session-panel: + en: aff5b9d70836e810 + zh: 2cb8c75d3c82fba9 +/deepseek-ai-dsh-client-ui-session-panel/summary: + en: b5a091528bf5375a + zh: 48a22fec747fb07a +/deepseek-ai-dsh-client-ui-session-panel/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-client-ui-session-panel/use-this-package: + en: 62a513f72d48d6e2 + zh: 7f0eb3e873c0473f +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/docking-and-the-overlay: + en: 67b33b9f412a687d + zh: 2a9b8c89c8bb22e4 +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/contribute-a-section: + en: b76852d8740aee0f + zh: ccfeb7774e1b0e27 +/deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: + en: ede595ecc4aab24a + zh: 5a30a4042ab7483a +/deepseek-ai-dsh-client-ui-session-panel/further-exploration: + en: 09b403af819bd155 + zh: e949998de4794393 +/deepseek-ai-dsh-client-ui-session-panel/model-experience: + en: 7e8bbe318a76fd54 + zh: c60e87da2a37642a +/deepseek-ai-dsh-client-ui-session-panel/model-experience/kv-cache-effect: + en: 47f982e326fe77fd + zh: 275b2ef7eec3ab19 +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work: + en: d5cf7883b7f7e0ab + zh: f5407439447acc44 +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: b532016223ceceef diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md new file mode 100644 index 0000000000..43ba71d18e --- /dev/null +++ b/packages/client/ui-session-panel/README.md @@ -0,0 +1,134 @@ +--- +description: "The Session panel: a header toggle and a floating panel in the Chat View's aside whose sections other plugins register, with the built-in Environment section." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-session-panel + +English | [中文](README.zh.md) + +## Summary + +`dsh-client-ui-session-panel` adds a Session header toggle that shows or hides a floating panel of facts about the current Session. The panel lives in the Chat View: it docks in the Chat View's end gutter when the gutter can hold it, and otherwise opens over the transcript on request. It draws section titles and leaves section content to the plugins that register sections; it ships the Environment section with the working folder row. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +The `@deepseek-ai/dsh-web-app` bundle loads this package by default. The toggle is the first Session header utility, before sharing and the schedule catalog. It is an icon button with the panel name and its indicators as its accessible name, a tooltip that says whether a press shows or hides the panel, shown after 500ms of hover or at once on keyboard focus, and `aria-expanded` for whether the panel shows. + +### Docking and the overlay + +The panel docks while the gutter between the transcript column and the Chat frame's end edge is at least 348px: 40px clear of the column and its width handle, the panel's 300px minimum width, and an 8px edge margin. Docked, it is 300–360px wide, 8px from the end edge, starts 12px below the header, stops above the composer stack, and scrolls inside itself in a reserved scrollbar column 2px from its end edge, so its content keeps one width whether or not it scrolls. Pressing the toggle then flips one docking preference that every Session shares and that persists in `localStorage` under `dsh.sessionPanel.pinned`; the panel docks by default. + +A narrower gutter hides the docked panel, so it never covers the transcript. This includes a narrow window, an expanded right sidebar, and a dragged-wide transcript column. Pressing the toggle then opens the panel over the transcript with the prominent elevation, 280px wide so it covers less of the transcript than the docked panel takes beside it, 8px from the end edge, above the composer stack and not covering it. The overlay closes from the toggle, on Escape, and on a pointer press outside the panel, the toggle, and any open menu, such as a row's context menu; Escape returns focus to the toggle when focus was inside the panel. A modal above the page, an input method composing text, and a handler that already took the key, such as an open menu's, keep Escape; otherwise the overlay takes it first, so with the overlay open the first Escape from the composer closes the overlay and does not count toward stopping a running turn. Closing it does not change the docking preference. At most one Session's overlay is open; it closes once the gutter widens enough to dock and once no Chat View shows the Session, as after switching to another Session or View, and switching back does not reopen it. When the panel hides while focus is inside it, focus moves to the toggle. + +Other Views, such as the trajectory View, show no panel. While no Chat View shows the Session, the toggle is unavailable: it stays in the header with its indicators, dimmed, and its tooltip asks to switch to the Chat view. + + +### Contribute a section + +A section is one `conversation.session.panel.section` list registration: `id` addresses it, `order` sorts it ascending, and the required `label` is its title, which the panel draws in the active locale. The section component receives `presentation` (`docked` or `overlay`) and `dismissOverlay()` as owner props; it renders its body and renders nothing when it has nothing to show, which hides its title too. Register trailing title controls, such as a count or a refresh button, in the keyed `conversation.session.panel.section.actions` slot under the section's `id`. A section without a label is reported to the console and not shown. The shipped sections are Environment (`order: 0`), Change requests from the [forge bundle](../../experimental/client-ui-forge/README.md) (`100`), [Subagents](../ui-subagent/README.md) (`200`), [Shared tasks](../ui-agent-team/README.md) (`250`), and [Background jobs](../ui-jobs/README.md) (`300`). + +Plugins share a title by registering rows in a section owner's row slot. The built-in Environment section (`id: 'environment'`, `order: 0`) declares `conversation.session.panel.environment.row`, whose rows receive the same owner props as a section; its `project` row (`order: 0`) shows the Session's working folder: the current directory from the `workingDirectory` projection, or, before the projection arrives or when it records none, the directory the Session was created in, then the directory of the Workspace that lists the Session. The row shows the folder name followed by its parent folder in tertiary ink, which clips with an ellipsis; its tooltip, shown after 500ms of hover, names the working folder and gives the full path. Both abbreviate the Host home to `~`. Right-clicking the row or pressing its More button opens the shared `directory` context menu. The forge bundle adds its checkout and local changes rows at orders 20 and 30. A plugin that owns a shared section declares its own row slot the same way. + +Marks that must stay visible while the panel is hidden, such as an attention dot, go in the `conversation.session.panel.indicator` list. Each occupant is one element: the toggle sizes it to a 6px dot at the glyph's corner, and the occupant sets its `background` and includes text that names it, which becomes part of the toggle's accessible name. Occupants overlap, and a higher `order` paints above a lower one. The `panelShown` owner prop lets a mark that only repeats the panel's content render nothing while the panel shows. Subagents and Background jobs show a blue dot while work runs and the panel does not show (orders 10 and 20); the forge bundle's red attention dot (order 100) paints above them and stays while the panel shows. + +Rows share one look without sharing a component. A section's component, or an Environment row entry, writes its row's markup and marks the parts, and the panel's stylesheet lays them out, so icon, text, and trailing areas line up across packages while each package owns what its row contains. + +| Mark | Part | +|---|---| +| `data-session-panel-row` | The row: one 28px line. A row with an action or a menu highlights as a whole on hover and while one of its menus is open. | +| `data-row-part="body"` | The icon and the text. A ` + + ) +} diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.module.css b/packages/client/ui-session-panel/src/client/ProjectRow.module.css new file mode 100644 index 0000000000..0e99b68fd7 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/ProjectRow.module.css @@ -0,0 +1,41 @@ +/* [name] · [parent]: the name keeps its width up to the row, and the parent + fills the rest of the line and clips with an ellipsis. With less than 5em + left for it, the parent wraps onto a second line, which the one-line height + hides, so the row never shows a separator without a parent. The separator + is decorative, so assistive technology reads the name and the parent alone. */ + +.folder { + display: flex; + flex-wrap: wrap; + align-items: baseline; + min-width: 0; + height: 1lh; + overflow: hidden; + white-space: nowrap; +} + +.folder:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} + +.name { + flex: 0 1 auto; + min-width: 0; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; +} + +.parent { + flex: 1 1 0; + min-width: 5em; + overflow: hidden; + color: var(--dsw-alias-label-tertiary); + text-overflow: ellipsis; +} + +.parent::before { + padding: 0 4px; + content: '·' / ''; +} diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.tsx b/packages/client/ui-session-panel/src/client/ProjectRow.tsx new file mode 100644 index 0000000000..15f64d245d --- /dev/null +++ b/packages/client/ui-session-panel/src/client/ProjectRow.tsx @@ -0,0 +1,51 @@ +/** Environment row naming the Session's working folder. */ +import type { ReactNode } from 'react' +import { IconFolderCloseRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { abbreviateHomePath, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' +import type {} from '@deepseek-ai/dsh-working-directory/types' +import type { ProjectRowProps } from './slots.ts' +import css from './ProjectRow.module.css' + +const ROOT = /^(?:[/\\]|[A-Za-z]:[/\\])$/ + +/** + * Render the Session's working folder as its name followed by its parent + * folder, with the label and the full path in the tooltip. The folder is the + * Session's current working directory; before that projection arrives, or + * when it records none, it is the directory the Session was created in, else + * the Workspace that lists the Session. Paths under the Host account home + * start with `~`. The row and its More button open the directory context menu. + * @param props - Session values, the working directory projection, Workspace and Session list hooks, Host facts, menu bindings, and copy. + * @returns the row, or null before the Session's directory is known. + */ +export function ProjectRow({ + sessionId, useProjection, useWorkspaces, useSessions, useHost, useContextMenu, renderFactorySlot, t, +}: ProjectRowProps): ReactNode { + const current = useProjection('workingDirectory') + const createdIn = useSessions(snapshot => snapshot.byId[sessionId]?.cwd) + const workspacePath = useWorkspaces(snapshot => snapshot.items.find(item => item.sessionIds.includes(sessionId))?.path) + const home = useHost(facts => facts.home) + const { getTriggerProps } = useContextMenu() + const path = current ?? createdIn ?? workspacePath + if (path === undefined) return null + const shown = abbreviateHomePath(path, home) + const { directory, name } = pathPartsOf(shown) + const parent = ROOT.test(directory) ? directory : directory.replace(/[/\\]+$/, '') + const target = { kind: 'directory', value: { sessionId, path } } as const + return ( +
      + + + + + + {name} + {parent !== '' && {parent}} + + + + + {renderFactorySlot('contextMenu.button', { target, label: t('project.actions') })} +
      + ) +} diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css new file mode 100644 index 0000000000..f16ef86393 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -0,0 +1,373 @@ +/* The panel floats in the Chat View's aside layer, a zero-height box across + the top of the Chat frame that passes pointer events through. The layer + inherits the scrollport's --dsh-conversation-viewport-height and + --dsh-composer-height and publishes --dsh-chat-aside-gutter, the inline + space between the transcript column and the frame's end edge. */ + +/* The docked panel's inline metrics: 40px clear of the transcript column, + past its width handle, 8px from the end edge, and at least 300px wide. The + panel's width and the dock probe both derive from them, so the gutter that + docks the panel is exactly the one that holds its minimum width. */ +.panel, +.dockProbe { + --panel-clear: 40px; + --panel-edge: 8px; + --panel-min-width: 300px; +} + +.panel { + position: absolute; + top: 12px; + right: var(--panel-edge); + box-sizing: border-box; + width: clamp( + var(--panel-min-width), + calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge)), + 360px + ); + /* Stops above the composer stack, whose seat fades and takes presses across the body's full width. */ + max-height: calc(var(--dsh-conversation-viewport-height, 100dvh) - var(--dsh-composer-height, 152px) - 24px); + overflow-y: auto; + overscroll-behavior: contain; + /* The bar has a place of its own: the content keeps its width whether or not + the panel scrolls, and the end inset stays 8px. A transparent end border + over the panel's own background holds the bar 2px from the edge, as the + sidebar does, and the track margin keeps the thumb out of the rounded corners. */ + scrollbar-gutter: stable; + --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); + --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); + --dsh-scrollbar-track-margin: 12px; + padding: 6px calc(8px - 2px - var(--dsh-scrollbar-width)) 6px 8px; + border: 0; + border-right: 2px solid transparent; + /* The standard menu tier: a compact summary surface, not an enclosing panel. */ + border-radius: var(--dsw-radius-lg); + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-bg-layer-1); + box-shadow: var(--dsw-elevation-panel); + pointer-events: auto; + animation: dsh-session-panel-enter 120ms ease-out; +} + +/* Over the transcript the panel is narrower than docked, so it covers less of + the transcript, and takes the prominent elevation. */ +.panel[data-session-panel='overlay'] { + width: min(280px, calc(100% - 2 * var(--panel-edge))); + box-shadow: var(--dsw-elevation-prominent); +} + +/* The dock probe tells the plugin whether the gutter holds the docked panel + without a pixel measurement: it is 1px wide from the gutter that fits the + panel's minimum width and 0 below it, a width under 0 being used as 0. A + size observer on it therefore reports only when the docking decision + flips, not while the window resizes on one side of it or the transcript + grows. It has no height and takes no pointer events. */ +.dockProbe { + position: absolute; + top: 0; + right: 0; + width: calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px); + max-width: 1px; + height: 0; + visibility: hidden; + pointer-events: none; +} + +.section { + padding: 4px 0 6px; +} + +/* An empty body hides its section: a plain section renders into one outlet + anchor, and a shared section renders its own row outlet inside it. */ +.section:has(> .body > [data-slot]:empty), +.section:has(> .body > [data-slot] > [data-slot]:only-child:empty) { + display: none; +} + +.section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty)) + ~ .section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty)) { + margin-top: 2px; + padding-top: 8px; + border-top: 0.5px solid var(--dsw-alias-border-l2); +} + +.head { + display: flex; + align-items: center; + gap: 8px; + min-height: 24px; + padding: 0 6px; +} + +/* Secondary ink at medium weight: apart from the primary rows below and the tertiary counts beside it. */ +.title { + flex: 0 1 auto; + min-width: 0; + margin: 0; + overflow: hidden; + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xxs-12); + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* Takes what the title leaves and clips first, so long progress never squeezes the title. */ +.actions { + display: inline-flex; + flex: 1 1000 0; + align-items: center; + justify-content: flex-end; + gap: 2px; + min-width: 0; + overflow: hidden; +} + +.actions:has(> [data-slot]:empty) { + display: none; +} + +@keyframes dsh-session-panel-enter { + from { opacity: 0; transform: translateY(-4px); } + to { opacity: 1; transform: translateY(0); } +} + +@media (prefers-reduced-motion: reduce) { + .panel { + animation: none; + } +} + +/* Rows. The rows of every section share one look without sharing a + component: each contributor writes its row's markup and marks the parts, + and these rules lay them out. + + [data-session-panel-row] the row: one 28px line + [data-row-part='body'] the icon and the text; a + + ) +} diff --git a/packages/client/ui-session-panel/src/client/element-ids.ts b/packages/client/ui-session-panel/src/client/element-ids.ts new file mode 100644 index 0000000000..f6e881ee55 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/element-ids.ts @@ -0,0 +1,20 @@ +/** DOM ids that connect a Session's toggle and panel across their separate slot entries. */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' + +/** + * Id of a Session's panel element, which the toggle names in `aria-controls`. + * @param sessionId - Session that owns the panel. + * @returns the element id. + */ +export function panelElementId(sessionId: SessionId): string { + return `dsh-session-panel-${sessionId}` +} + +/** + * Id of a Session's toggle, which receives focus when its overlay closes from the keyboard. + * @param sessionId - Session whose header holds the toggle. + * @returns the element id. + */ +export function toggleElementId(sessionId: SessionId): string { + return `dsh-session-panel-toggle-${sessionId}` +} diff --git a/packages/client/ui-session-panel/src/client/index.ts b/packages/client/ui-session-panel/src/client/index.ts new file mode 100644 index 0000000000..e75283bca3 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/index.ts @@ -0,0 +1,109 @@ +/** + * Session panel plugin, browser half: a Session header toggle and a floating + * panel in the Chat View's aside. The panel draws the titles of the sections + * other plugins register, lays out the rows they mark, offers the fold control + * their lists end with and the details their rows show on hover, and ships the + * Environment section with the working folder row. + */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-chat/client' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-connection/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { EnvironmentSection } from './EnvironmentSection.tsx' +import { PanelDetails } from './PanelDetails.tsx' +import { PanelFold } from './PanelFold.tsx' +import { ProjectRow } from './ProjectRow.tsx' +import { SessionPanel } from './SessionPanel.tsx' +import { SessionPanelToggle } from './SessionPanelToggle.tsx' +import { sectionSource } from './sections.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from './slots.ts' +import { SessionPanelState } from './visibility.ts' +import { de, en, es, fr, ja, NS, pt, ru, zh, type SessionPanelKey } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Session panel copy. */ + sessionPanel: SessionPanelKey + } +} + +export type { + EnvironmentSectionProps, PanelDetailsFact, PanelDetailsProps, PanelFoldProps, ProjectRowInjected, ProjectRowProps, SessionPanelDockable, + SessionPanelIndicatorOwnerProps, SessionPanelInjected, SessionPanelPresentation, SessionPanelProbes, SessionPanelProps, + SessionPanelSectionEntry, SessionPanelSectionOwnerProps, SessionPanelToggleInjected, SessionPanelToggleProps, SessionPanelVisibility, +} from './slots.ts' + +/** Required services: the slot registry, dictionaries, and the Host facts of the Remote carrier. */ +export const inject = ['slots', 'locale', 'remote'] + +/** + * Client plugin body: register the dictionaries, the fold control and row + * details Factories, the header toggle, the panel, and the Environment section + * with its project row. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-session-panel: dictionaries') + const t = ctx.locale.bind(NS) + const state = new SessionPanelState() + ctx.effect(() => () => { state.dispose() }, 'ui-session-panel: overlay follower and dock probes') + const sections = sectionSource(ctx) + const host: ObservableSnapshot = { + getSnapshot: () => ctx.remote.$host, + subscribe: listener => ctx.on('connection/reset', listener), + } + + ctx.slots.registerFactory({ name: 'conversation.session.panel.fold', scope: 'root' }, PanelFold) + ctx.slots.registerFactory({ name: 'conversation.session.panel.details', scope: 'root' }, PanelDetails) + + ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({ + name: 'conversation.session.header.utilities', + id: 'session-panel', + // The first utility: left of change requests, sharing, and the schedule catalog. + order: -10, + locale: NS, + children: { + 'conversation.session.panel.indicator': { kind: 'list', scope: 'session', inline: true }, + }, + inject: (): SessionPanelToggleInjected => ({ + hooks: { visibility: state.visibility, dockable: state.dockable }, + toggle: (sessionId) => { state.toggle(sessionId) }, + }), + }, SessionPanelToggle)) + + ctx.slots.inject('conversation.chat.aside', () => ctx.slots.register({ + name: 'conversation.chat.aside', + locale: NS, + children: { + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + }, + inject: (): SessionPanelInjected => ({ + hooks: { visibility: state.visibility, sections, probes: state.probes }, + createProbeRef: (sessionId, probe) => state.createProbeRef(sessionId, probe), + closeOverlay: (sessionId) => { state.closeOverlay(sessionId) }, + }), + }, SessionPanel)) + + ctx.slots.inject('conversation.session.panel.section', () => ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'environment', + order: 0, + label: () => t('section.environment'), + children: { + 'conversation.session.panel.environment.row': { kind: 'list', scope: 'session' }, + }, + }, EnvironmentSection)) + + ctx.slots.inject('conversation.session.panel.environment.row', () => ctx.slots.register({ + name: 'conversation.session.panel.environment.row', + id: 'project', + order: 0, + locale: NS, + inject: (): ProjectRowInjected => ({ hooks: { host } }), + }, ProjectRow)) +} diff --git a/packages/client/ui-session-panel/src/client/locales.ts b/packages/client/ui-session-panel/src/client/locales.ts new file mode 100644 index 0000000000..1264e8ad94 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/locales.ts @@ -0,0 +1,95 @@ +/** `sessionPanel` namespace dictionaries. */ + +/** Dictionary namespace owned by this plugin. */ +export const NS = 'sessionPanel' + +/** Simplified Chinese dictionary (the key-set source of truth). */ +export const zh = { + 'panel.name': '会话面板', + 'toggle.show': '显示会话面板', + 'toggle.hide': '隐藏会话面板', + 'toggle.unavailable': '切换到「对话」视图后可显示会话面板', + 'section.environment': '环境', + 'project.label': '工作目录', + 'project.actions': '工作目录操作', +} as const + +/** Every key of the `sessionPanel` namespace. */ +export type SessionPanelKey = keyof typeof zh + +/** English dictionary, key-identical to the Chinese source of truth. */ +export const en: Record = { + 'panel.name': 'Session panel', + 'toggle.show': 'Show session panel', + 'toggle.hide': 'Hide session panel', + 'toggle.unavailable': 'Switch to the Chat view to show the session panel', + 'section.environment': 'Environment', + 'project.label': 'Working folder', + 'project.actions': 'Working folder actions', +} + +/** Japanese dictionary. */ +export const ja = { + 'panel.name': 'セッションパネル', + 'toggle.show': 'セッションパネルを表示', + 'toggle.hide': 'セッションパネルを非表示', + 'toggle.unavailable': '「チャット」ビューに切り替えるとセッションパネルを表示できます', + 'section.environment': '環境', + 'project.label': '作業フォルダー', + 'project.actions': '作業フォルダーの操作', +} satisfies Record + +/** Spanish dictionary. */ +export const es = { + 'panel.name': 'Panel de la sesión', + 'toggle.show': 'Mostrar el panel de la sesión', + 'toggle.hide': 'Ocultar el panel de la sesión', + 'toggle.unavailable': 'Cambia a la vista Chat para mostrar el panel de la sesión', + 'section.environment': 'Entorno', + 'project.label': 'Carpeta de trabajo', + 'project.actions': 'Acciones de la carpeta de trabajo', +} satisfies Record + +/** French dictionary. */ +export const fr = { + 'panel.name': 'Panneau de session', + 'toggle.show': 'Afficher le panneau de session', + 'toggle.hide': 'Masquer le panneau de session', + 'toggle.unavailable': 'Passez à la vue Discussion pour afficher le panneau de session', + 'section.environment': 'Environnement', + 'project.label': 'Dossier de travail', + 'project.actions': 'Actions sur le dossier de travail', +} satisfies Record + +/** German dictionary. */ +export const de = { + 'panel.name': 'Sitzungsbereich', + 'toggle.show': 'Sitzungsbereich anzeigen', + 'toggle.hide': 'Sitzungsbereich ausblenden', + 'toggle.unavailable': 'Wechseln Sie zur Ansicht „Chat“, um den Sitzungsbereich anzuzeigen', + 'section.environment': 'Umgebung', + 'project.label': 'Arbeitsordner', + 'project.actions': 'Aktionen für den Arbeitsordner', +} satisfies Record + +/** Russian dictionary. */ +export const ru = { + 'panel.name': 'Панель сеанса', + 'toggle.show': 'Показать панель сеанса', + 'toggle.hide': 'Скрыть панель сеанса', + 'toggle.unavailable': 'Переключитесь на вид «Чат», чтобы показать панель сеанса', + 'section.environment': 'Среда', + 'project.label': 'Рабочая папка', + 'project.actions': 'Действия с рабочей папкой', +} satisfies Record + +/** Brazilian Portuguese dictionary. */ +export const pt = { + 'panel.name': 'Painel da sessão', + 'toggle.show': 'Mostrar painel da sessão', + 'toggle.hide': 'Ocultar painel da sessão', + 'toggle.unavailable': 'Mude para a visualização Chat para mostrar o painel da sessão', + 'section.environment': 'Ambiente', + 'project.label': 'Pasta de trabalho', + 'project.actions': 'Ações da pasta de trabalho', +} satisfies Record diff --git a/packages/client/ui-session-panel/src/client/sections.ts b/packages/client/ui-session-panel/src/client/sections.ts new file mode 100644 index 0000000000..fcc9feed5e --- /dev/null +++ b/packages/client/ui-session-panel/src/client/sections.ts @@ -0,0 +1,66 @@ +/** Projection of the section list's registrations into the titles the panel draws. */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import { resolveSlotLabel, type StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionPanelSectionEntry } from './slots.ts' + +const SECTION_SLOT = 'conversation.session.panel.section' + +/** + * Project live section registrations in display order. A registration + * without a label cannot be titled; it is reported and left out. + * @param entries - shadowing winners of the section list in ledger order. + * @param report - receives one message per unlabeled registration. + * @returns sections ordered by ascending `order`, then registration order. + */ +export function projectSections( + entries: readonly StoredEntry[], report: (message: string) => void, +): readonly SessionPanelSectionEntry[] { + const rows: (SessionPanelSectionEntry & { readonly order: number })[] = [] + for (const entry of entries) { + /* v8 ignore next -- list registration validates id at load. */ + const id = entry.options.id ?? '' + const label = resolveSlotLabel(entry.options.label) + if (label === undefined || label === '') { + report(`ui-session-panel: section "${id}" from ${entry.registrant ?? 'an unknown registrant'} has no label and is not shown`) + continue + } + rows.push({ id, label, order: entry.options.order ?? 0 }) + } + return rows.sort((a, b) => a.order - b.order).map(({ id, label }) => ({ id, label })) +} + +/** + * Observable section roster: recomputed when the section list's ledger or + * the active locale changes, and identity-stable between changes. + * @param ctx - client context whose slot registry and locale the roster follows. + * @returns the section source. + */ +export function sectionSource(ctx: ClientContext): ObservableSnapshot { + let version = -1 + let revision = -1 + let sections: readonly SessionPanelSectionEntry[] = [] + return { + getSnapshot: () => { + const nextVersion = ctx.slots.getVersion(SECTION_SLOT) + const nextRevision = ctx.locale.getSnapshot().revision + if (nextVersion !== version || nextRevision !== revision) { + const reportOnce = version !== nextVersion + version = nextVersion + revision = nextRevision + sections = projectSections(ctx.slots.entriesOfSlot(SECTION_SLOT), (message) => { + if (reportOnce) console.error(message) + }) + } + return sections + }, + subscribe: (listener) => { + const offLedger = ctx.slots.subscribe(SECTION_SLOT, listener) + const offLocale = ctx.locale.subscribe(listener) + return () => { + offLedger() + offLocale() + } + }, + } +} diff --git a/packages/client/ui-session-panel/src/client/slots.ts b/packages/client/ui-session-panel/src/client/slots.ts new file mode 100644 index 0000000000..67eb471b26 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/slots.ts @@ -0,0 +1,226 @@ +/** Session panel slot declarations and composed component props. */ +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { + InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, +} from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { StateDotState } from '@deepseek-ai/dsh-client-ui-primitives' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-chat/client' +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type { NS } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** + * Sections of the Session panel. `id` addresses the section, `order` sorts + * the sections ascending, and the required `label` is the section title, + * which the panel draws. A section with nothing to show renders nothing, + * and the panel hides its title with it. + */ + 'conversation.session.panel.section': { + kind: 'list' + scope: 'session' + owner: SessionPanelSectionOwnerProps + } + /** Trailing controls of one section title, keyed by the section's `id`. */ + 'conversation.session.panel.section.actions': { kind: 'keyed'; scope: 'session' } + /** + * Marks over the panel toggle, such as an attention dot. Each occupant is + * one element: the toggle sizes it to a 6px dot at the glyph's corner, and + * the occupant sets its `background` and includes text that names it for + * assistive technology, which becomes part of the toggle's name. Occupants + * overlap, and a higher `order` paints above a lower one. An occupant that + * only repeats what the panel shows renders nothing while `panelShown`. + */ + 'conversation.session.panel.indicator': { + kind: 'list' + scope: 'session' + inline: true + owner: SessionPanelIndicatorOwnerProps + } + /** Rows of the built-in Environment section in ascending `order`; they receive the section's owner values. */ + 'conversation.session.panel.environment.row': { kind: 'list'; scope: 'session'; owner: SessionPanelSectionOwnerProps } + } + interface SlotFactoryMap { + /** + * The fold control of a panel list. A list shows at most five rows of a + * group and then this control as its last row, which shows the rest or + * folds them again; a list folds only when that hides two rows or more, + * since the control takes a row itself. The list keeps the fold state and + * decides which rows show. + */ + 'conversation.session.panel.fold': { scope: 'root'; props: PanelFoldProps } + /** + * The details of one panel row, for the content of the row's HoverCard: the + * row's full name, secondary lines such as its owner, its state, and its + * measures. A row whose single line clips or leaves these out shows them + * here. + */ + 'conversation.session.panel.details': { scope: 'root'; props: PanelDetailsProps } + } +} + +/** What a panel row's hover card says about the row. */ +export interface PanelDetailsProps { + /** + * The full name of what the row shows; it wraps instead of clipping. Omit it + * when the name can run long, such as a command, and the row's own view + * shows it in full. + */ + readonly title?: string | undefined + /** Lines in secondary type under the title, such as the owner; each stops after six lines. */ + readonly lines?: readonly string[] | undefined + /** The state, after its dot. */ + readonly status?: { readonly state: StateDotState; readonly label: string } | undefined + /** Measures on one line, at most one of each kind. */ + readonly facts?: readonly PanelDetailsFact[] | undefined +} + +/** One measure in a panel row's hover card. */ +export interface PanelDetailsFact { + /** What the measure counts, which selects its icon: a database for `tokens`, a clock for `duration`. */ + readonly kind: 'tokens' | 'duration' + /** The measure as the card shows it, such as "3.3M tok" or "6m 56s". */ + readonly label: string +} + +/** Props of the fold control that ends a folded panel list. */ +export interface PanelFoldProps { + /** Whether the list shows every row; the control then folds it again. */ + readonly expanded: boolean + /** Visible text for the current state, such as "Show 14 more" or "Show less". */ + readonly label: string + /** Accessible name for the current state; it starts with `label` and names what the list holds. */ + readonly name: string + /** Show every row, or fold the list again. */ + readonly onToggle: () => void +} + +/** How the panel currently shows. */ +export type SessionPanelPresentation = + /** Beside the transcript in the Chat View's end gutter. */ + | 'docked' + /** Over the transcript, opened from the toggle while the gutter is too narrow. */ + | 'overlay' + +/** Values every section receives from the panel. */ +export interface SessionPanelSectionOwnerProps { + /** Current presentation; sections may lower their density in the overlay. */ + readonly presentation: SessionPanelPresentation + /** Close the overlay, for example after a row opened another surface; no effect while docked. */ + readonly dismissOverlay: () => void +} + +/** Values every toggle indicator receives from the toggle. */ +export interface SessionPanelIndicatorOwnerProps { + /** Whether the panel shows, docked or as an overlay. */ + readonly panelShown: boolean +} + +/** One section the panel draws, projected from the section list's registrations. */ +export interface SessionPanelSectionEntry { + /** Registration id. */ + readonly id: string + /** Localized title. */ + readonly label: string +} + +/** Panel visibility shared by the toggle and the panel. */ +export interface SessionPanelVisibility { + /** Whether the panel docks while the gutter has room; persisted across reloads. */ + readonly pinned: boolean + /** Session whose overlay is open, or null. */ + readonly overlay: SessionId | null +} + +/** + * Whether each Session whose Chat View holds a panel has room to dock it: + * true when the end gutter of at least one of its Chat Views holds the docked + * panel. A Session without an entry shows no Chat View. + */ +export type SessionPanelDockable = ReadonlyMap + +/** + * Whether the end gutter of each mounted panel's Chat View holds the docked + * panel, by the id the panel gave its dock probe. + */ +export type SessionPanelProbes = ReadonlyMap + +/** Business face of the header toggle. */ +export interface SessionPanelToggleInjected { + /** Shared visibility and each Session's room to dock; the renderer binds them as `useVisibility` and `useDockable`. */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly dockable: ObservableSnapshot + } + /** + * Show or hide the panel. With room to dock this flips the docking + * preference and closes any overlay; otherwise it opens or closes the + * Session's overlay. No effect while no Chat View shows the Session. + * @param sessionId - Session whose header holds the toggle. + */ + readonly toggle: (sessionId: SessionId) => void +} + +/** Business face of the panel. */ +export interface SessionPanelInjected { + /** + * Shared visibility, the projected section roster, and each dock probe's + * room; the renderer binds them as `useVisibility`, `useSections`, and `useProbes`. + */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly sections: ObservableSnapshot + readonly probes: ObservableSnapshot + } + /** + * Create the ref of one mounted panel's dock probe, the element whose + * stylesheet width says whether the Chat View's end gutter holds the docked + * panel. The plugin observes the element while it is attached and records + * the probe's room under `probe`, and the Session's for the toggle. + * @param sessionId - Session the panel's Chat View shows. + * @param probe - identity of the panel within the page. + * @returns the ref callback for the probe element; detaching withdraws the probe. + */ + readonly createProbeRef: (sessionId: SessionId, probe: string) => (element: HTMLElement | null) => void + /** + * Close the Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays. + */ + readonly closeOverlay: (sessionId: SessionId) => void +} + +/** Business face of the project row. */ +export interface ProjectRowInjected { + /** Host facts from the connection's ready frame; the renderer binds them as `useHost`. */ + readonly hooks: { readonly host: ObservableSnapshot } +} + +/** Full props of the header toggle. */ +export type SessionPanelToggleProps = + PropsRuntime<'conversation.session.header.utilities'> + & PropsRenderSlots<'conversation.session.panel.indicator'> + & InjectFace + & PropsLocale + +/** Full props of the panel. */ +export type SessionPanelProps = + PropsRuntime<'conversation.chat.aside'> + & PropsRenderSlots<'conversation.session.panel.section' | 'conversation.session.panel.section.actions'> + & InjectFace + & PropsLocale + +/** Full props of the built-in Environment section. */ +export type EnvironmentSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderSlots<'conversation.session.panel.environment.row'> + +/** Full props of the project row. */ +export type ProjectRowProps = + PropsRuntime<'conversation.session.panel.environment.row'> + & PropsRenderFactories + & InjectFace + & PropsLocale diff --git a/packages/client/ui-session-panel/src/client/visibility.ts b/packages/client/ui-session-panel/src/client/visibility.ts new file mode 100644 index 0000000000..2e4b036036 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/visibility.ts @@ -0,0 +1,188 @@ +/** Session panel visibility: the persisted docking preference, the transient overlay, the dock probes, and the presentation. */ +import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionPanelDockable, SessionPanelPresentation, SessionPanelProbes, SessionPanelVisibility } from './slots.ts' + +/** localStorage key of the docking preference. */ +export const PINNED_STORAGE_KEY = 'dsh.sessionPanel.pinned' + +const NO_SESSIONS: SessionPanelDockable = new Map() +const NO_PROBES: SessionPanelProbes = new Map() + +/** + * Decide how the panel shows for one Session. + * @param fits - whether the gutter can hold the docked panel. + * @param visibility - shared visibility state. + * @param sessionId - Session whose panel is decided. + * @returns the presentation, or `hidden` when the panel renders nothing. + */ +export function presentationOf( + fits: boolean, visibility: SessionPanelVisibility, sessionId: SessionId, +): SessionPanelPresentation | 'hidden' { + if (fits) return visibility.pinned ? 'docked' : 'hidden' + return visibility.overlay === sessionId ? 'overlay' : 'hidden' +} + +/** + * Visibility shared by every Session's toggle and panel, and whether each + * mounted panel and each Session has room to dock. The panel's stylesheet + * decides the room: each mounted panel renders a dock probe that is 1px wide + * while its Chat View's end gutter holds the docked panel and 0 otherwise, + * and this state observes only that probe, so it hears the decision flip + * and nothing while the window resizes on one side of it or the transcript + * grows. Docking follows one preference for all Sessions; at most one + * Session's overlay is open, and it closes once its Session has room to dock + * or no Chat View shows that Session any longer. + */ +export class SessionPanelState { + // A stored value other than `false` keeps the default: the panel docks. + private readonly pinned = createSnapshotStore(true, { persist: { name: PINNED_STORAGE_KEY } }) + private readonly overlay = createSnapshotStore(null) + private readonly room = createSnapshotStore(NO_SESSIONS) + private readonly fits = createSnapshotStore(NO_PROBES) + /** The Session of every attached probe. */ + private readonly owners = new Map() + /** Stops observing each attached probe. */ + private readonly detachers = new Set<() => void>() + private current: SessionPanelVisibility = { pinned: this.pinned.getSnapshot() !== false, overlay: null } + /** Stops following the open overlay's gutter. */ + private unfollow: () => void = () => {} + + /** Combined visibility; the snapshot keeps its identity until a member changes. */ + readonly visibility: ObservableSnapshot = { + getSnapshot: () => { + const pinned = this.pinned.getSnapshot() !== false + const overlay = this.overlay.getSnapshot() + if (pinned !== this.current.pinned || overlay !== this.current.overlay) this.current = { pinned, overlay } + return this.current + }, + subscribe: (listener) => { + const offPinned = this.pinned.subscribe(listener) + const offOverlay = this.overlay.subscribe(listener) + return () => { + offPinned() + offOverlay() + } + }, + } + + /** + * Whether each Session with a mounted panel has room to dock it: true while + * any of its probes does. The snapshot keeps its identity until a Session + * gains or loses its entry or its room changes. + */ + readonly dockable: ObservableSnapshot = this.room + + /** + * Whether each attached probe's gutter holds the docked panel. The snapshot + * keeps its identity until a probe attaches, detaches, or flips. + */ + readonly probes: ObservableSnapshot = this.fits + + /** + * Create the element-ref lifecycle of one mounted panel's dock probe. + * Attaching the element enters the probe without room and observes its + * size; a probe at least 1px wide has room. Detaching stops the + * observation and withdraws the probe. Without `ResizeObserver` the probe + * stays without room, so the panel shows only as an overlay. + * @param sessionId - Session the panel's Chat View shows. + * @param probe - identity of the panel within the page. + * @returns the ref callback for the probe element. + */ + createProbeRef(sessionId: SessionId, probe: string): (element: HTMLElement | null) => void { + let detach: (() => void) | undefined + return (element) => { + detach?.() + detach = element === null ? undefined : this.attach(sessionId, probe, element) + } + } + + /** + * Show or hide the panel from a Session's toggle. With room to dock this + * flips the docking preference and closes any overlay; otherwise it opens + * or closes the Session's overlay. No effect while no Chat View shows the Session. + * @param sessionId - Session whose header holds the toggle. + */ + toggle(sessionId: SessionId): void { + const dockable = this.room.getSnapshot().get(sessionId) + if (dockable === undefined) return + if (dockable) { + this.pinned.set(!this.visibility.getSnapshot().pinned) + this.setOverlay(null) + return + } + this.setOverlay(this.overlay.getSnapshot() === sessionId ? null : sessionId) + } + + /** + * Close a Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays open. + */ + closeOverlay(sessionId: SessionId): void { + if (this.overlay.getSnapshot() === sessionId) this.setOverlay(null) + } + + /** Stop following the open overlay's Session and stop observing every attached probe. */ + dispose(): void { + this.stopFollowing() + for (const detach of [...this.detachers]) detach() + } + + private stopFollowing(): void { + this.unfollow() + this.unfollow = () => {} + } + + private setOverlay(sessionId: SessionId | null): void { + this.stopFollowing() + this.overlay.set(sessionId) + if (sessionId === null) return + const check = (): void => { + if (this.room.getSnapshot().get(sessionId) !== false) this.closeOverlay(sessionId) + } + this.unfollow = this.room.subscribe(check) + } + + private attach(sessionId: SessionId, probe: string, element: HTMLElement): () => void { + this.report(sessionId, probe, false) + const measure: ResizeObserverCallback = (entries) => { + for (const entry of entries) this.report(sessionId, probe, entry.contentRect.width >= 1) + } + const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure) + observer?.observe(element) + const detach = (): void => { + // The ref callback and dispose may both detach; the first one withdraws the probe. + if (!this.detachers.delete(detach)) return + observer?.disconnect() + this.report(sessionId, probe, null) + } + this.detachers.add(detach) + return detach + } + + /** Record one probe's room, or its withdrawal, publishing only what changed. */ + private report(sessionId: SessionId, probe: string, dockable: boolean | null): void { + const fits = this.fits.getSnapshot() + if (fits.get(probe) !== (dockable ?? undefined)) { + const next = new Map(fits) + if (dockable === null) { + next.delete(probe) + this.owners.delete(probe) + } else { + next.set(probe, dockable) + this.owners.set(probe, sessionId) + } + this.fits.set(next) + } + let any: boolean | undefined + for (const [id, owner] of this.owners) { + if (owner === sessionId) any = any === true || this.fits.getSnapshot().get(id) === true + } + const room = this.room.getSnapshot() + if (room.get(sessionId) === any) return + const next = new Map(room) + if (any === undefined) next.delete(sessionId) + else next.set(sessionId, any) + this.room.set(next) + } +} diff --git a/packages/client/ui-session-panel/src/css-modules.d.ts b/packages/client/ui-session-panel/src/css-modules.d.ts new file mode 100644 index 0000000000..8811db1264 --- /dev/null +++ b/packages/client/ui-session-panel/src/css-modules.d.ts @@ -0,0 +1,4 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} diff --git a/packages/client/ui-session-panel/src/index.ts b/packages/client/ui-session-panel/src/index.ts new file mode 100644 index 0000000000..76ee1f0c6a --- /dev/null +++ b/packages/client/ui-session-panel/src/index.ts @@ -0,0 +1,9 @@ +/** + * Node half of the Session panel plugin. The browser half in `src/client/` + * owns every contribution; this entry exists so the package appears as an + * ordinary Loader row. + * @module @deepseek-ai/dsh-client-ui-session-panel + */ + +/** Loader-visible no-op body; the browser half carries the feature. */ +export function apply(): void {} diff --git a/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts new file mode 100644 index 0000000000..f909fdccca --- /dev/null +++ b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts @@ -0,0 +1,145 @@ +/** + * ui-session-panel plugin halves: the browser entry's dictionaries, fold + * control Factory, header toggle, panel, Environment section, and project row against the real + * SlotRegistry, the inject faces those entries receive, the section roster + * projection, fiber teardown removing every contribution (HMR safety), and + * the inert node entry. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { apply, inject } from '../src/client/index.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from '../src/client/slots.ts' +import { apply as applyNode } from '../src/index.ts' + +const SID = 'session-1' as SessionId + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** Boot the browser half over a real slot tree that declares the header utilities and the Chat aside. */ +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotRegistry).await() + ctx.slots.register({ + name: 'root', + children: { + 'conversation.session.header.utilities': { kind: 'list', scope: 'session' }, + 'conversation.chat.aside': { kind: 'single', scope: 'session' }, + }, + } as never, () => null) + const host = { home: '/Users/me', isLoopback: true } + ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never) + ctx.provide('remote', { $on: () => () => {}, $host: host } as never) + ctx.provide('configForms', { developerTools: { enabled: createSnapshotStore(true) }, get: () => stubConfigForm().scope } as never) + await ctx.plugin({ inject: localeInject, apply: applyLocale }).await() + ctx.locale.setLocale('zh') + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + return { ctx, fiber, host } +} + +/** Inject face of one registration, called for the test Session. */ +function faceOf(ctx: Context, slot: string, id: string | undefined): unknown { + const entry = ctx.slots.entries(slot as never).find(candidate => candidate.options.id === id) + const face = entry?.inject as ((sessionId: SessionId) => unknown) | undefined + if (face === undefined) throw new Error(`${slot} entry ${id ?? '(single)'} registered no inject face`) + return face(SID) +} + +describe('ui-session-panel browser half', () => { + it('declares the services it binds', () => { + expect(inject).toEqual(['slots', 'locale', 'remote']) + }) + + it('registers the fold control and row details Factories, the toggle first among the header utilities, the panel in the Chat aside, the Environment section, and the project row', async () => { + const { ctx } = await bench() + expect(ctx.slots.snapshot('factory:conversation.session.panel.fold')).toHaveLength(1) + expect(ctx.slots.snapshot('factory:conversation.session.panel.details')).toHaveLength(1) + const toggle = ctx.slots.entries('conversation.session.header.utilities').find(entry => entry.options.id === 'session-panel') + expect(toggle?.options.order).toBe(-10) + expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(1) + const section = ctx.slots.entries('conversation.session.panel.section').find(entry => entry.options.id === 'environment') + expect(section?.options.order).toBe(0) + expect(ctx.slots.entries('conversation.session.panel.environment.row').map(entry => entry.options.id)).toEqual(['project']) + }) + + it('hands the toggle the room to dock the panel tracks, and both the shared visibility', async () => { + const { ctx, fiber } = await bench() + const toggle = faceOf(ctx, 'conversation.session.header.utilities', 'session-panel') as SessionPanelToggleInjected + const panel = faceOf(ctx, 'conversation.chat.aside', undefined) as SessionPanelInjected + expect(toggle.hooks.visibility).toBe(panel.hooks.visibility) + const attach = panel.createProbeRef(SID, 'main') + // The node suite has no DOM or ResizeObserver; the probe enters without room and stays unobserved. + attach({} as HTMLElement) + expect(panel.hooks.probes.getSnapshot().get('main')).toBe(false) + expect(toggle.hooks.dockable.getSnapshot().get(SID)).toBe(false) + toggle.toggle(SID) + expect(panel.hooks.visibility.getSnapshot()).toEqual({ pinned: true, overlay: SID }) + panel.closeOverlay(SID) + expect(panel.hooks.visibility.getSnapshot().overlay).toBeNull() + toggle.toggle(SID) + // Disposing the plugin withdraws the probe and stops the open overlay from following the room to dock. + await fiber.dispose() + expect(toggle.hooks.dockable.getSnapshot().has(SID)).toBe(false) + attach(null) + expect(panel.hooks.visibility.getSnapshot().overlay).toBe(SID) + }) + + it('projects the section roster in the active locale and keeps it stable between changes', async () => { + const { ctx } = await bench() + const panel = faceOf(ctx, 'conversation.chat.aside', undefined) as SessionPanelInjected + const roster = panel.hooks.sections + const first = roster.getSnapshot() + expect(first).toEqual([{ id: 'environment', label: '环境' }]) + expect(roster.getSnapshot()).toBe(first) + const listener = vi.fn() + const off = roster.subscribe(listener) + ctx.locale.setLocale('en') + expect(listener).toHaveBeenCalled() + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + const dispose = ctx.slots.register({ name: 'conversation.session.panel.section', id: 'untitled', order: 5 }, () => null) + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + ctx.locale.setLocale('zh') + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + dispose() + off() + }) + + it('gives the project row the Host facts and follows connection resets', async () => { + const { ctx, host } = await bench() + const row = faceOf(ctx, 'conversation.session.panel.environment.row', 'project') as ProjectRowInjected + expect(row.hooks.host.getSnapshot()).toBe(host) + const listener = vi.fn() + const off = row.hooks.host.subscribe(listener) + ctx.emit('connection/reset' as never) + expect(listener).toHaveBeenCalledTimes(1) + off() + }) + + it('removes every contribution with the fiber (HMR safety)', async () => { + const { ctx, fiber } = await bench() + await fiber.dispose() + expect(ctx.slots.snapshot('factory:conversation.session.panel.fold')).toHaveLength(0) + expect(ctx.slots.snapshot('factory:conversation.session.panel.details')).toHaveLength(0) + expect(ctx.slots.entries('conversation.session.header.utilities')).toHaveLength(0) + expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(0) + expect(ctx.slots.entries('conversation.session.panel.section')).toHaveLength(0) + }) +}) + +describe('ui-session-panel node half', () => { + it('contributes no host behavior', () => { + expect(applyNode).not.toThrow() + }) +}) diff --git a/packages/client/ui-session-panel/tests/components.client.spec.tsx b/packages/client/ui-session-panel/tests/components.client.spec.tsx new file mode 100644 index 0000000000..81cf2211d5 --- /dev/null +++ b/packages/client/ui-session-panel/tests/components.client.spec.tsx @@ -0,0 +1,548 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { useRef, type ReactNode } from 'react' +import { useModalLayer } from '@deepseek-ai/dsh-client-ui-primitives' +import { bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { EnvironmentSection } from '../src/client/EnvironmentSection.tsx' +import { PanelDetails } from '../src/client/PanelDetails.tsx' +import { PanelFold } from '../src/client/PanelFold.tsx' +import { ProjectRow } from '../src/client/ProjectRow.tsx' +import { SessionPanel } from '../src/client/SessionPanel.tsx' +import { SessionPanelToggle } from '../src/client/SessionPanelToggle.tsx' +import type { + EnvironmentSectionProps, PanelDetailsProps, ProjectRowProps, SessionPanelDockable, SessionPanelProbes, SessionPanelProps, + SessionPanelSectionEntry, SessionPanelSectionOwnerProps, SessionPanelToggleProps, SessionPanelVisibility, +} from '../src/client/slots.ts' +import { SessionPanelState } from '../src/client/visibility.ts' +import { en, zh } from '../src/client/locales.ts' + +const SID = 'session-1' as SessionId +const t = makeTranslate(zh) as SessionPanelToggleProps['t'] +const DOCKED: SessionPanelVisibility = { pinned: true, overlay: null } + +function selectorOf(value: T) { + return (select: (current: T) => S): S => select(value) +} + +beforeEach(() => { + vi.stubGlobal('ResizeObserver', class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} + }) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true, addEventListener() {}, removeEventListener() {} }))) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +/** Whether a hovered anchor's tooltip shows before and at 500ms of hover. */ +function tooltipAfterHover(anchor: Element): { readonly early: boolean; readonly at500: boolean } { + vi.useFakeTimers() + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(499) }) + const early = screen.queryByRole('tooltip', { hidden: true }) !== null + act(() => { vi.advanceTimersByTime(1) }) + return { early, at500: screen.queryByRole('tooltip', { hidden: true }) !== null } +} + +describe('SessionPanelToggle', () => { + function toggleProps(dockable: boolean | undefined, visibility: SessionPanelVisibility, toggle = vi.fn()) { + const renderSlot = vi.fn(() => 需要处理) + const entries: SessionPanelDockable = new Map(dockable === undefined ? [] : [[SID, dockable]]) + const props = { + sessionId: SID, useDockable: selectorOf(entries), useVisibility: selectorOf(visibility), toggle, renderSlot, t, + } as SessionPanelToggleProps + return { props, toggle, renderSlot } + } + + it('names the panel together with its indicators and reports the docked panel as expanded', () => { + const { props, renderSlot } = toggleProps(true, DOCKED) + render() + const button = screen.getByRole('button', { name: '会话面板 需要处理' }) + expect(button.getAttribute('aria-expanded')).toBe('true') + expect(button.getAttribute('aria-controls')).toBe(`dsh-session-panel-${SID}`) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', { panelShown: true }) + }) + + it('flips docking with room to dock and opens the overlay without it', () => { + const wide = toggleProps(true, DOCKED) + render() + fireEvent.click(screen.getByRole('button')) + expect(wide.toggle).toHaveBeenCalledWith(SID) + cleanup() + const narrow = toggleProps(false, DOCKED) + render() + const button = screen.getByRole('button') + expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.hasAttribute('aria-controls')).toBe(false) + fireEvent.click(button) + expect(narrow.toggle).toHaveBeenCalledWith(SID) + }) + + it('reports an open overlay as expanded', () => { + const { props } = toggleProps(false, { pinned: false, overlay: SID }) + render() + expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('true') + }) + + it('tells its indicators whether the panel shows', () => { + const { props, renderSlot } = toggleProps(false, DOCKED) + render() + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', { panelShown: false }) + }) + + it('shows its tooltip after 500ms of hover', () => { + const { props } = toggleProps(true, DOCKED) + render() + expect(tooltipAfterHover(screen.getByRole('button'))).toEqual({ early: false, at500: true }) + }) + + it('is unavailable and says why while no Chat View shows the Session', () => { + const { props } = toggleProps(undefined, { pinned: true, overlay: SID }) + render() + const button = screen.getByRole('button') + expect(button.getAttribute('aria-disabled')).toBe('true') + expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.hasAttribute('aria-controls')).toBe(false) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(button) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('切换到「对话」视图后可显示会话面板') + }) +}) + +describe('SessionPanel', () => { + const SECTIONS: readonly SessionPanelSectionEntry[] = [ + { id: 'environment', label: '环境' }, + { id: 'change-requests', label: '变更请求' }, + ] + + /** Ids of the probes the rendered panels created, so a later props object answers for the mounted panel. */ + const probeIds = new Set() + afterEach(() => { probeIds.clear() }) + + /** Panel props whose dock probes all have, or all lack, room to dock. */ + function panelProps(dockable: boolean, visibility: SessionPanelVisibility, closeOverlay = vi.fn()) { + const owners: SessionPanelSectionOwnerProps[] = [] + const renderSlot = ((key: string, owner: object, opts?: { only?: string; entryKey?: string }): ReactNode => { + if (key === 'conversation.session.panel.section.actions') { + return opts?.entryKey === 'change-requests' ? : null + } + owners.push(owner as SessionPanelSectionOwnerProps) + return

      {`${opts?.only ?? ''} body`}

      + }) as SessionPanelProps['renderSlot'] + const attached = vi.fn<(element: HTMLElement | null) => void>() + const createProbeRef = vi.fn((_sessionId: SessionId, probe: string) => { + probeIds.add(probe) + return attached + }) + const props = { + sessionId: SID, + useVisibility: selectorOf(visibility), + useSections: selectorOf(SECTIONS), + useProbes: (select: (probes: SessionPanelProbes) => S): S => select(new Map([...probeIds].map(id => [id, dockable]))), + createProbeRef, + closeOverlay, + renderSlot, + t, + } as SessionPanelProps + return { props, owners, closeOverlay, createProbeRef, attached } + } + + it('attaches its dock probe through the injected ref once and detaches it on unmount', () => { + const { props, createProbeRef, attached } = panelProps(true, DOCKED) + const view = render() + const probe = view.container.querySelector('[data-session-panel-probe]') + expect(probe).not.toBeNull() + expect(createProbeRef.mock.calls).toEqual([[SID, expect.any(String)]]) + expect(attached.mock.calls).toEqual([[probe]]) + // A later render keeps the ref, so the probe is neither detached nor attached again. + const next = panelProps(true, DOCKED) + view.rerender() + expect(next.createProbeRef).not.toHaveBeenCalled() + expect(attached).toHaveBeenCalledTimes(1) + view.unmount() + expect(attached.mock.calls.at(-1)).toEqual([null]) + }) + + it('renders again only when its dock probe flips', () => { + const observed: { readonly element: Element; readonly callback: ResizeObserverCallback }[] = [] + vi.stubGlobal('ResizeObserver', class { + private readonly callback: ResizeObserverCallback + constructor(callback: ResizeObserverCallback) { this.callback = callback } + observe(element: Element): void { observed.push({ element, callback: this.callback }) } + unobserve(): void {} + disconnect(): void {} + }) + const state = new SessionPanelState() + const base = panelProps(false, DOCKED) + const props = { + ...base.props, + useProbes: bindSnapshotSelector(state.probes), + createProbeRef: (sessionId: SessionId, probe: string) => state.createProbeRef(sessionId, probe), + } as SessionPanelProps + const view = render() + const resize = (width: number): void => { + act(() => { + for (const { element, callback } of observed) { + callback([{ target: element, contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver) + } + }) + } + expect(observed.map(entry => entry.element)).toEqual([view.container.querySelector('[data-session-panel-probe]')]) + expect(screen.queryByRole('complementary')).toBeNull() + expect(state.dockable.getSnapshot().get(SID)).toBe(false) + resize(1) + expect(screen.getByRole('complementary').getAttribute('data-session-panel')).toBe('docked') + // CSS sizes the docked panel; no measured width reaches its style. + expect(screen.getByRole('complementary').getAttribute('style')).toBeNull() + const settled = base.owners.length + resize(1) + expect(base.owners).toHaveLength(settled) + // A probe under 1px wide sits within a pixel below the gutter that docks the panel. + resize(0.5) + expect(screen.queryByRole('complementary')).toBeNull() + expect(state.dockable.getSnapshot().get(SID)).toBe(false) + view.unmount() + expect(state.dockable.getSnapshot().has(SID)).toBe(false) + }) + + it('renders only its dock probe while hidden', () => { + const { props } = panelProps(true, { pinned: false, overlay: null }) + const view = render() + expect(view.container.querySelector('[data-session-panel]')).toBeNull() + expect(view.container.children).toHaveLength(1) + expect(view.container.firstElementChild?.hasAttribute('data-session-panel-probe')).toBe(true) + }) + + it('docks with one titled region per section in roster order and each section body', () => { + const { props, owners } = panelProps(true, DOCKED) + render() + const panel = screen.getByRole('complementary', { name: '会话面板' }) + expect(panel.getAttribute('data-session-panel')).toBe('docked') + expect(panel.id).toBe(`dsh-session-panel-${SID}`) + const regions = screen.getAllByRole('region') + expect(regions.map(region => region.getAttribute('aria-labelledby'))).toEqual([ + `dsh-session-panel-${SID}-environment`, `dsh-session-panel-${SID}-change-requests`, + ]) + expect(screen.getByRole('heading', { name: '变更请求' })).toBeTruthy() + expect(screen.getByText('environment body')).toBeTruthy() + expect(screen.getByRole('button', { name: '刷新' })).toBeTruthy() + expect(owners.every(owner => owner.presentation === 'docked')).toBe(true) + }) + + it('closes the overlay on Escape from inside and returns focus to the toggle', () => { + const { props, owners, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + document.body.append(toggle) + try { + render() + const panel = screen.getByRole('complementary') + expect(panel.getAttribute('data-session-panel')).toBe('overlay') + fireEvent.keyDown(document, { key: 'Enter' }) + expect(closeOverlay).not.toHaveBeenCalled() + screen.getByRole('button', { name: '刷新' }).focus() + fireEvent.keyDown(document.activeElement as Element, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(toggle) + owners[0]?.dismissOverlay() + expect(closeOverlay).toHaveBeenCalledTimes(2) + } finally { + toggle.remove() + } + }) + + it('closes the overlay on Escape from the page without moving focus', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + render() + const outside = document.createElement('input') + document.body.append(outside) + try { + outside.focus() + fireEvent.keyDown(outside, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(outside) + } finally { + outside.remove() + } + }) + + it('closes the overlay on an outside pointerdown but not on the panel, the toggle, or an open menu', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + const menu = document.createElement('div') + menu.setAttribute('role', 'menu') + const item = document.createElement('button') + menu.append(item) + document.body.append(toggle, menu) + try { + render() + fireEvent.pointerDown(screen.getByText('environment body')) + fireEvent.pointerDown(toggle) + fireEvent.pointerDown(item) + expect(closeOverlay).not.toHaveBeenCalled() + fireEvent.pointerDown(document.body) + expect(closeOverlay).toHaveBeenCalledWith(SID) + } finally { + toggle.remove() + menu.remove() + } + }) + + it('leaves Escape to other handlers while docked, after another handler took it, or behind a modal', () => { + const docked = panelProps(true, DOCKED) + render() + fireEvent.keyDown(document, { key: 'Escape' }) + fireEvent.pointerDown(document.body) + expect(docked.closeOverlay).not.toHaveBeenCalled() + cleanup() + const overlay = panelProps(false, { pinned: true, overlay: SID }) + render() + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) + event.preventDefault() + document.dispatchEvent(event) + expect(overlay.closeOverlay).not.toHaveBeenCalled() + // A modal opened over the overlay registers its Escape after the panel's, so the panel sees it first. + function Modal() { + const dialog = useRef(null) + useModalLayer(dialog, true, () => {}) + return
      + } + const modal = render() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(overlay.closeOverlay).not.toHaveBeenCalled() + modal.unmount() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(overlay.closeOverlay).toHaveBeenCalledWith(SID) + }) + + it('leaves Escape to an input method composing text, including the key that ends the composition', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + render() + fireEvent(document, new Event('compositionstart')) + fireEvent.keyDown(document, { key: 'Escape', isComposing: true }) + fireEvent(document, new Event('compositionend')) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(closeOverlay).not.toHaveBeenCalled() + fireEvent.keyUp(document, { key: 'Escape' }) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + }) + + it('hands focus to the toggle when the panel hides with the keyboard inside it', () => { + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + const outside = document.createElement('button') + document.body.append(toggle, outside) + try { + const docked = panelProps(true, DOCKED) + const view = render() + const control = screen.getByRole('button', { name: '刷新' }) + control.focus() + // Moves within the panel, and blurs that name no next target, keep the keyboard inside. + fireEvent.focusOut(control, { relatedTarget: screen.getByRole('complementary') }) + fireEvent.focusOut(control, { relatedTarget: null }) + view.rerender() + expect(document.activeElement).toBe(toggle) + // Focus that already left the panel stays where it went. + view.rerender() + screen.getByRole('button', { name: '刷新' }).focus() + outside.focus() + view.rerender() + expect(document.activeElement).toBe(outside) + // A panel that hides without having held focus moves nothing. + view.rerender() + view.rerender() + expect(document.activeElement).toBe(outside) + } finally { + toggle.remove() + outside.remove() + } + }) +}) + +describe('EnvironmentSection', () => { + it('renders its rows straight into the section body with the section owner values', () => { + const renderSlot = vi.fn(() => row) + const dismissOverlay = vi.fn<() => void>() + render(<>{EnvironmentSection({ presentation: 'overlay', dismissOverlay, renderSlot } as Pick as EnvironmentSectionProps)}) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.environment.row', { presentation: 'overlay', dismissOverlay }) + expect(screen.getByText('row')).toBeTruthy() + }) +}) + +describe('ProjectRow', () => { + function rowProps(over: { + workingDirectory?: string | null + workspacePath?: string + cwd?: string + home?: string + }, open = vi.fn()) { + const renderFactorySlot = vi.fn((_name: string, input: { label: string }) => ) + const props = { + sessionId: SID, + useProjection: (key: string) => key === 'workingDirectory' ? over.workingDirectory : undefined, + useWorkspaces: selectorOf({ + items: over.workspacePath === undefined ? [] : [{ path: over.workspacePath, sessionIds: [SID] }], + }), + useSessions: selectorOf({ byId: over.cwd === undefined ? {} : { [SID]: { cwd: over.cwd } } }), + useHost: selectorOf({ home: over.home, isLoopback: true }), + useContextMenu: contextMenuHook(open), + renderFactorySlot, + t, + } as ProjectRowProps + return { props, renderFactorySlot, open } + } + + function folderOf(container: HTMLElement): { name: string | null; parent: string | null } { + const folder = container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement + const [name, parent] = [...folder.children] + return { name: name?.textContent ?? null, parent: parent?.textContent ?? null } + } + + it('shows the working directory as its name and parent folder, with the label and full path in the tooltip', () => { + const { props, renderFactorySlot } = rowProps({ + workingDirectory: '/Users/me/projects/app/.worktrees/fix', + cwd: '/Users/me/projects/app', + workspacePath: '/Users/me/projects/app', + home: '/Users/me', + }) + const view = render() + expect(folderOf(view.container)).toEqual({ name: 'fix', parent: '~/projects/app/.worktrees' }) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('工作目录\n~/projects/app/.worktrees/fix') + fireEvent.blur(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement) + expect(tooltipAfterHover(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement)) + .toEqual({ early: false, at500: true }) + expect(renderFactorySlot).toHaveBeenCalledWith('contextMenu.button', expect.objectContaining({ + target: { kind: 'directory', value: { sessionId: SID, path: '/Users/me/projects/app/.worktrees/fix' } }, + label: '工作目录操作', + })) + expect(renderFactorySlot.mock.calls[0]?.[1]).not.toHaveProperty('size') + expect(screen.getByRole('button', { name: '工作目录操作' })).toBeTruthy() + }) + + it('marks its parts for the panel\'s row rules: icon and folder in the body, then the More button as the row menu', () => { + const view = render() + const row = view.container.querySelector('[data-session-panel-row]') as HTMLElement + expect(row.hasAttribute('data-session-panel-project')).toBe(true) + expect([...row.children].map(part => part.getAttribute('data-row-part'))).toEqual(['body', 'menu']) + const [body, menu] = [...row.children] as [HTMLElement, HTMLElement] + expect(body.tagName).toBe('SPAN') + expect([...body.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content']) + expect(body.children[0]?.getAttribute('aria-hidden')).toBe('true') + expect(body.children[1]?.textContent).toBe('app/srv') + expect(menu.querySelector('button')?.textContent).toBe('工作目录操作') + }) + + it('falls back to the directory the Session was created in and opens the directory menu on right-click', () => { + const { props, open } = rowProps({ cwd: '/srv/app', workspacePath: '/srv' }) + const view = render() + expect(folderOf(view.container)).toEqual({ name: 'app', parent: '/srv' }) + fireEvent.contextMenu(view.container.querySelector('[data-session-panel-project]') as HTMLElement) + expect(open).toHaveBeenCalledWith({ kind: 'directory', value: { sessionId: SID, path: '/srv/app' } }, expect.anything()) + }) + + it('falls back to the listing Workspace when no directory is recorded, keeping a root parent and omitting an absent one', () => { + const atRoot = render() + expect(folderOf(atRoot.container)).toEqual({ name: 'srv', parent: '/' }) + atRoot.unmount() + const atHome = render() + expect(folderOf(atHome.container)).toEqual({ name: '~', parent: null }) + }) + + it('renders nothing before the Session directory is known', () => { + const { props } = rowProps({}) + const view = render() + expect(view.container.innerHTML).toBe('') + }) +}) + +describe('PanelFold', () => { + type FoldProps = FactoryComponentPropsOf<'conversation.session.panel.fold'> + + /** Render the control with the props a list passes; the renderer's standard seats are left out, as the control reads none. */ + function fold(expanded: boolean) { + const onToggle = vi.fn<() => void>() + const props = { + expanded, onToggle, + label: expanded ? 'Show less' : 'Show 14 more', + name: expanded ? 'Show less (subagents)' : 'Show 14 more (subagents)', + } as Pick as FoldProps + const view = render() + return { onToggle, row: view.container.firstElementChild as HTMLElement } + } + + it('is a panel row whose body is the button, with a down chevron in the icon part while rows are held back', () => { + const { row, onToggle } = fold(false) + expect(row.getAttribute('data-session-panel-row')).toBe('fold') + expect([...row.children].map(part => `${part.tagName}:${part.getAttribute('data-row-part') ?? ''}`)).toEqual(['BUTTON:body']) + const button = screen.getByRole('button', { name: 'Show 14 more (subagents)' }) + expect(button.getAttribute('aria-expanded')).toBe('false') + expect([...button.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content']) + expect(button.children[0]?.getAttribute('aria-hidden')).toBe('true') + expect(button.querySelector('svg')?.getAttribute('data-icon')).toBe('dsw-icon-chevron-down-outline-regular') + expect(button.children[1]?.textContent).toBe('Show 14 more') + fireEvent.click(button) + expect(onToggle).toHaveBeenCalledOnce() + }) + + it('points the chevron up and reports expanded once the list shows every row', () => { + const { row } = fold(true) + const button = screen.getByRole('button', { name: 'Show less (subagents)' }) + expect(button.getAttribute('aria-expanded')).toBe('true') + expect(row.querySelector('svg')?.getAttribute('data-icon')).toBe('dsw-icon-chevron-up-outline-regular') + expect(row.querySelector('[data-row-part="content"]')?.textContent).toBe('Show less') + }) +}) + +describe('PanelDetails', () => { + /** Render the details with the props a row passes; the renderer's standard seats are left out, as the details read none. */ + function details(input: PanelDetailsProps): HTMLElement { + const view = render(} />) + return view.container.querySelector('[data-session-panel-details]') as HTMLElement + } + + it('stacks the title, lines, state, and measures in order, each measure after the icon of its kind', () => { + const root = details({ + title: 'Survey open-source harnesses', + lines: ['Owner: open-source-arch'], + status: { state: 'done', label: 'Completed' }, + facts: [{ kind: 'tokens', label: '3.3M tok' }, { kind: 'duration', label: '6m 56s' }], + }) + expect([...root.children].map(child => child.textContent)) + .toEqual(['Survey open-source harnesses', 'Owner: open-source-arch', 'Completed', '3.3M tok6m 56s']) + expect(root.children[2]?.querySelector('[data-state="done"]')).not.toBeNull() + const facts = [...(root.children[3] as HTMLElement).children] + expect(facts.map(fact => [fact.getAttribute('data-fact'), fact.querySelector('svg')?.getAttribute('data-icon')])).toEqual([ + ['tokens', 'dsw-icon-database-outline-regular'], + ['duration', 'dsw-icon-clock-outline-regular'], + ]) + expect(facts.every(fact => fact.firstElementChild?.getAttribute('aria-hidden') === 'true')).toBe(true) + }) + + it('renders only the title when nothing else is given', () => { + expect(details({ title: 'sleep 30' }).children).toHaveLength(1) + }) + + it('starts with the lines when the title is omitted', () => { + const root = details({ lines: ['bash'], status: { state: 'ongoing', label: 'running' } }) + expect([...root.children].map(child => child.textContent)).toEqual(['bash', 'running']) + }) +}) + +describe('dictionaries', () => { + it('keeps the English dictionary key-identical to the Chinese source of truth', () => { + expect(Object.keys(en).sort()).toEqual(Object.keys(zh).sort()) + }) +}) diff --git a/packages/client/ui-session-panel/tests/sections.client.spec.ts b/packages/client/ui-session-panel/tests/sections.client.spec.ts new file mode 100644 index 0000000000..5500f97256 --- /dev/null +++ b/packages/client/ui-session-panel/tests/sections.client.spec.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest' +import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import { projectSections } from '../src/client/sections.ts' + +function entry(id: string, order: number | undefined, label: StoredEntry['options']['label'], registrant?: string): StoredEntry { + return { + component: () => null, + options: { id, ...order === undefined ? {} : { order }, ...label === undefined ? {} : { label } }, + ...registrant === undefined ? {} : { registrant }, + } +} + +describe('projectSections', () => { + it('orders sections by ascending order, keeping registration order for ties, and resolves locale thunks', () => { + const report = vi.fn() + const sections = projectSections([ + entry('later', 100, 'Change requests'), + entry('first', 0, () => 'Environment'), + entry('tie', 100, 'Outputs'), + entry('default', undefined, 'Default order'), + ], report) + expect(sections).toEqual([ + { id: 'first', label: 'Environment' }, + { id: 'default', label: 'Default order' }, + { id: 'later', label: 'Change requests' }, + { id: 'tie', label: 'Outputs' }, + ]) + expect(report).not.toHaveBeenCalled() + }) + + it('reports and leaves out a section that cannot be titled', () => { + const report = vi.fn() + const sections = projectSections([ + entry('untitled', 0, undefined, 'acme-plugin'), + entry('blank', 1, ''), + entry('titled', 2, 'Titled'), + ], report) + expect(sections).toEqual([{ id: 'titled', label: 'Titled' }]) + expect(report).toHaveBeenCalledTimes(2) + expect(report.mock.calls[0]?.[0]).toContain('"untitled" from acme-plugin') + expect(report.mock.calls[1]?.[0]).toContain('"blank" from an unknown registrant') + }) +}) diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts new file mode 100644 index 0000000000..fb87b56c88 --- /dev/null +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -0,0 +1,155 @@ +/** + * The Session panel's stylesheet as CSS text. jsdom has no layout, so the + * component suite cannot show that the dock probe is 1px wide exactly from + * the gutter that holds the docked panel, or that marked rows get one + * geometry; this reads the declarations and evaluates the docking ones for + * gutters around that boundary. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/client/SessionPanel.module.css', import.meta.url)), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, ' ') + +/** Declarations of the rule with exactly this selector list, with whitespace collapsed. */ +function declarationsOf(selector: string): Record { + const pattern = selector.split(',').map(part => part.trim().replace(/[.[\]():*+^$\\'=]/g, '\\$&')).join('\\s*,\\s*') + const rule = new RegExp(`(?:^|[{}])\\s*${pattern}\\s*\\{([^{}]*)\\}`).exec(css) + if (rule === null) throw new Error(`SessionPanel.module.css has no \`${selector}\` rule`) + const entries = (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean).map((part): [string, string] => { + const colon = part.indexOf(':') + return [part.slice(0, colon).trim(), part.slice(colon + 1).replace(/\s+/g, ' ').replace(/\( /g, '(').replace(/ \)/g, ')').trim()] + }) + return Object.fromEntries(entries) +} + +const px = (value: string | undefined): number => { + const match = /^(-?\d+(?:\.\d+)?)px$/.exec(value ?? '') + if (match === null) throw new Error(`not a px length: ${String(value)}`) + return Number(match[1]) +} + +describe('SessionPanel.module.css docking geometry', () => { + const metrics = declarationsOf('.panel, .dockProbe') + const clear = px(metrics['--panel-clear']) + const edge = px(metrics['--panel-edge']) + const minWidth = px(metrics['--panel-min-width']) + + it('derives the docked width and the dock probe from one set of metrics', () => { + expect([clear, edge, minWidth]).toEqual([40, 8, 300]) + const panel = declarationsOf('.panel') + expect(panel['right']).toBe('var(--panel-edge)') + expect(panel['width']).toBe( + 'clamp(var(--panel-min-width), calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge)), 360px)', + ) + const probe = declarationsOf('.dockProbe') + expect(probe['width']).toBe( + 'calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px)', + ) + expect(probe['max-width']).toBe('1px') + }) + + it('makes the probe 1px wide exactly from the gutter that holds the panel at its minimum width', () => { + // The declarations above, evaluated: a width below 0 is used as 0, and max-width caps the probe at 1px. + const probeWidth = (gutter: number): number => Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1)) + const dockedWidth = (gutter: number): number => Math.min(360, Math.max(minWidth, gutter - clear - edge)) + expect([probeWidth(0), probeWidth(347), probeWidth(347.5), probeWidth(348), probeWidth(900)]).toEqual([0, 0, 0.5, 1, 1]) + // At the first gutter that docks, the panel is at its minimum width and keeps both clearances. + expect(dockedWidth(348)).toBe(minWidth) + expect(348 - dockedWidth(348) - edge).toBe(clear) + expect([dockedWidth(377), dockedWidth(500)]).toEqual([329, 360]) + }) + + it('keeps the probe out of sight, out of the layout flow, and away from the pointer', () => { + expect(declarationsOf('.dockProbe')).toMatchObject({ + 'position': 'absolute', 'height': '0', 'visibility': 'hidden', 'pointer-events': 'none', + }) + }) + + it('floats the overlay narrower than the docked panel, at the same edge inset', () => { + expect(declarationsOf(".panel[data-session-panel='overlay']")['width']).toBe('min(280px, calc(100% - 2 * var(--panel-edge)))') + }) +}) + +describe('SessionPanel.module.css row rules', () => { + /** A rule for marked row markup: `.panel :where()`. */ + const row = (inner: string, tail = ''): Record => declarationsOf(`.panel :where(${inner})${tail}`) + + it('lays a marked row out as one 28px line with the icon and the menu on fixed columns', () => { + expect(row('[data-session-panel-row]')).toMatchObject({ + 'display': 'flex', 'align-items': 'center', 'gap': '8px', 'min-height': '28px', 'padding': '0 6px', + }) + expect(row("[data-session-panel-row] > [data-row-part='body']")).toMatchObject({ flex: '1 1 auto', height: '28px', gap: '8px' }) + // 6px of padding and half of the 16px box put the icon's center 14px from the row's start, and the menu's from its end. + expect(row("[data-session-panel-row] [data-row-part='icon']")).toMatchObject({ width: '16px', height: '16px', flex: 'none' }) + expect(row("[data-session-panel-row] > [data-row-part='menu']")).toMatchObject({ 'width': '16px', 'justify-content': 'center' }) + expect(row("[data-session-panel-row] [data-row-part='content']")).toMatchObject({ + 'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', + }) + }) + + it('grows a row with a detail line and keeps the icon level with the first line', () => { + const tall = "[data-session-panel-row] > [data-row-part='body']:has([data-row-part='detail'])" + expect(row(tall)).toEqual({ 'align-items': 'flex-start', 'height': 'auto', 'padding': '4px 0' }) + expect(row(`${tall} > [data-row-part='icon']`)).toEqual({ height: '20px' }) + expect(row("[data-session-panel-row] [data-row-part='lines']")).toMatchObject({ 'display': 'flex', 'flex-direction': 'column', 'min-width': '0' }) + expect(row("[data-session-panel-row] [data-row-part='detail']")).toMatchObject({ + 'color': 'var(--dsw-alias-label-tertiary)', 'font-size': '12px', 'line-height': '17px', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', + }) + // The two-line rules follow the one-line ones they adjust, since every rule for a part has the same specificity. + const order = (selector: string): number => { + const at = css.indexOf(`.panel :where(${selector}) {`) + expect(at).toBeGreaterThan(-1) + return at + } + expect(order(tall)).toBeGreaterThan(order("[data-session-panel-row] > button[data-row-part='body']")) + expect(order(`${tall} > [data-row-part='icon']`)).toBeGreaterThan(order("[data-session-panel-row] [data-row-part='icon']")) + }) + + it('makes a button body the action of the whole row and rings the row when it has keyboard focus', () => { + expect(row("[data-session-panel-row] > button[data-row-part='body']", '::after')).toMatchObject({ position: 'absolute', inset: '0' }) + expect(row("[data-session-panel-row] > [data-row-part='trailing'], [data-session-panel-row] > [data-row-part='menu']")) + .toMatchObject({ 'position': 'relative', 'z-index': '1' }) + expect(row("[data-session-panel-row]:has(> button[data-row-part='body']:focus-visible)")['outline-offset']).toBe('-2px') + }) + + it('gives a plain button in the menu a 24px target and a tertiary glyph without a fill', () => { + expect(row("[data-session-panel-row] > [data-row-part='menu']", ' button')).toMatchObject({ + width: '24px', height: '24px', margin: '-4px', background: 'transparent', color: 'var(--dsw-alias-label-tertiary)', + }) + }) + + it('highlights only a row with an action or a menu that renders something, and keeps an open menu and its row shown', () => { + const interactive = "[data-session-panel-row]:has(> button[data-row-part='body'], > [data-row-part='menu']:not(:empty))" + expect(row("[data-session-panel-row] > [data-row-part='menu']:empty")).toEqual({ display: 'none' }) + // Only an open control in the menu part keeps the row highlighted; an expanded body button does not. + expect(row("[data-session-panel-row]:has(> [data-row-part='menu'] [aria-expanded='true'])")) + .toEqual({ background: 'var(--dsw-alias-interactive-bg-hover)' }) + expect(css).not.toMatch(/:has\(\[aria-expanded='true'\]\)\)\s*\{\s*background/) + expect(row("[data-session-panel-row] > [data-row-part='menu']:has([aria-expanded='true'])")['opacity']).toBe('1') + // Hover rules stay inside the hover media query, where the menu hides until the row is hovered or focused. + const hover = /@media \(hover: hover\) \{([\s\S]*?)\n\}/.exec(css)?.[1] ?? '' + expect(hover).toContain(`.panel :where(${interactive}:hover)`) + expect(hover).toMatch(/\[data-row-part='menu'\]\) \{\s*opacity: 0;/) + expect(css.replace(/@media \(hover: hover\) \{[\s\S]*?\n\}/g, '')).not.toContain(':hover') + }) + + it('sets a fold control in the quiet type of the section counts with a 14px chevron, darker on hover and keyboard focus', () => { + const fold = "[data-session-panel-row='fold']" + expect(row(fold)).toEqual({ + 'color': 'var(--dsw-alias-label-tertiary)', 'font': 'var(--dsw-font-xxs-12)', 'font-variant-numeric': 'tabular-nums', + }) + expect(row(`${fold} [data-row-part='icon']`, ' svg')).toEqual({ width: '14px', height: '14px' }) + expect(row(`${fold}:has(> button:focus-visible)`)).toEqual({ color: 'var(--dsw-alias-label-secondary)' }) + expect(row(`${fold}:hover`)).toEqual({ color: 'var(--dsw-alias-label-secondary)' }) + // The fold rules follow the row rules they adjust, since every rule for a part has the same specificity. + const at = (selector: string, tail = ''): number => { + const index = css.indexOf(`.panel :where(${selector})${tail} {`) + expect(index).toBeGreaterThan(-1) + return index + } + expect(at(fold)).toBeGreaterThan(at('[data-session-panel-row]')) + expect(at(`${fold} [data-row-part='icon']`, ' svg')).toBeGreaterThan(at("[data-session-panel-row] [data-row-part='icon']", ' svg')) + }) +}) diff --git a/packages/client/ui-session-panel/tests/visibility.client.spec.ts b/packages/client/ui-session-panel/tests/visibility.client.spec.ts new file mode 100644 index 0000000000..29ee583e7a --- /dev/null +++ b/packages/client/ui-session-panel/tests/visibility.client.spec.ts @@ -0,0 +1,263 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { PINNED_STORAGE_KEY, SessionPanelState, presentationOf } from '../src/client/visibility.ts' + +const A = 'session-a' as SessionId +const B = 'session-b' as SessionId + +/** What the stubbed ResizeObserver holds for each observed probe element. */ +interface Observation { + /** Deliver one size report for the element. */ + readonly report: (width: number) => void + /** Whether the observer was disconnected. */ + disconnected: boolean +} + +const observations = new Map() +let nextProbe = 0 + +beforeEach(() => { + localStorage.clear() + observations.clear() + vi.stubGlobal('ResizeObserver', class { + private readonly callback: ResizeObserverCallback + private readonly targets: Observation[] = [] + constructor(callback: ResizeObserverCallback) { this.callback = callback } + observe(element: Element): void { + const observation: Observation = { + report: (width) => { this.callback([{ target: element, contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver) }, + disconnected: false, + } + this.targets.push(observation) + observations.set(element, observation) + } + + unobserve(): void {} + disconnect(): void { for (const observation of this.targets) observation.disconnected = true } + }) +}) + +afterEach(() => { + localStorage.clear() + vi.unstubAllGlobals() +}) + +/** + * One mounted panel's dock probe: its id, a size report for its element, and + * its detachment, as the panel's ref drives them. + */ +function probeOf(state: SessionPanelState, sessionId: SessionId, width = 0) { + nextProbe += 1 + const id = `probe-${nextProbe}` + const element = document.createElement('span') + const ref = state.createProbeRef(sessionId, id) + ref(element) + const observation = observations.get(element) + if (observation === undefined) throw new Error('the probe element is not observed') + if (width > 0) observation.report(width) + return { id, element, observation, resize: observation.report, detach: () => { ref(null) } } +} + +/** A state whose Chat Views show `A` and `B` without room to dock. */ +function newState() { + const state = new SessionPanelState() + return { state, a: probeOf(state, A), b: probeOf(state, B) } +} + +describe('presentationOf', () => { + it.each([ + [true, true, null, 'docked'], + [true, true, A, 'docked'], + [true, false, null, 'hidden'], + [true, false, A, 'hidden'], + [false, true, null, 'hidden'], + [false, false, null, 'hidden'], + [false, true, A, 'overlay'], + [false, false, A, 'overlay'], + [false, true, B, 'hidden'], + ] as const)('fits=%s pinned=%s overlay=%s shows %s', (fits, pinned, overlay, expected) => { + expect(presentationOf(fits, { pinned, overlay }, A)).toBe(expected) + }) +}) + +describe('SessionPanelState dock probes', () => { + it('enters an attached probe without room and gives it room from 1px of width', () => { + const state = new SessionPanelState() + expect(state.probes.getSnapshot().size).toBe(0) + const probe = probeOf(state, A) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + // Within a pixel below the gutter that docks the panel the probe is narrower than 1px. + probe.resize(0.5) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + probe.resize(1) + expect(state.probes.getSnapshot().get(probe.id)).toBe(true) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + probe.resize(0) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + }) + + it('gives a Session room while any of its probes has it, and drops the Session once its last probe detaches', () => { + const state = new SessionPanelState() + const main = probeOf(state, A, 1) + const embedded = probeOf(state, A) + expect(state.probes.getSnapshot()).toEqual(new Map([[main.id, true], [embedded.id, false]])) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + main.detach() + expect(main.observation.disconnected).toBe(true) + expect(state.probes.getSnapshot()).toEqual(new Map([[embedded.id, false]])) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + embedded.resize(1) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + embedded.detach() + expect(state.dockable.getSnapshot().has(A)).toBe(false) + expect(state.probes.getSnapshot().size).toBe(0) + // A second detachment of the same element withdraws nothing more. + const before = state.dockable.getSnapshot() + embedded.detach() + expect(state.dockable.getSnapshot()).toBe(before) + }) + + it('publishes only when a probe flips or a Session changes its room', () => { + const state = new SessionPanelState() + const main = probeOf(state, A, 1) + const probes = state.probes.getSnapshot() + const dockable = state.dockable.getSnapshot() + let probeCalls = 0 + let sessionCalls = 0 + const offProbes = state.probes.subscribe(() => { probeCalls += 1 }) + const offSessions = state.dockable.subscribe(() => { sessionCalls += 1 }) + main.resize(1) + expect(state.probes.getSnapshot()).toBe(probes) + expect(state.dockable.getSnapshot()).toBe(dockable) + // A second Chat View without room changes the probes, not the Session's room. + const embedded = probeOf(state, A) + expect([probeCalls, sessionCalls]).toEqual([1, 0]) + main.resize(0) + expect([probeCalls, sessionCalls]).toEqual([2, 1]) + embedded.detach() + expect([probeCalls, sessionCalls]).toEqual([3, 1]) + offProbes() + offSessions() + }) + + it('keeps a probe without room where ResizeObserver is missing', () => { + vi.stubGlobal('ResizeObserver', undefined) + const state = new SessionPanelState() + const ref = state.createProbeRef(A, 'unobserved') + ref(document.createElement('span')) + expect(state.probes.getSnapshot().get('unobserved')).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + ref(null) + expect(state.dockable.getSnapshot().has(A)).toBe(false) + }) + + it('stops observing every attached probe on dispose, after which a detachment withdraws nothing', () => { + const { state, a, b } = newState() + state.dispose() + expect([a.observation.disconnected, b.observation.disconnected]).toEqual([true, true]) + expect(state.probes.getSnapshot().size).toBe(0) + expect(state.dockable.getSnapshot().size).toBe(0) + const before = state.probes.getSnapshot() + a.detach() + expect(state.probes.getSnapshot()).toBe(before) + }) +}) + +describe('SessionPanelState visibility', () => { + it('docks by default and keeps the snapshot identity until a member changes', () => { + const { state } = newState() + const first = state.visibility.getSnapshot() + expect(first).toEqual({ pinned: true, overlay: null }) + expect(state.visibility.getSnapshot()).toBe(first) + }) + + it('flips and persists the docking preference when the gutter has room, closing any overlay', () => { + const { state, a } = newState() + state.toggle(A) + expect(state.visibility.getSnapshot().overlay).toBe(A) + a.resize(1) + expect(state.visibility.getSnapshot().overlay).toBeNull() + state.toggle(A) + expect(state.visibility.getSnapshot()).toEqual({ pinned: false, overlay: null }) + expect(localStorage.getItem(PINNED_STORAGE_KEY)).toBe('false') + expect(new SessionPanelState().visibility.getSnapshot().pinned).toBe(false) + state.toggle(A) + expect(state.visibility.getSnapshot().pinned).toBe(true) + }) + + it('opens and closes one Session overlay without touching the docking preference', () => { + const { state } = newState() + state.toggle(A) + state.toggle(B) + expect(state.visibility.getSnapshot()).toEqual({ pinned: true, overlay: B }) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBe(B) + state.toggle(B) + expect(state.visibility.getSnapshot().overlay).toBeNull() + state.toggle(A) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBeNull() + }) + + it('ignores the toggle of a Session that no Chat View shows', () => { + const state = new SessionPanelState() + const before = state.visibility.getSnapshot() + state.toggle(A) + expect(state.visibility.getSnapshot()).toBe(before) + }) + + it('treats a stored value other than false as the default', () => { + localStorage.setItem(PINNED_STORAGE_KEY, '"yes"') + expect(newState().state.visibility.getSnapshot().pinned).toBe(true) + }) + + it('notifies subscribers of both members and stops after unsubscribe', () => { + const { state, a } = newState() + let calls = 0 + const off = state.visibility.subscribe(() => { calls += 1 }) + state.toggle(A) + a.resize(1) + state.toggle(A) + const seen = calls + expect(seen).toBeGreaterThanOrEqual(2) + off() + state.toggle(A) + expect(calls).toBe(seen) + }) + + it('closes an overlay once its gutter can dock the panel, without reopening it when the gutter narrows again', () => { + const { state, a } = newState() + state.toggle(A) + a.resize(0.5) + expect(state.visibility.getSnapshot().overlay).toBe(A) + a.resize(1) + expect(state.visibility.getSnapshot()).toEqual({ pinned: true, overlay: null }) + a.resize(0) + expect(presentationOf(false, state.visibility.getSnapshot(), A)).toBe('hidden') + }) + + it('closes an overlay once no Chat View shows its Session, so returning to it shows no overlay', () => { + const { state, a } = newState() + state.toggle(A) + a.detach() + expect(state.visibility.getSnapshot().overlay).toBeNull() + probeOf(state, A) + expect(presentationOf(false, state.visibility.getSnapshot(), A)).toBe('hidden') + }) + + it('follows only the open overlay, and nothing after dispose', () => { + const { state, a } = newState() + state.toggle(A) + state.toggle(B) + // A's Chat View no longer matters once B holds the overlay. + a.detach() + expect(state.visibility.getSnapshot().overlay).toBe(B) + // Dispose withdraws B's probe too, but nothing follows the overlay any longer. + state.dispose() + expect(state.dockable.getSnapshot().has(B)).toBe(false) + expect(state.visibility.getSnapshot().overlay).toBe(B) + }) +}) diff --git a/packages/client/ui-session-panel/tsconfig.json b/packages/client/ui-session-panel/tsconfig.json new file mode 100644 index 0000000000..e868af02be --- /dev/null +++ b/packages/client/ui-session-panel/tsconfig.json @@ -0,0 +1,66 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" + }, + { + "path": "../../api/workspace-controller/tsconfig.client.json" + }, + { + "path": "../connection/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-chat/tsconfig.client.json" + }, + { + "path": "../ui-context-menu" + }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-session" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../core/session" + }, + { + "path": "../../util/workspace-path" + }, + { + "path": "../../session/working-directory" + }, + { + "path": "../../workspace/workspace" + } + ] +} diff --git a/packages/client/ui-session-panel/tsdown.config.ts b/packages/client/ui-session-panel/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-session-panel/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index b7dd7357d5..217a3754e1 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -15,14 +15,14 @@ en: c26f81e8adf0128b zh: e11ab371f51f66bc /deepseek-ai-dsh-client-ui-settings-account/use-this-package: - en: 9e61a6adc39fddbc - zh: fbcb4852ca4eded1 + en: 51864317e5c33943 + zh: c0507f3448859ef0 /deepseek-ai-dsh-client-ui-settings-account/use-this-package/desktop-onboarding: - en: 7ae4e68f9491b068 - zh: f7478269bf8d28b3 + en: b17e3d33f66af025 + zh: 780f813205d955d9 /deepseek-ai-dsh-client-ui-settings-account/understand-the-implementation: - en: a0da9e739f2aa682 - zh: 27aa6d13dba6f4b4 + en: 916a0c6e3d735da9 + zh: 0310dca3463e2201 /deepseek-ai-dsh-client-ui-settings-account/further-exploration: en: f5ca95916ef486dc zh: 1e238d8299e0d838 diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index 0585faf254..5c212e17ff 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -28,6 +28,8 @@ A new account-model sign-in-required event displays “Model unavailable. Please ## Use this package +Settings, feedback and sign-in actions use 14px shared Regular icons with 1px strokes. The package-local logout icon uses the same size and fixed stroke weight without a separately positioned inner SVG. The sign-in dialog aligns the trailing edges of its close button and footer actions with a shared 24px inset. + Desktop and plain Web clients both mount the sidebar account launcher, Account settings, the sign-in step of model onboarding, and the account-state subscription. Desktop main opens the authorization page in the system browser. A plain Web client, identified by the absent Desktop preload bridge, sends `login_source` web with its own origin as the callback origin, preopens a tab during the sign-in click, navigates it to the authorization URL with the same `theme` parameter once its attempt receives one, and closes it on failure, expiry, or cancellation; a blocked popup leaves the copy-link route. Embedded Platform pages, Desktop onboarding, and the native device reader stay Desktop-only, so Web Platform links open new tabs. The sidebar and Account settings display circular profile images with diameters of 24px and 32px respectively. Both observe one browser image load and show the account icon while no URL is available, loading is pending, or loading failed. A rendered image failure updates the shared result, so both surfaces return to the icon and remain eligible for retry; reports from a superseded picture attempt are ignored. Each Settings entry, or return from a Settings or quota-notice top-up page, retries a failed image once even when its URL is unchanged; pending and successful loads are reused, and success updates both surfaces. A changed picture URL starts a new load; account-state replacement, sign-out, and plugin unload discard the previous picture and its callbacks. The collapsed sidebar centers the avatar in a 36 × 36 px button. Before sign-in the sidebar launcher shows a compact More row instead, leading with the ellipsis glyph and aligning its content and inset hover fill with navigation rows. Expanded buttons use border-box sizing: the signed-in row is 44px high including its 6px padding, and the signed-out More row is 32px high. The signed-in launcher retains its 24px avatar and 8px label gap and owns a 2px inline margin on its root; this inset does not move the Settings shell's adjacent status indicator horizontally. @@ -52,7 +54,7 @@ The account card’s More account information link has no underline and opens th Sign out first queries running account-token tasks and opens a confirmation dialog. The warning describes interruption when such tasks exist; otherwise it explains that data is retained and the account can be signed in again. Cancel, close, and Escape dismiss without signing out. Failed impact queries still open confirmation with an explicit unknown-task warning; failed sign-out keeps the dialog available for retry. -Account notification polling and presentation belong to [ui-account-notifications](../ui-account-notifications/README.md). The account menu positions the notification slot above its launcher inside the sidebar, keeps its DOM mounted while the rail hides it, and publishes account lifecycle and refresh events. +Account notification polling and presentation belong to [ui-account-notifications](../ui-account-notifications/README.md). The plugin fills the settings shell's `settings.notice` row above the launcher row with the notification slot, and publishes account lifecycle and refresh events. ### Desktop onboarding @@ -61,12 +63,12 @@ The Desktop preload marker enables the introduction after account credentials ar The welcome page requires Get started. The credit page always appears. A positive balance confirmed at first entry selects Continue as the primary action and Add credits as the secondary action. This choice stays fixed until the onboarding controller is recreated and is never persisted; late balance results cannot change the buttons. Only a confirmed absence of positive credit adds a confirmation before continuing without recharge; pending or failed queries do not block continuing. Purpose descriptions remain unchanged when selected. Returning from the native top-up view keeps the credit page and re-reads profile and balance in the background after any read already running, whether loading or payment succeeded. That read does not recompute the funded-mode choice, so a completed recharge leaves the buttons as first entered while continuing still evaluates the refreshed balance. Next confirms only a known zero balance; Skip uses the credit warning on the credit page and the setup warning on the question pages. Office-only use completes with compact presentation; development or both purposes also ask for process detail. Back preserves selections, and explicit skip from any supported step applies standard process, compact performance/usage, and disabled Coding Tools. This flow creates no workspace or demonstration task. -Access: the account stream, quota notice, settings launcher, account settings section, and models sign-in entry exist only while the current Peer may call `account/watch`; Desktop onboarding and the platform page are not gated. Losing that access discards the account reads that grant started, closes a pending authorization tab, and clears the account view, details, picture, and sign-in dialog state; a later grant shows the account section again once its first frame arrives. The owner always has access. +Access: the account stream, quota notice, settings launcher, notification row, account settings section, and models sign-in entry exist only while the current Peer may call `account/watch`; Desktop onboarding and the platform page are not gated. Losing that access discards the account reads that grant started, closes a pending authorization tab, and clears the account view, details, picture, and sign-in dialog state; a later grant shows the account section again once its first frame arrives. The owner always has access. ## Understand the implementation -The Account section appears first in Settings only while signed in; it is hidden before account state loads and after sign-out. The plugin owns one Host snapshot stream shared through framework hooks by settings.section and settings.launcher. The launcher opens Settings and offers Sign out only while an account credential is stored. Platform failures leave the menu available for retry. It maintains no independent credential state. +The Account section appears first in Settings only while signed in; it is hidden before account state loads and after sign-out. The plugin owns one Host snapshot stream shared through framework hooks by settings.section, settings.launcher, and settings.notice. The launcher opens Settings and offers Sign out only while an account credential is stored. Platform failures leave the menu available for retry. It maintains no independent credential state. The desktop controller writes progress to `ui-settings-account` through Host settings. Completion first applies `ui-chat.transcriptView` and `ui-chat.performanceUsage` together, then calls the shared Coding Tools preference to persist `ui-settings.enabled`, and finally saves the done marker; a rejected write keeps the flow available for retry. Successful completion reveals the workspace through a 180ms fade; choices and ordinary navigation preview immediately while writes run in order. A failed final queued write restores saved progress and allows retry. Completion waits for queued choices and retains the page until preferences persist; reduced motion skips the fade. Onboarding choices compact, standard, and detailed apply directly to the corresponding Chat work-detail modes. API-key entry and explicit skip select standard; onboarding does not select verbose. Complete Figma illustration layers ship as transparent, lossless 3× WebP [package assets](../AGENTS.md#dependency-declaration); welcome layers are merged with local sidebar blur; recharge uses a 70% opaque foreground window with local blur of the covered illustration, and headings use the bundled Montserrat brand font; English headings and descriptions use Light (300), except the DeepSeek Harness brand within headings uses Medium (500); card titles retain Regular (400) when selected. English footer navigation uses Light (300). Confirmed onboarding sets a 960px minimum window width and enlarges narrower windows; completion releases the minimum without restoring the previous size. Loading or already-completed onboarding does not resize the window. Empty footer navigation space passes pointer events through to the primary action. Cards exclude native window dragging and own the keyboard focus outline for their checkbox. The account package owns its onboarding overlay and control geometry. Each step and the confirmation dialog has a separate component; the flow coordinates navigation, transitions, and recharge. The overlay hides the workspace while initial account and progress state loads. Question headings and cards follow the Figma positions at 1440 × 920 and 960 × 600, independently of their action buttons. On macOS, the shell resets inherited window regions on each element, and a first-child drag band leaves an 8px native resize margin. The stage’s `data-window-drag-controls` scope excludes its interactive controls, later dialogs exclude their own boxes, and a native Platform page disables the underlying onboarding band. The upper workspace popup illustration has an opaque background in both languages and themes; the underlying sidebar omits its selected-row highlight. Welcome keeps its illustration at its original size, repositions and clips the artwork in narrow windows, and reveals the complete illustration on wide windows. The [historical onboarding decision](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md) owns persistence and presentation trade-offs. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 4ea576d157..7ea45f5067 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -28,6 +28,8 @@ kind: "package-reference" ## 使用此包 +设置、意见反馈和登录操作使用共享的 14px Regular 图标,描边为 1px。包内的退出登录图标采用相同的尺寸和固定描边粗细,无需单独定位内层 SVG。 登录弹窗的关闭按钮与底部操作按钮按外框右边缘对齐,共用 24px 内缩。 + Desktop 与普通 Web 客户端都挂载侧边栏账号菜单、账号设置、模型引导中的登录步骤,并订阅账号状态。Desktop 主进程在系统浏览器中打开授权页面。普通 Web 客户端(以缺少 Desktop preload 桥接识别)以 `login_source` web 发起登录,并以自身 origin 作为回调 origin;它在点击登录时预先打开一个标签页,本次尝试获得授权 URL 后带上相同的 `theme` 参数导航该标签页,并在失败、过期或取消时关闭它;弹窗被拦截时仍可使用复制链接。内嵌 Platform 页面、Desktop 引导和原生设备信息读取器仅在 Desktop 中提供,因此 Web 中的 Platform 链接在新标签页打开。 侧边栏和账号设置以正圆图片显示账号头像,直径分别为 24px 和 32px。两处共享一次浏览器图片加载,URL 缺失、加载中或加载失败时使用账号图标兜底。渲染图片失败时更新共享结果,两处一起恢复为图标,并保留重试机会;已被替换的图片加载尝试上报的失败会被忽略。每次进入设置,或从设置及余额不足提示打开的充值页面返回时,都会重试一次失败的图片,即使 URL 未变化;加载中和已成功的图片会复用,成功后两处一起展示。头像 URL 变化时开始新加载;账号状态替换、退出登录和插件卸载会丢弃旧头像及其回调。折叠侧边栏将头像居中放置在 36 × 36 px 的按钮内。登录前侧边栏入口改为紧凑的「更多」行,以三点图标开头,内容和内缩的悬停底色与导航行对齐。展开态按钮采用 border-box 尺寸:已登录行含 6px 内边距共高 44px,未登录的「更多」行高 32px。已登录入口保留 24px 头像及 8px 标签间距,并由自身根节点承担左右各 2px 外边距;该内缩不会水平移动设置外壳中相邻的状态指示器。 @@ -52,7 +54,7 @@ Chat 通过 `shell.overlay` 中的宿主把已绑定 Session 的实时欠费交 退出登录先查询正在使用账号 token 的任务,再打开确认弹窗。有此类任务时提示执行将被打断,否则提示数据保留且可重新登录。取消、关闭和 Escape 均不退登。影响查询失败仍打开确认弹窗,并明确提示无法确认任务状态;退登失败保留弹窗以便重试。 -账号通知的轮询与展示由 [ui-account-notifications](../ui-account-notifications/README.zh.md) 负责。账号菜单在侧栏内部将通知插槽定位于入口上方,收起为窄栏时隐藏但保留其 DOM,并发布账号生命周期和刷新事件。 +账号通知的轮询与展示由 [ui-account-notifications](../ui-account-notifications/README.zh.md) 负责。插件在设置外壳位于入口行上方的 `settings.notice` 行中渲染通知插槽,并发布账号生命周期和刷新事件。 ### Desktop 引导 @@ -61,12 +63,12 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本 欢迎页必须点击“开始设置”。额度页始终展示。首次进入时若已确认有正余额,则主操作为“继续”,次操作为“去充值”。该选择在引导控制器重建前保持固定且不持久化,后到的余额结果不会改变按钮。仅在确认不存在正余额时,继续而不充值才需确认;查询中或失败时不阻止继续。用途卡片选中后描述不变。从原生充值视图返回后保留额度页,并在等待任何已在进行的读取结束后于后台重读资料与余额,不受页面加载或支付结果影响。该读取不会重新计算该选择,因此充值成功后按钮仍保持首次进入时的状态,而继续前行仍按刷新后的余额判断。“下一步”仅在确认零余额时提示;额度页的“跳过”使用充值提示,答题页使用设置提示。仅选办公用途时以简洁展示完成;选择开发或两种用途时还会询问过程详情。上一步保留已有选择,任意可跳过步骤均采用标准工作过程、简洁性能与用量以及关闭代码工作工具的默认值。此流程不创建工作区或示例任务。 -访问控制:账号状态流、额度提醒、设置启动器、账号设置分区与模型登录入口只在当前 Peer 可以调用 `account/watch` 时存在;桌面引导与平台页面不受此控制。失去该权限时,这一轮发出的账号读取作废,待授权的浏览器标签页关闭,账号视图、详情、头像与登录对话框状态清空;之后再次授权时,账号分区等新流的第一帧到达后才重新出现。owner 始终有权限。 +访问控制:账号状态流、额度提醒、设置启动器、通知行、账号设置分区与模型登录入口只在当前 Peer 可以调用 `account/watch` 时存在;桌面引导与平台页面不受此控制。失去该权限时,这一轮发出的账号读取作废,待授权的浏览器标签页关闭,账号视图、详情、头像与登录对话框状态清空;之后再次授权时,账号分区等新流的第一帧到达后才重新出现。owner 始终有权限。 ## 理解实现 -仅登录后在设置导航首位显示账号页;账号状态加载完成前以及退出登录后隐藏该页。 插件持有一条 Host 快照流,通过框架 hook 供 settings.section 和 settings.launcher 共享。入口菜单可打开设置,并仅在已存储账号凭证时提供退出登录。Platform 请求失败时保留菜单,以供重试。插件不维护独立凭证状态。 +仅登录后在设置导航首位显示账号页;账号状态加载完成前以及退出登录后隐藏该页。 插件持有一条 Host 快照流,通过框架 hook 供 settings.section、settings.launcher 和 settings.notice 共享。入口菜单可打开设置,并仅在已存储账号凭证时提供退出登录。Platform 请求失败时保留菜单,以供重试。插件不维护独立凭证状态。 桌面控制器通过 Host 设置将进度写入 `ui-settings-account`。完成时先一并应用 `ui-chat.transcriptView` 与 `ui-chat.performanceUsage`,再通过共享代码工作工具偏好保存 `ui-settings.enabled`,最后保存完成标记;写入被拒绝时保留引导以供重试。成功完成后通过 180ms 淡出显露工作区;选择和普通翻页立即预览,写入在后台按顺序执行。队列最后一次写入失败时恢复已保存进度,并允许重试。完成操作会等待选择队列及偏好保存成功,再关闭页面;减少动态效果偏好会跳过淡出。onboarding 选项 compact、standard、detailed 直接应用到对应的 Chat 工作过程模式。API Key 进入与显式跳过均采用 standard;onboarding 不选择 verbose。完整 Figma 示意图层以透明、无损编码的 3× WebP [包资源](../AGENTS.md#dependency-declaration)形式提供;欢迎页图层合并并烘焙侧栏局部模糊;充值页前景窗口不透明度为 70%,仅烘焙其覆盖插图区域的模糊,标题使用已打包的 Montserrat 品牌字体,英文标题和描述使用 Light(300),标题中的 DeepSeek Harness 使用 Medium(500);卡片标题选中前后均使用 Regular(400)。英文底部导航使用 Light(300)。确认进入引导后,窗口最小宽度设为 960px,较窄窗口自动放大;完成后解除宽度限制,但不恢复原尺寸。加载中或已完成引导的启动不改变窗口尺寸。底部导航空白区域透过鼠标事件,避免遮挡主操作。卡片区域不参与原生窗口拖动,复选框的键盘焦点仅在卡片外框展示。账号包负责引导覆盖层和控件尺寸样式。每个步骤和确认弹窗各有独立组件,流程组件协调导航、切换动画和充值。初始账号与进度加载期间,覆盖层隐藏工作区。答题标题和卡片独立于操作按钮,位置对齐 Figma 的 1440 × 920 和 960 × 600 断点。在 macOS 上,Shell 为每个元素重置继承的窗口区域,位于内容之前的拖拽层保留 8px 原生缩放边缘。内容层的 `data-window-drag-controls` 范围排除交互控件,后续弹窗排除自身矩形;原生平台页面打开时禁用底层引导拖拽层。上方工作区弹窗插画在两种语言和主题下均使用不透明背景,下层侧边栏不绘制选中行高亮。欢迎页保持示意图的原始尺寸,在窄窗口内调整插图位置并裁切,在宽窗口内展示完整插图。[历史引导决策](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md)记录持久化与展示方面的取舍。 diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.module.css b/packages/client/ui-settings-account/src/client/AccountMenu.module.css index 773e791722..66214266d6 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.module.css +++ b/packages/client/ui-settings-account/src/client/AccountMenu.module.css @@ -1,6 +1,5 @@ -.root { position: relative; flex: 1; min-width: 0; } +.root { flex: 1; min-width: 0; } .root[data-inset='true'] { margin-inline: 2px; } -.notifications { position: absolute; inset-inline: 0; bottom: calc(100% + 4px); z-index: 1; } .anchor { width: 100%; } .trigger { user-select: none; display: flex; align-items: center; width: 100%; height: 44px; gap: 8px; padding: 6px calc(var(--dsh-sidebar-row-padding) - var(--dsh-sidebar-paint-inset)); border: 0; border-inline: var(--dsh-sidebar-paint-inset) solid transparent; box-sizing: border-box; border-radius: var(--dsw-radius-md); background: transparent; background-clip: padding-box; color: var(--dsw-alias-label-primary); font: inherit; font-size: 14px; cursor: pointer; } .trigger[data-signed-out='false']:not([data-collapsed='true']) { padding: 6px; border-inline: 0; background-clip: border-box; } @@ -29,11 +28,3 @@ font-size: 14px; line-height: 22px; } - -.signedOutMenu [role='menuitem'] > span:first-child:not(:last-child) { - width: 16px; - height: 16px; - color: var(--dsw-alias-menu-icon); -} - -.signedOutMenu [role='menuitem'] > span:first-child:not(:last-child) svg { width: 16px; height: 16px; } diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.tsx b/packages/client/ui-settings-account/src/client/AccountMenu.tsx index 58838a5c6c..1972e80bfd 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.tsx +++ b/packages/client/ui-settings-account/src/client/AccountMenu.tsx @@ -1,9 +1,9 @@ /** Sidebar account launcher and locally authoritative sign-out action. */ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { - Toast, Menu, IconEllipsisOutlineMedium, IconPaperPlaneOutlineMedium, IconSettingsOutlineMedium, IconUserOutlineMedium, + Toast, Menu, IconEllipsisOutlineMedium, IconPaperPlaneOutlineRegular, IconSettingsOutlineRegular, IconUserOutlineRegular, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { InjectFace, PropsLocale, PropsRuntime, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { AccountSectionInjected } from './AccountSection.tsx' import { SignOutDialog } from './SignOutDialog.tsx' import { SignInDialog } from './SignInDialog.tsx' @@ -13,7 +13,7 @@ import type {} from './account-ui.ts' import css from './AccountMenu.module.css' /** Account launcher composed by the settings shell. */ -export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsRenderSlots<'settings.launcher.notifications'> & PropsLocale<'settings.account'> & InjectFace +export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsLocale<'settings.account'> & InjectFace /** The signed-in label stays empty while the profile loads. * @param props - sidebar geometry, settings navigation and account operations. @@ -21,7 +21,7 @@ export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsRenderSl */ export function AccountMenu({ subscribeSessionExpired, subscribeModelSignInRequired, wide, settingsShortcut, openSettings, openOnboarding, settingsOpen, - useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount, renderSlot, + useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount, contactUs, showLogin, start, cancel, avatarFailed, t, }: AccountMenuProps) { // The launcher outlives the panel, so a false-to-true edge is one Settings entry: @@ -53,13 +53,9 @@ export function AccountMenu({ } // The plugin's start publishes `loginFailed` before it rejects, so the dialog owns the report. const beginSignIn = (): void => { setOpen(false); void start().catch(() => undefined) } - const openAccount = useCallback(() => { openSettings('account') }, [openSettings]) return
      {signInNotice > 0 && { setSignInNotice(0) }} />} {expiryNotice && { setExpiryNotice(false) }} />} - { setOpen(value => !value) }}> @@ -71,11 +67,11 @@ export function AccountMenu({ {wide && {signedIn ? label : t('more')}} } items={[ - { id: 'settings', label: t('settings'), icon: , + { id: 'settings', label: t('settings'), icon: , ...(settingsShortcut === undefined ? {} : { shortcut: settingsShortcut }) }, - { id: 'contact', label: t('contactUs'), icon: }, + { id: 'contact', label: t('contactUs'), icon: }, ...(signedIn ? [{ id: 'signout', label: t('signOut'), icon: , disabled: busy }] - : [{ id: 'signin', label: t('signIn'), icon: }]), + : [{ id: 'signin', label: t('signIn'), icon: }]), ]} onClose={() => { setOpen(false) }} onSelect={(id) => { diff --git a/packages/client/ui-settings-account/src/client/AccountNotices.module.css b/packages/client/ui-settings-account/src/client/AccountNotices.module.css new file mode 100644 index 0000000000..02c9ac99f3 --- /dev/null +++ b/packages/client/ui-settings-account/src/client/AccountNotices.module.css @@ -0,0 +1,2 @@ +/* Matches the signed-in launcher inset so the card edges align with the account row. */ +.root { margin-inline: 2px; } diff --git a/packages/client/ui-settings-account/src/client/AccountNotices.tsx b/packages/client/ui-settings-account/src/client/AccountNotices.tsx new file mode 100644 index 0000000000..42ecc5bb5b --- /dev/null +++ b/packages/client/ui-settings-account/src/client/AccountNotices.tsx @@ -0,0 +1,21 @@ +/** Account notification row above the sidebar account launcher. */ +import type { InjectFace, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { AccountSectionInjected } from './AccountSection.tsx' +import type {} from './account-ui.ts' +import css from './AccountNotices.module.css' + +/** Notice row composed by the settings shell. */ +export type AccountNoticesProps = PropsRuntime<'settings.notice'> + & PropsRenderSlots<'settings.launcher.notifications'> & InjectFace + +/** + * @param props - settings navigation and account state. + * @returns the account notification extension, active only when signed in outside onboarding. + */ +export function AccountNotices({ openSettings, useAccount, renderSlot }: AccountNoticesProps) { + const account = useAccount(state => state) + const active = account.view?.status === 'credential-stored' && !account.desktopOnboardingVisible && !account.onboarding + return
      {renderSlot('settings.launcher.notifications', { + active, openAccount: () => { openSettings('account') }, + })}
      +} diff --git a/packages/client/ui-settings-account/src/client/LogoutIcon.tsx b/packages/client/ui-settings-account/src/client/LogoutIcon.tsx index 6c3a5cb61e..4c1f75adaa 100644 --- a/packages/client/ui-settings-account/src/client/LogoutIcon.tsx +++ b/packages/client/ui-settings-account/src/client/LogoutIcon.tsx @@ -1,10 +1,9 @@ -/** Figma IcDsLogOutOutline16 glyph, stored inline for theme-aware rendering. */ +/** Account-menu logout glyph with the shared optical size and stroke weight. */ +import { ICON_REGULAR_STROKE } from '@deepseek-ai/dsh-client-ui-primitives' -/** @returns the account menu logout glyph. */ +/** @returns the decorative account-menu logout glyph. */ export function LogoutIcon() { - return } diff --git a/packages/client/ui-settings-account/src/client/account-ui.ts b/packages/client/ui-settings-account/src/client/account-ui.ts index e2c6e696ee..8ad0e24662 100644 --- a/packages/client/ui-settings-account/src/client/account-ui.ts +++ b/packages/client/ui-settings-account/src/client/account-ui.ts @@ -20,9 +20,9 @@ export interface AccountUi { clientMetadata(locale: string): AccountClientMetadata } -/** Account-menu presentation facts supplied to its notification extension. */ +/** Account presentation facts supplied to its notification extension. */ export interface AccountNotificationsOwnerProps { - /** Whether the account menu can display notifications outside onboarding. */ + /** Whether a signed-in account can display notifications outside onboarding. */ active: boolean /** Open the account section in the existing settings shell. */ openAccount: () => void @@ -43,7 +43,7 @@ declare module '@deepseek-ai/cordis' { declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { - /** Notifications anchored at the account menu; the contribution owns its markup and lifecycle. */ + /** Notifications in the row above the account launcher; the contribution owns its markup and lifecycle. */ 'settings.launcher.notifications': { kind: 'single'; scope: 'root'; owner: AccountNotificationsOwnerProps } } } diff --git a/packages/client/ui-settings-account/src/client/index.ts b/packages/client/ui-settings-account/src/client/index.ts index a8ac2c89fa..e680e1cb32 100644 --- a/packages/client/ui-settings-account/src/client/index.ts +++ b/packages/client/ui-settings-account/src/client/index.ts @@ -20,6 +20,7 @@ import { BrowserLogin } from './browser-login.ts' import { AccountOnboarding } from './AccountOnboarding.tsx' import { AccountPlatformHost, type AccountPlatformHostInjected } from './AccountPlatformHost.tsx' import { AccountMenu } from './AccountMenu.tsx' +import { AccountNotices } from './AccountNotices.tsx' import { createPlatformPages, type PlatformPages } from './platform-pages.ts' import { AccountSection, type AccountSnapshot, type AccountSectionInjected } from './AccountSection.tsx' import { accountClientMetadata } from './client-metadata.ts' @@ -313,8 +314,11 @@ export function apply(ctx: Context): void { } ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.launcher', () => ctx.slots.register({ name: 'settings.launcher', locale: 'settings.account', inject: () => operations, - children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } }, }, AccountMenu))) + ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.notice', () => ctx.slots.register({ + name: 'settings.notice', inject: () => operations, + children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } }, + }, AccountNotices))) ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.section', () => { let unregister: (() => void) | undefined const update = () => { diff --git a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts index 3e55d655d9..01a599b981 100644 --- a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts +++ b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts @@ -92,22 +92,22 @@ it('withdraws every account surface and the account stream on revocation, and re }, } const surfaces = (): Record => Object.fromEntries( - ['settings.launcher', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section'].map(name => [name, registered.get(name)]), + ['settings.launcher', 'settings.notice', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section'].map(name => [name, registered.get(name)]), ) try { apply(ctx as never) expect(new Set(guards.map(guard => guard.action))).toEqual(new Set(['account/watch'])) grant(guards) await streams[0]!.accepted - expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) + expect(surfaces()).toEqual({ 'settings.launcher': 1, 'settings.notice': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) revoke(guards) expect(streams[0]!.signal.aborted).toBe(true) - expect(surfaces()).toEqual({ 'settings.launcher': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0 }) + expect(surfaces()).toEqual({ 'settings.launcher': 0, 'settings.notice': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0 }) grant(guards) await streams[1]!.accepted - expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) + expect(surfaces()).toEqual({ 'settings.launcher': 1, 'settings.notice': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) } finally { revoke(guards) for (const dispose of lifetime.reverse()) dispose() diff --git a/packages/client/ui-settings-account/tests/account.client.spec.tsx b/packages/client/ui-settings-account/tests/account.client.spec.tsx index 85c85677d9..dd93b8fa79 100644 --- a/packages/client/ui-settings-account/tests/account.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/account.client.spec.tsx @@ -10,6 +10,7 @@ import { createPlatformPages, type PlatformPages } from '../src/client/platform- import { AccountPlatformHost } from '../src/client/AccountPlatformHost.tsx' import { AccountSection, type AccountSectionInjected, type AccountSnapshot } from '../src/client/AccountSection.tsx' import type { AccountMenuProps } from '../src/client/AccountMenu.tsx' +import type { AccountNoticesProps } from '../src/client/AccountNotices.tsx' import type { AccountNotificationsOwnerProps } from '../src/client/account-ui.ts' import type {} from '../src/client/index.ts' import { en, zh, type AccountKey } from '../src/client/locales.ts' @@ -92,14 +93,12 @@ function SharedPlatformHost({ Globals, pages, platform, copy, refreshAccount }: * @param settingsOpen - whether the settings panel covers the sidebar. * @returns the sidebar launcher with its framework hooks wired to the test face. */ -async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean, - renderSlot: AccountMenuProps['renderSlot'] = () => null, - openSettings: AccountMenuProps['openSettings'] = () => {}, wide = true) { +async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean) { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - return selector(snapshot())} wide={wide} + return selector(snapshot())} wide useTheme={selector => selector(operations.hooks.theme.getSnapshot())} - openOnboarding={() => {}} openSettings={openSettings} t={key => en[key as AccountKey]} /> + openOnboarding={() => {}} openSettings={() => {}} t={key => en[key as AccountKey]} /> } it.each([en, zh])('renders account cards without inventing profile or balance data', async (copy) => { @@ -129,7 +128,7 @@ it.each([en, zh].flatMap(copy => ([false, true, 'unknown'] as const).map(running const operations = mount({ status: 'credential-stored', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut} + render( { if (running === 'unknown') throw new Error('offline'); return running }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} @@ -156,7 +155,7 @@ it.each([en, zh])('updates the Settings menu keycaps and accessible combination const operations = mount({ status: 'signed-out', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const props: AccountMenuProps = { renderSlot: () => null, + const props: AccountMenuProps = { ...({} as GlobalStandardProps), ...operations, wide: true, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -185,7 +184,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco const openSettings = vi.fn() const operations = operationsOf({ status: 'signed-out', attempt: null }) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} t={key => key in copy ? copy[key as AccountKey] : key} />) @@ -205,7 +204,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco it.each([true, false])('keeps the account inset local through sign-in changes with wide=%s', async (wide) => { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let operations = operationsOf({ status: 'signed-out', attempt: null }) - const props: AccountMenuProps = { renderSlot: () => null, + const props: AccountMenuProps = { ...({} as GlobalStandardProps), ...operations, wide, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -237,7 +236,7 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( snapshot = { ...snapshot, loginVisible: true, loginFailed: true } return Promise.reject(new Error('account start failed')) }) - const view = render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + const view = render( selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -246,7 +245,7 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: en.signIn })) }) expect(start).toHaveBeenCalledOnce() expect(screen.queryByRole('alert')).toBeNull() - view.rerender( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + view.rerender( selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -263,7 +262,7 @@ it('keeps the confirmation dialog open after a failed sign-out', async () => { cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const signOut = vi.fn((): Promise => Promise.reject(new Error('account sign-out failed'))) - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide @@ -426,7 +425,7 @@ it.each([ }) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -439,7 +438,7 @@ it('shows the same shared picture outcome in settings and the sidebar', async () profile: { status: 'ready', value: { id: null, name: 'User', contact: null, avatarUrl: 'https://example.test/avatar.png' } }, }, undefined, avatar) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -510,7 +509,7 @@ it.each([en, zh])('shows a localized toast when the account credential expires', const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let expire: (() => void) | undefined const unsubscribe = vi.fn() - const element = null} {...({} as GlobalStandardProps)} {...operations} + const element = { expire = listener; return unsubscribe }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -609,7 +608,7 @@ it('dismisses a collapsed menu and hands its login dialog to the API-key onboard const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const openOnboarding = vi.fn() let snapshot = operations.hooks.account.getSnapshot() - const props = { ...({} as GlobalStandardProps), ...operations, renderSlot: () => null, wide: false, settingsOpen: false, + const props = { ...({} as GlobalStandardProps), ...operations, wide: false, settingsOpen: false, openSettings: vi.fn(), openOnboarding, useAccount: (select: (value: AccountSnapshot) => T) => select(snapshot), useTheme: (select: (value: ThemeSnapshot) => T) => select(operations.hooks.theme.getSnapshot()), @@ -698,7 +697,7 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after const unsubscribe = vi.fn(() => { listener = undefined }) operations.subscribeModelSignInRequired = (next) => { listener = next; return unsubscribe } const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const element = null} {...({} as GlobalStandardProps)} {...operations} + const element = selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -720,12 +719,13 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after }) it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notification slot until %s ends', async (field) => { + const { AccountNotices } = await import('../src/client/AccountNotices.tsx') const operations = operationsOf({ status: 'credential-stored', attempt: null }) let snapshot: AccountSnapshot = { ...operations.hooks.account.getSnapshot(), [field]: true } let active: boolean | undefined let openAccount: (() => void) | undefined const openSettings = vi.fn() - const renderSlot: AccountMenuProps['renderSlot'] = (name, owner) => { + const renderSlot: AccountNoticesProps['renderSlot'] = (name, owner) => { expect(name).toBe('settings.launcher.notifications') const value: object = owner const props = value as AccountNotificationsOwnerProps @@ -733,25 +733,29 @@ it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notifica openAccount = props.openAccount return null } - const view = render(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + const notices = () => selector(snapshot)} + useTheme={selector => selector(operations.hooks.theme.getSnapshot())} openSettings={openSettings} /> + const view = render(notices()) expect(active).toBe(false) snapshot = { ...snapshot, [field]: false } - view.rerender(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + view.rerender(notices()) expect(active).toBe(true) openAccount?.() expect(openSettings).toHaveBeenCalledExactlyOnceWith('account') }) -it('keeps notification DOM inside the launcher while the collapsed rail hides it', async () => { - const operations = operationsOf({ status: 'credential-stored', attempt: null }) - const snapshot = () => operations.hooks.account.getSnapshot() - const renderSlot: AccountMenuProps['renderSlot'] = () =>
      Notification
      - const view = render(await accountMenu(operations, snapshot, false, renderSlot)) - const notice = screen.getByRole('status') - expect(view.container.contains(notice)).toBe(true) - view.rerender(await accountMenu(operations, snapshot, false, renderSlot, undefined, false)) - expect(screen.queryByRole('status')).toBeNull() - expect(notice.isConnected).toBe(true) - view.rerender(await accountMenu(operations, snapshot, false, renderSlot)) - expect(screen.getByRole('status')).toBe(notice) +it('keeps the notification slot inactive while signed out', async () => { + const { AccountNotices } = await import('../src/client/AccountNotices.tsx') + const operations = operationsOf({ status: 'signed-out', attempt: null }) + const owners: AccountNotificationsOwnerProps[] = [] + const renderSlot: AccountNoticesProps['renderSlot'] = (_name, owner) => { + const value: object = owner + owners.push(value as AccountNotificationsOwnerProps) + return null + } + render( selector(operations.hooks.account.getSnapshot())} + useTheme={selector => selector(operations.hooks.theme.getSnapshot())} openSettings={() => {}} />) + expect(owners.at(-1)?.active).toBe(false) }) diff --git a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx index 7393ce1d5a..d00a17cf35 100644 --- a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx @@ -3,6 +3,7 @@ * The account takeover inside the shipped composition: the frame-wide notice * chain, the account settings page, and the one shared native Platform host. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -111,7 +112,7 @@ async function bench() { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ apply: applyMenus, inject: injectMenus }) + await runtime.mount({ apply: applyMenus, inject: injectMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) runtime.slots.installLocale(locale) runtime.ctx.effect(() => locale.register('settings.account', { en, zh }), 'spec: account dictionaries') await runtime.declare({ @@ -119,7 +120,7 @@ async function bench() { 'settings.section': { kind: 'list', scope: 'root' }, 'conversation.approval.detail': { kind: 'single', scope: 'session' }, }) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) let descriptor: Parameters[0] | undefined const provide = runtime.ctx.uiSession.provide.bind(runtime.ctx.uiSession) runtime.ctx.uiSession.provide = (next) => { descriptor ??= next; return provide(next) } diff --git a/packages/client/ui-settings-account/tsconfig.json b/packages/client/ui-settings-account/tsconfig.json index ac170f07db..d425a8cdea 100644 --- a/packages/client/ui-settings-account/tsconfig.json +++ b/packages/client/ui-settings-account/tsconfig.json @@ -36,7 +36,7 @@ "path": "../ui-theme/tsconfig.client.json" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../ui-settings-models" diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index 1bbfb63a97..a56b70ab37 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7600861d064dbc99 zh: a52ba446016e3a21 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation: - en: 4d25df8fe0e60b20 - zh: cecd02d3b6e47b24 + en: 2ba62c7be5b79052 + zh: 9220e867a0e88076 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation/ledger-projections: en: fd99444278ab8530 zh: 2efc5831c7e19be1 diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index 8e5c7ef0d3..a12ef36089 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -68,7 +68,7 @@ Desktop also contributes an **Update channel** row to General when the preload e ## Understand the implementation -The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. +The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. The shell also declares settings.notice and renders it in a zero-height, full-width row above the launcher row; its content floats over the sidebar list, so status indicators beside the launcher do not narrow its content; the collapsed rail hides that row without unmounting it.
      Implementation internals — click to expand diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index 4012c252d6..d3db7fcf87 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -68,7 +68,7 @@ Web 与桌面端的通用设置底部显示当前发布版本,使用构建注 ## 理解实现 -外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。 +外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。外壳还声明 settings.notice,并在入口行上方零高度的满宽行中渲染它,其内容浮在侧栏列表之上,因此入口旁的状态指示器不会挤压其内容;折叠轨道隐藏该行但不卸载它。
      实现细节——点击展开 diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.module.css b/packages/client/ui-settings-general/src/client/SettingsRoot.module.css index 29c3d52c45..4bc579e344 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.module.css +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.module.css @@ -8,6 +8,20 @@ margin: 4px 0; } +/* The notice row takes no height: its content floats above the sidebar list at + the row's full width, so status indicators in the trigger row do not narrow it. */ +.noticeRow { + position: relative; + height: 0; +} + +.notice { + position: absolute; + inset-inline: 0; + bottom: 0; + z-index: 1; +} + .triggerRow.railRow { width: 36px; margin: 8px 0 10px; diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx index e461d65868..96bddf9410 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -221,14 +221,17 @@ export function SettingsRoot(props: SettingsRootComponentProps) { connectionIndicator = 'recovered' } + const openSettings = (sectionId?: string): void => { + if (sectionId === undefined) actions.open() + else actions.openSection(sectionId) + } + return ( <> +
      {renderSlot('settings.launcher', { - wide, settingsOpen: open, openSettings: (sectionId) => { - if (sectionId === undefined) actions.open() - else actions.openSection(sectionId) - }, + wide, settingsOpen: open, openSettings, ...(shortcut?.keys.length ? { settingsShortcut: { keys: shortcut.keys, aria: shortcut.aria } } : {}), openOnboarding: (id) => { close(); setRequestedOnboarding(id) }, }, { fallback: diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts index 5303fb46ba..ee3bb86d99 100644 --- a/packages/client/ui-settings-general/src/client/index.ts +++ b/packages/client/ui-settings-general/src/client/index.ts @@ -236,6 +236,7 @@ export function apply(ctx: ClientContext): void { store: shellStore, children: { 'settings.launcher': { kind: 'single', scope: 'root' }, + 'settings.notice': { kind: 'single', scope: 'root' }, 'settings.trigger': { kind: 'single', scope: 'root' }, 'settings.header': { kind: 'single', scope: 'root' }, 'settings.action': { kind: 'list', scope: 'root' }, diff --git a/packages/client/ui-settings-general/src/client/shell-contract.ts b/packages/client/ui-settings-general/src/client/shell-contract.ts index 6c548e1e1d..1150d3f48c 100644 --- a/packages/client/ui-settings-general/src/client/shell-contract.ts +++ b/packages/client/ui-settings-general/src/client/shell-contract.ts @@ -67,6 +67,7 @@ export type SettingsRootComponentProps = PropsRuntime<'sidebar.settings'> & PropsRenderSlots< | 'settings.launcher' + | 'settings.notice' | 'settings.trigger' | 'settings.header' | 'settings.action' diff --git a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx index b728799793..0d37968a37 100644 --- a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx @@ -42,6 +42,7 @@ type Step = { id: string; order: number } /** Slot-content stand-ins: the shell renders whatever the seats contribute. */ const SEAT_CONTENT: Record = { 'settings.trigger': 'Settings', + 'settings.notice': 'Account notice', 'settings.header': 'Settings Title', 'settings.action': 'Open configuration file', 'settings.close': 'Close', @@ -165,6 +166,7 @@ function mount({ desktopUpdate = next view.rerender() } + const setWide = (next: boolean) => { view.rerender() } const setShortcuts = (next: readonly ShortcutCatalogEntry[]) => { shortcuts = next view.rerender() @@ -178,7 +180,7 @@ function mount({ } return { view, renderSlot, renderFactorySlot, bump, listeners, reconnect, - setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive, + setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive, setWide, } } @@ -558,3 +560,24 @@ it('passes current Settings key labels to the launcher and removes them when unb setShortcuts([{ ...row, keys: [], aria: undefined, binding: null, modified: true }]) expect(launcher()).not.toHaveProperty('settingsShortcut') }) + +it('renders the notice row before the launcher row and opens the requested section', () => { + const { renderSlot } = mount({ rows: [{ id: 'general', order: 0, label: 'General' }, { id: 'account', order: 1, label: 'Account' }] }) + const notice = screen.getByText('Account notice').parentElement! + expect(notice.nextElementSibling?.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true) + const owner = renderSlot.mock.calls.find(call => call[0] === 'settings.notice')! + act(() => { (owner[1] as { openSettings: (sectionId?: string) => void }).openSettings('account') }) + expect(screen.getByTestId('section-account')).toBeTruthy() +}) + +it('hides the notice row in the collapsed rail and keeps the same node', () => { + const { setWide } = mount() + const notice = screen.getByText('Account notice').parentElement! + expect(notice.hidden).toBe(false) + setWide(false) + expect(screen.getByText('Account notice').parentElement).toBe(notice) + expect(notice.hidden).toBe(true) + setWide(true) + expect(screen.getByText('Account notice').parentElement).toBe(notice) + expect(notice.hidden).toBe(false) +}) diff --git a/packages/client/ui-settings-general/tests/shell.client.spec.ts b/packages/client/ui-settings-general/tests/shell.client.spec.ts index 8e36d7bde4..c728b1e704 100644 --- a/packages/client/ui-settings-general/tests/shell.client.spec.ts +++ b/packages/client/ui-settings-general/tests/shell.client.spec.ts @@ -28,6 +28,7 @@ function injectedOf(c: TestClient): SettingsRootInjected { /** The slots this package declares, through the shell or the `settings.section.view` Factory. */ const CHILD_SPECS = { 'settings.launcher': { kind: 'single', scope: 'root' }, + 'settings.notice': { kind: 'single', scope: 'root' }, 'settings.trigger': { kind: 'single', scope: 'root' }, 'settings.header': { kind: 'single', scope: 'root' }, 'settings.action': { kind: 'list', scope: 'root' }, diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 0b4439bdbe..d48ee26cad 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-settings-models/use-this-package: - en: db5aaf7f702e1f0c - zh: 409a78c14fb2b6e3 + en: 9a429fabe725d166 + zh: 0ba6e68958fb4c75 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: en: fa2cefbf8c4fdafe zh: 3a4689591b50f6ea /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: a83a61e44b6f1c00 - zh: 2dc6d84692e524ac + en: 041857583e079891 + zh: b6cd6dd11609aa28 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc @@ -30,14 +30,14 @@ en: 589397a35f82244e zh: 342fbceee2c173a2 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/extension-slots: - en: 79f8f80bdaba73cd - zh: f4d7496b293fbf81 + en: db662df5625ede0b + zh: e7578f1a5894ac59 /deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation: - en: a87afbec5e339b36 - zh: 6348c81af7e650e1 + en: b4adb51e0ceff8da + zh: 238873b13d0660cf /deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation/validation: - en: d469e496518d44c5 - zh: e71938ef7502a20c + en: 7ebb4f43b619d8dd + zh: 3cdb6dd893cb8c8e /deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation/concurrency-and-credentials: en: 6e04c00818f014cd zh: 2d57f8d8944e67ed diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index ec7675d6c6..0551ca9f1b 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -27,6 +27,8 @@ Desktop product events use the optional [product analytics service](../product-a ## Use this package +The section title and introduction form one group above the provider list. Expanded model fields separate adjacent field groups more than labels from their controls, and model-list actions follow the shared control-radius scale. + Saving credentials or a custom provider preserves the selected model. The user can select an available model from the composer. DeepSeek Account appears first and DeepSeek second in the provider list; third-party providers retain their directory order. @@ -59,7 +61,7 @@ The same fold edits the provider's `retryPolicy` for both families. **Retry poli The DeepSeek card edits the `llm-deepseek` endpoint, credentials, retry policy, and model catalog. It uses Messages, with the default endpoint placeholder `https://api.deepseek.com/anthropic`. -Drag a model’s reorder handle to change its position within the provider, or focus the handle and use the up and down arrow keys. Apply saves the order; Cancel discards it. Each model keeps its settings, expanded options, and unfinished capacity text when moved. The full-row drag preview and reduced-motion-aware row animations share primitives with workspace reordering; before/after insertion markers follow the same style. +Drag a model’s reorder handle to change its position within the provider, or focus the handle and use the up and down arrow keys. Apply saves the order; Cancel discards it. Each model keeps its settings, expanded options, and unfinished capacity text when moved. The full-row drag preview and reduced-motion-aware row animations share primitives with workspace reordering; before/after insertion markers follow the same style. Row spacing and the adjoining drop targets share one gap value so the space between rows accepts drops. Expand **Customized settings → Model options** to edit each model. When the model row is narrow, the main row shows only the model ID; expand the row to view or edit its display name. Wider rows show both fields side by side. Focusing a display name expands its row and keeps it open until explicitly collapsed. Tab reaches the option and delete buttons before the display name at every width. Both provider families share the same row layout, labels, and icons: context window and max output tokens occupy two columns, and **Input types** occupies a separate row with **Text** and **Image** checkboxes. A row without an input declaration displays the installed model’s input types, then the provider default, then Text. Known pi-ai providers load their installed catalog without endpoint I/O; opening a row does not write an override. Explicit input selections take precedence, including text-only overrides of vision models. Checkbox edits save the selected types, with at least one type required. DeepSeek writes `inputModalities`; pi-ai writes `input`. Unchecking Image for DeepSeek also removes `imagePixelBudget` and `imageMaxBytes`, because the adapter rejects those limits without image input. Clearing the input field in `cordis.patch.yml` restores adapter inheritance; **Restore default models** resets the entire catalog override. Declare only input types the upstream model can actually process. @@ -83,17 +85,21 @@ The Models page includes **DeepSeek Account** (`deepseek-account`, **DeepSeek ----- +Onboarding groups its title and explanation closely, then separates credential fields and the action row with larger gaps. + ## Understand the implementation
      Implementation internals — click to expand +Model identity and capacity fields share columns; narrow cards stack their fields. Each provider editor keeps its cancel and save actions together at the scrolling edge, and focused controls retain clearance from that action group. + The page never holds a full settings section: it holds only the REDACTED descriptor, so every edit lands as `settings.mutate` path ops against the stored section — a set per changed field, an unset per cleared one, and a single unset for a deleted provider row. ### Validation -A typed API key is judged on its own field: after trimming, it must be non-empty and every character must be printable ASCII (`[\x21-\x7E]`), which is exactly what an HTTP header value can carry — the twin of `normalizeApiKey` in `@deepseek-ai/dsh-llm`, mirrored here because the source-plane split forbids importing it. A value matching a pasted `NAME=value` environment line or wrapped in matching quotes is refused as the same format failure. Empty ids, duplicate ids, empty explicit names, and unreadable, non-positive, or fractional capacities fail before any write. The retry fields come from the `retryPolicy` schema the namespace publishes: each union branch is a mode, number fields become inputs whose integer step, minimum, and maximum are checked from the schema, string lists become the code picker, nested objects become folds, and fields of other types are not shown. The labels, hints, messages, and code names are copy owned by this page; an unlabelled field shows its schema key. The two rules `resolveRetryPolicy` in `@deepseek-ai/dsh-llm` enforces beyond any field bound, an initial delay at most the maximum delay and no repeated code, are mirrored for the same reason, because `llm-deepseek` only logs a warning for a live policy it refuses. The card writes the policy field by field, so an unchanged inherited field stays inherited. DeepSeek's `models` is one replace-by-value array: the editor shows inherited effective rows until the first model edit materializes the complete array in the user layer, while reset unsets that override. +A typed API key is judged on its own field: after trimming, it must be non-empty and every character must be printable ASCII (`[\x21-\x7E]`), which is exactly what an HTTP header value can carry — the twin of `normalizeApiKey` in `@deepseek-ai/dsh-credentials`, mirrored here because the source-plane split forbids importing it. A value matching a pasted `NAME=value` environment line or wrapped in matching quotes is refused as the same format failure. Empty ids, duplicate ids, empty explicit names, and unreadable, non-positive, or fractional capacities fail before any write. The retry fields come from the `retryPolicy` schema the namespace publishes: each union branch is a mode, number fields become inputs whose integer step, minimum, and maximum are checked from the schema, string lists become the code picker, nested objects become folds, and fields of other types are not shown. The labels, hints, messages, and code names are copy owned by this page; an unlabelled field shows its schema key. The two rules `resolveRetryPolicy` in `@deepseek-ai/dsh-llm` enforces beyond any field bound, an initial delay at most the maximum delay and no repeated code, are mirrored for the same reason, because `llm-deepseek` only logs a warning for a live policy it refuses. The card writes the policy field by field, so an unchanged inherited field stays inherited. DeepSeek's `models` is one replace-by-value array: the editor shows inherited effective rows until the first model edit materializes the complete array in the user layer, while reset unsets that override. ### Concurrency and credentials diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 244e1c0e05..17ba45fbec 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -27,6 +27,8 @@ kind: "package-reference" ## 使用本包 +分区标题与说明在提供商列表上方组成一组。模型展开字段的组间距大于标签与控件间距,模型列表操作沿用统一的控件圆角尺度。 + 保存凭据或自定义提供方时保留已选模型。用户可在 composer 中选择可用模型。 提供方列表中 DeepSeek 账号排第一,DeepSeek 排第二;第三方提供方保留目录中的相对顺序。 @@ -59,7 +61,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 `llm-deepseek` 的 DeepSeek 卡片编辑端点、凭据、重试策略和模型目录。它使用 Messages,默认端点占位符为 `https://api.deepseek.com/anthropic`。 -拖动模型的排序手柄可调整它在当前提供商内的位置,也可以聚焦手柄后使用上下方向键。保存会保留顺序,取消会放弃修改。移动时,每个模型的参数、已展开选项和未完成的容量输入都会随模型保留。整行拖拽预览及遵循减少动态效果设置的行动画,与工作区排序共用基础组件;前后插入标记沿用相同样式。 +拖动模型的排序手柄可调整它在当前提供商内的位置,也可以聚焦手柄后使用上下方向键。保存会保留顺序,取消会放弃修改。移动时,每个模型的参数、已展开选项和未完成的容量输入都会随模型保留。整行拖拽预览及遵循减少动态效果设置的行动画,与工作区排序共用基础组件;前后插入标记沿用相同样式。行距与相邻拖放区域共用同一个间距值,行间空白也可接收放置。 展开**自定义设置 → 模型选项**编辑模型。模型行较窄时,主行仅显示模型 ID,展开模型行后可查看或编辑显示名称;宽度充足时,两个输入框并排显示。显示名称获得焦点时会展开该行,并保持展开,直到显式收起。所有宽度下,Tab 都先经过模型选项和删除按钮,再到显示名称。两个提供商家族共用相同的模型行布局、标签和图标:上下文窗口与最大输出 token 数分为两列,**输入类型**独占下一行,提供**文本**和**图片**复选框。未声明输入类型的模型行优先显示已安装模型的输入类型,其次是提供商默认值,最后回退为文本。已知 pi-ai 提供商会加载已安装目录,不向端点发送请求;打开模型行不会写入覆盖值。显式输入选择具有优先权,包括为视觉模型设置的仅文本覆盖。修改复选框会保存所选类型,且至少保留一种。DeepSeek 写入 `inputModalities`,pi-ai 写入 `input`。DeepSeek 取消勾选图片时,还会移除 `imagePixelBudget` 和 `imageMaxBytes`,因为适配器在没有图片输入时拒绝这些限制。在 `cordis.patch.yml` 中清除输入字段可恢复适配器继承;**恢复默认模型**会重置整个模型目录覆盖。仅声明上游模型实际能够处理的输入类型。 @@ -83,17 +85,21 @@ Models 页面包含 **DeepSeek 账号**(`deepseek-account`,英文为 **DeepS ----- +首次配置将标题和说明紧密成组,再以较大间距分隔密钥字段和操作区。 + ## 理解实现
      实现细节——点击展开 +模型标识与容量字段共用列,窄卡片中字段纵向排列。每个提供商编辑区在滚动边缘保留取消与保存操作组,聚焦控件与该操作组保持避让。 + 页面只持有脱敏后的描述符,从不持有完整设置分区:因此每次编辑都以 `settings.mutate` 路径操作落到已存分区上——每个改动字段一次 set、每个清除字段一次 unset、删除提供商行则一次 unset。 ### 校验 -键入的 API 密钥按其自身字段判定:去除首尾空白后必须非空,且每个字符都必须是可打印 ASCII(`[\x21-\x7E]`),这正是 HTTP 头值能够携带的字符集——与 `@deepseek-ai/dsh-llm` 中的 `normalizeApiKey` 互为镜像,此处复刻是因为源平面拆分禁止导入它。与粘贴的 `NAME=value` 环境行一致或包裹在匹配引号内的值,会作为同样的格式失败被拒绝。空 id、重复 id、空显式名称以及不可读、非正数或小数的容量都会在任何写入之前失败。重试字段来自命名空间发布的 `retryPolicy` schema:每个 union 分支是一种模式,数字字段成为输入框,其整数步长、最小值和最大值按 schema 检查,字符串列表成为错误码勾选列表,嵌套对象成为折叠区,其他类型的字段不显示。标签、提示、错误消息和错误码名称是本页面拥有的文案;没有标签的字段显示其 schema 键名。`@deepseek-ai/dsh-llm` 中 `resolveRetryPolicy` 在字段上限之外还强制执行两条规则:初始延迟不大于最大延迟、错误码不重复,出于同样原因在此复刻,因为 `llm-deepseek` 对它拒绝的实时策略只记录警告。卡片按字段写入策略,因此未修改的继承字段保持继承。DeepSeek 的 `models` 是一个按值整体替换的数组:编辑器先显示继承的有效行,直到第一次模型编辑把完整数组物化进用户层,重置则取消该覆盖。 +键入的 API 密钥按其自身字段判定:去除首尾空白后必须非空,且每个字符都必须是可打印 ASCII(`[\x21-\x7E]`),这正是 HTTP 头值能够携带的字符集——与 `@deepseek-ai/dsh-credentials` 中的 `normalizeApiKey` 互为镜像,此处复刻是因为源平面拆分禁止导入它。与粘贴的 `NAME=value` 环境行一致或包裹在匹配引号内的值,会作为同样的格式失败被拒绝。空 id、重复 id、空显式名称以及不可读、非正数或小数的容量都会在任何写入之前失败。重试字段来自命名空间发布的 `retryPolicy` schema:每个 union 分支是一种模式,数字字段成为输入框,其整数步长、最小值和最大值按 schema 检查,字符串列表成为错误码勾选列表,嵌套对象成为折叠区,其他类型的字段不显示。标签、提示、错误消息和错误码名称是本页面拥有的文案;没有标签的字段显示其 schema 键名。`@deepseek-ai/dsh-llm` 中 `resolveRetryPolicy` 在字段上限之外还强制执行两条规则:初始延迟不大于最大延迟、错误码不重复,出于同样原因在此复刻,因为 `llm-deepseek` 对它拒绝的实时策略只记录警告。卡片按字段写入策略,因此未修改的继承字段保持继承。DeepSeek 的 `models` 是一个按值整体替换的数组:编辑器先显示继承的有效行,直到第一次模型编辑把完整数组物化进用户层,重置则取消该覆盖。 ### 并发与凭据 diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.module.css b/packages/client/ui-settings-models/src/client/ModelsSection.module.css index a232a69045..81eff0e641 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.module.css +++ b/packages/client/ui-settings-models/src/client/ModelsSection.module.css @@ -6,7 +6,7 @@ .section { display: flex; flex-direction: column; - gap: 12px; + gap: 24px; max-width: 720px; color: var(--dsw-alias-label-primary); } @@ -42,12 +42,11 @@ .rows { list-style: none; - /* Extra air between the title/intro block and the first provider card. */ - margin: 12px 0 0; + margin: 0; padding: 0; display: flex; flex-direction: column; - gap: 8px; + gap: 12px; } /* Provider cards share the settings material; editors use the inset module fill. */ @@ -58,7 +57,7 @@ padding: 12px 14px; display: flex; flex-direction: column; - gap: 12px; + gap: 16px; } .rowHead { @@ -345,6 +344,10 @@ gap: 8px; } +.addBlock > .editorActions { + margin-top: 12px; +} + .addBlock { display: flex; flex-direction: column; @@ -474,8 +477,8 @@ position: relative; display: flex; flex-direction: column; - gap: 10px; - padding-top: 12px; + gap: 12px; + padding-top: 16px; border-top: 0.5px solid var(--dsw-alias-border-l2); } @@ -501,9 +504,11 @@ } .modelList { + --model-row-gap: 12px; + container-type: inline-size; display: flex; flex-direction: column; - gap: 8px; + gap: var(--model-row-gap); } .modelListHead { @@ -515,6 +520,9 @@ .modelEntry { container: model-row / inline-size; + display: grid; + grid-template-columns: 28px minmax(0, 1.4fr) minmax(0, 1fr) 28px 28px; + column-gap: 6px; position: relative; border: 0.5px solid var(--dsw-alias-border-l4); border-radius: var(--dsw-radius-lg); @@ -523,7 +531,8 @@ .modelRow { display: grid; - grid-template-columns: auto minmax(0, 1.4fr) minmax(0, 1fr) auto auto; + grid-column: 1 / -1; + grid-template-columns: subgrid; align-items: center; gap: 6px; } @@ -538,6 +547,11 @@ } @container model-row (max-width: 440px) { + .modelRow > .modelAdvanced { + grid-column: 1 / -1; + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .modelRow { grid-template-columns: auto minmax(0, 1fr) auto auto; } @@ -574,7 +588,7 @@ background: var(--dsw-alias-bg-module-platform); } -/* Each row owns half of the 8px gap so native drops reach the insertion line. */ +/* Cover half the row gap plus the border's inward, pixel-rounded positioning edge. */ .modelEntry::before, .modelEntry::after { content: ''; @@ -582,15 +596,15 @@ z-index: 1; left: 0; right: 0; - height: 4px; + height: calc(var(--model-row-gap) / 2 + 1px); } .modelEntry::before { - top: -4px; + top: calc(-1 * (var(--model-row-gap) / 2 + 1px)); } .modelEntry::after { - bottom: -4px; + bottom: calc(-1 * (var(--model-row-gap) / 2 + 1px)); } .modelEntry[data-drop-target='before']::before, @@ -615,11 +629,11 @@ } .modelEntry[data-drop-target='before']::before { - top: -10px; + top: calc(-1 * (var(--model-row-gap) / 2 + 6px)); } .modelEntry[data-drop-target='after']::after { - bottom: -10px; + bottom: calc(-1 * (var(--model-row-gap) / 2 + 6px)); } /* Square, label-free affordances: the row's own inputs carry the meaning, so @@ -660,10 +674,10 @@ .modelAdvanced { display: grid; - grid-column: 1 / -1; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 8px; - padding: 2px 4px; + grid-column: 2 / 4; + grid-template-columns: subgrid; + row-gap: 16px; + padding: 16px 0 6px; } /* Retry-policy fields under the mode select: codes and count, then the folded backoff values. */ @@ -706,7 +720,7 @@ display: flex; flex-direction: column; min-width: 0; - gap: 4px; + gap: 6px; } .modelInputTypes { @@ -719,7 +733,7 @@ .modelInputTypes legend { padding: 0; - margin-bottom: 4px; + margin-bottom: 6px; } .modelInputChoices { @@ -786,17 +800,18 @@ align-self: flex-start; display: inline-flex; align-items: center; - gap: 4px; - height: 28px; + gap: 6px; + height: 32px; padding: 0 10px; border: 0.5px solid var(--dsw-alias-border-l3); - border-radius: var(--dsw-radius-sm); + border-radius: var(--dsw-radius-md); background: transparent; color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; line-height: 18px; cursor: pointer; + margin-top: 4px; } @media (hover: hover) { @@ -832,7 +847,7 @@ select.input { } .input::placeholder { - color: var(--dsw-alias-label-dimmed); + color: var(--dsw-alias-label-tertiary); } .input:disabled { @@ -1001,3 +1016,15 @@ select.input { line-height: 20px; text-align: center; } + +.sectionHeader { + display: flex; + flex-direction: column; + gap: 4px; +} + +@media (pointer: coarse) { + .input { + font-size: 16px; + } +} diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.tsx b/packages/client/ui-settings-models/src/client/ModelsSection.tsx index 461ab37aad..43517c183c 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.tsx +++ b/packages/client/ui-settings-models/src/client/ModelsSection.tsx @@ -412,8 +412,10 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS return (
      -

      {t('title')}

      -

      {t('intro')}

      +
      +

      {t('title')}

      +

      {t('intro')}

      +
      {!state.writable && state.status === 'ready' ?

      {t('readOnly')}

      : null} {savedIdentity === undefined ? null diff --git a/packages/client/ui-settings-models/src/client/OnboardingModal.module.css b/packages/client/ui-settings-models/src/client/OnboardingModal.module.css index 5c5629567f..a230af5b76 100644 --- a/packages/client/ui-settings-models/src/client/OnboardingModal.module.css +++ b/packages/client/ui-settings-models/src/client/OnboardingModal.module.css @@ -23,7 +23,7 @@ } .body { - margin-top: 20px; + margin-top: 8px; } @media (max-width: 560px) { diff --git a/packages/client/ui-settings-models/src/client/apiKey.ts b/packages/client/ui-settings-models/src/client/apiKey.ts index 353488a0b5..64c7daa08c 100644 --- a/packages/client/ui-settings-models/src/client/apiKey.ts +++ b/packages/client/ui-settings-models/src/client/apiKey.ts @@ -4,7 +4,7 @@ */ /** - * Twin of `normalizeApiKey` in `@deepseek-ai/dsh-llm`: printable ASCII, space + * Twin of `normalizeApiKey` in `@deepseek-ai/dsh-credentials`: printable ASCII, space * excluded. Client packages reference only client packages, so the charset * rule is mirrored here rather than imported; keep the two in step, as * `validateDeepSeekModels` is kept in step with the host's `catalogModel`. diff --git a/packages/client/ui-settings-subagent/src/client/SubagentModelSelectionFields.tsx b/packages/client/ui-settings-subagent/src/client/SubagentModelSelectionFields.tsx index 39d733f688..2bfc69280b 100644 --- a/packages/client/ui-settings-subagent/src/client/SubagentModelSelectionFields.tsx +++ b/packages/client/ui-settings-subagent/src/client/SubagentModelSelectionFields.tsx @@ -1,4 +1,4 @@ -/** User control for model-selectable subagent delegation in new sessions. */ +/** User control for model-selectable subagent delegation in every session. */ import { Switch } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' diff --git a/packages/client/ui-settings-subagent/src/client/locales.ts b/packages/client/ui-settings-subagent/src/client/locales.ts index 6a575814d8..6f3abe1cdc 100644 --- a/packages/client/ui-settings-subagent/src/client/locales.ts +++ b/packages/client/ui-settings-subagent/src/client/locales.ts @@ -46,7 +46,7 @@ export const en: Record = { subagentCapacityInvalid: 'Enter a whole number of 1 or more.', subagentModelSelectionTitle: 'Model selection', subagentModelSelectionToggle: 'Allow agents to choose models for Subagents', - subagentModelSelectionChoose: 'When enabled, agents can choose a provider, model, and reasoning effort for each Subagent from the authorized models below. Applies only to new sessions.', + subagentModelSelectionChoose: 'When enabled, agents can choose a provider, model, and reasoning effort for each Subagent from the authorized models below. Changes apply immediately to every session.', subagentModelSelectionAllowed: 'Models agents may choose', subagentModelSelectionLoading: 'Loading models…', subagentModelSelectionLoadFailed: 'Models could not be loaded.', @@ -85,7 +85,7 @@ export const zh: Record = { subagentCapacityInvalid: '请输入不小于 1 的整数。', subagentModelSelectionTitle: '模型选择', subagentModelSelectionToggle: '允许 Agent 为子智能体选择模型', - subagentModelSelectionChoose: '开启后,Agent 可以从下方授权模型中,为每个子智能体选择提供方、模型和推理强度。仅影响新会话。', + subagentModelSelectionChoose: '开启后,Agent 可以从下方授权模型中,为每个子智能体选择提供方、模型和推理强度。修改会立即对所有会话生效。', subagentModelSelectionAllowed: 'Agent 可选择的模型', subagentModelSelectionLoading: '正在加载模型…', subagentModelSelectionLoadFailed: '无法加载模型。', @@ -133,7 +133,7 @@ export const ja = { 'subagentCapacityInvalid': '1以上の整数を入力してください。', 'subagentModelSelectionTitle': 'モデル選択', 'subagentModelSelectionToggle': 'エージェントによるサブエージェントのモデル選択を許可', - 'subagentModelSelectionChoose': '有効にすると、エージェントは以下の許可されたモデルからサブエージェントごとにプロバイダー、モデル、推論強度を選択できます。新しいセッションにのみ適用されます。', + 'subagentModelSelectionChoose': '有効にすると、エージェントは以下の許可されたモデルからサブエージェントごとにプロバイダー、モデル、推論強度を選択できます。変更はすべてのセッションに直ちに適用されます。', 'subagentModelSelectionAllowed': 'エージェントが選択可能なモデル', 'subagentModelSelectionLoading': 'モデルを読み込み中…', 'subagentModelSelectionLoadFailed': 'モデルを読み込めませんでした。', @@ -172,7 +172,7 @@ export const es = { subagentCapacityInvalid: 'Introduzca un número entero de 1 o más.', subagentModelSelectionTitle: 'Selección de modelo', subagentModelSelectionToggle: 'Permitir a los agentes elegir modelos para Subagentes', - subagentModelSelectionChoose: 'Cuando está habilitado, los agentes pueden elegir un proveedor, modelo y esfuerzo de razonamiento para cada subagente entre los modelos autorizados a continuación. Aplica sólo para sesiones nuevas.', + subagentModelSelectionChoose: 'Cuando está habilitado, los agentes pueden elegir un proveedor, modelo y esfuerzo de razonamiento para cada subagente entre los modelos autorizados a continuación. Los cambios se aplican de inmediato a todas las sesiones.', subagentModelSelectionAllowed: 'Los agentes modelos pueden elegir', subagentModelSelectionLoading: 'Cargando modelos…', subagentModelSelectionLoadFailed: 'No se pudieron cargar los modelos.', @@ -211,7 +211,7 @@ export const fr = { subagentCapacityInvalid: 'Entrez un nombre entier de 1 ou plus.', subagentModelSelectionTitle: 'Sélection du modèle', subagentModelSelectionToggle: 'Autoriser les agents à choisir des modèles pour les sous-agents', - subagentModelSelectionChoose: "Lorsque cette option est activée, les agents peuvent choisir un fournisseur, un modèle et un effort de raisonnement pour chaque sous-agent parmi les modèles autorisés ci-dessous. S'applique uniquement aux nouvelles sessions.", + subagentModelSelectionChoose: "Lorsque cette option est activée, les agents peuvent choisir un fournisseur, un modèle et un effort de raisonnement pour chaque sous-agent parmi les modèles autorisés ci-dessous. Les modifications s'appliquent immédiatement à toutes les sessions.", subagentModelSelectionAllowed: 'Les agents modèles peuvent choisir', subagentModelSelectionLoading: 'Chargement des modèles…', subagentModelSelectionLoadFailed: "Les modèles n'ont pas pu être chargés.", @@ -250,7 +250,7 @@ export const de = { subagentCapacityInvalid: 'Geben Sie eine ganze Zahl von 1 oder mehr ein.', subagentModelSelectionTitle: 'Modellauswahl', subagentModelSelectionToggle: 'Erlauben Sie Agenten, Modelle für Subagenten auszuwählen', - subagentModelSelectionChoose: 'Wenn diese Option aktiviert ist, können Agenten aus den unten aufgeführten autorisierten Modellen einen Anbieter, ein Modell und einen Argumentationsaufwand für jeden Subagenten auswählen. Gilt nur für neue Sitzungen.', + subagentModelSelectionChoose: 'Wenn diese Option aktiviert ist, können Agenten aus den unten aufgeführten autorisierten Modellen einen Anbieter, ein Modell und einen Argumentationsaufwand für jeden Subagenten auswählen. Änderungen gelten sofort für alle Sitzungen.', subagentModelSelectionAllowed: 'Modelagenten können wählen', subagentModelSelectionLoading: 'Modelle werden geladen…', subagentModelSelectionLoadFailed: 'Modelle konnten nicht geladen werden.', @@ -289,7 +289,7 @@ export const ru = { subagentCapacityInvalid: 'Введите целое число от 1 или более.', subagentModelSelectionTitle: 'Выбор модели', subagentModelSelectionToggle: 'Разрешить агентам выбирать модели для субагентов', - subagentModelSelectionChoose: 'Если этот параметр включен, агенты могут выбирать поставщика, модель и усилия по обоснованию для каждого субагента из авторизованных моделей, указанных ниже. Применяется только к новым сеансам.', + subagentModelSelectionChoose: 'Если этот параметр включен, агенты могут выбирать поставщика, модель и усилия по обоснованию для каждого субагента из авторизованных моделей, указанных ниже. Изменения сразу применяются ко всем сеансам.', subagentModelSelectionAllowed: 'Модели агенты могут выбирать', subagentModelSelectionLoading: 'Загрузка моделей…', subagentModelSelectionLoadFailed: 'Не удалось загрузить модели.', @@ -328,7 +328,7 @@ export const pt = { subagentCapacityInvalid: 'Insira um número inteiro de 1 ou mais.', subagentModelSelectionTitle: 'Seleção de modelo', subagentModelSelectionToggle: 'Permitir que os agentes escolham modelos para subagentes', - subagentModelSelectionChoose: 'Quando ativado, os agentes podem escolher um provedor, um modelo e um esforço de raciocínio para cada subagente dentre os modelos autorizados abaixo. Aplica-se apenas a novas sessões.', + subagentModelSelectionChoose: 'Quando ativado, os agentes podem escolher um provedor, um modelo e um esforço de raciocínio para cada subagente dentre os modelos autorizados abaixo. As alterações se aplicam imediatamente a todas as sessões.', subagentModelSelectionAllowed: 'Os agentes de modelos podem escolher', subagentModelSelectionLoading: 'Carregando modelos…', subagentModelSelectionLoadFailed: 'Não foi possível carregar os modelos.', diff --git a/packages/client/ui-settings-subagent/src/client/subagent-model-selection-card-controller.ts b/packages/client/ui-settings-subagent/src/client/subagent-model-selection-card-controller.ts index 3ea37e993e..8be02346fc 100644 --- a/packages/client/ui-settings-subagent/src/client/subagent-model-selection-card-controller.ts +++ b/packages/client/ui-settings-subagent/src/client/subagent-model-selection-card-controller.ts @@ -16,7 +16,7 @@ export interface AllowedSubagentModel { /** Settings fields stored for subagent model selection. */ export interface SubagentModelSelectionSettings { - /** Whether model-facing child route selection applies to new Sessions. */ + /** Whether model-facing child route selection is authorized; each delegation reads the saved value. */ enabled: boolean /** Exact child routes offered to newly composed top-level Sessions. */ allowedModels: AllowedSubagentModel[] diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index 5a1a4df3b2..6c4ca00638 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -30,8 +30,8 @@ en: 9767f17ca0f02ae3 zh: 8e475d6d3d670702 /deepseek-ai-dsh-client-ui-settings/understand-the-implementation: - en: 84b6449030ffabe7 - zh: 958382ead3ab0407 + en: 6741f576de0585c2 + zh: 5b621d137e52b63e /deepseek-ai-dsh-client-ui-settings/understand-the-implementation/the-describe-mirror: en: 0cd270ddcac46776 zh: 4e03bf1d153b3f04 diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index a575d5b5e2..6cb716d1dc 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -55,7 +55,7 @@ A committed write folds its answer into the shared mirror. Refused writes refres ## Understand the implementation -The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. +The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. The optional `settings.notice` contribution receives openSettings and renders in a zero-height, full-width row above the launcher row, floating over the sidebar list; the shell hides that row in the collapsed rail without unmounting it.
      Implementation internals — click to expand diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index 3503c75b9d..ba4e030086 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -55,7 +55,7 @@ kind: "package-reference" ## 理解实现 -可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。 +可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。可选的 `settings.notice` 贡献接收 openSettings,渲染在入口行上方零高度的满宽行中,浮在侧栏列表之上;折叠轨道中外壳隐藏该行但不卸载它。
      实现细节——点击展开 diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts index f9b89e70a6..7c2c5aedcf 100644 --- a/packages/client/ui-settings/src/client/contract/slots.ts +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -30,6 +30,12 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Optional sidebar account launcher; opens the shell-owned settings panel. */ 'settings.launcher': { kind: 'single'; scope: 'root'; owner: SettingsLauncherOwnerProps } + /** + * Optional content anchored above the launcher row at the launcher row's + * full width. The row takes no height, so the content floats over the + * sidebar list; the shell hides it in the rail without unmounting it. + */ + 'settings.notice': { kind: 'single'; scope: 'root'; owner: SettingsNoticeOwnerProps } /** * The sidebar-foot trigger row content: icon + label, supplied as slot @@ -167,6 +173,12 @@ export interface SettingsOnboardingOwnerProps { openSection: (id: string) => void } +/** Settings navigation for the row above the launcher row. */ +export interface SettingsNoticeOwnerProps { + /** @param sectionId - section to open; absent uses the shell's default section. */ + openSettings: (sectionId?: string) => void +} + /** Sidebar launcher geometry and settings navigation. */ export interface SettingsLauncherOwnerProps { /** Whether the sidebar shows labels. */ diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index 6b23b57d2d..7f6e7d7bef 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -14,7 +14,7 @@ import { SettingsDescribeMirror } from './settings-mirror.ts' export type { SettingsLauncherOwnerProps, SettingsGeneralItemOwnerProps, SettingsHeaderOwnerProps, SettingsOnboardingOwnerProps, - SettingsSectionIconOwnerProps, SettingsSectionOwnerProps, SettingsSectionViewProps, SettingsTriggerOwnerProps, + SettingsNoticeOwnerProps, SettingsSectionIconOwnerProps, SettingsSectionOwnerProps, SettingsSectionViewProps, SettingsTriggerOwnerProps, } from './contract/slots.ts' export type { ConfigForms } from './config-form.ts' export type { ConfigForm, ConfigFormSnapshot } from './config-form-types.ts' diff --git a/packages/client/ui-shortcuts/README.i18n.yaml b/packages/client/ui-shortcuts/README.i18n.yaml index 48f267d1ad..22f5e9ef91 100644 --- a/packages/client/ui-shortcuts/README.i18n.yaml +++ b/packages/client/ui-shortcuts/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 0cd57b7b8d8c9b59 /deepseek-ai-dsh-client-ui-shortcuts/use-this-package: - en: 84a109505e902f0a - zh: 87053c34cf4da672 + en: bbb365ff236edf02 + zh: b2e3bdff99e4d663 /deepseek-ai-dsh-client-ui-shortcuts/understand-the-implementation: - en: f56f2610e7258825 - zh: 249d7cdd55c57166 + en: 4f04c5262cc25a0d + zh: 86016074dd8d71c5 /deepseek-ai-dsh-client-ui-shortcuts/further-exploration: en: 8fe02ef5221e434d zh: 3aabfcfeb6d49a0e diff --git a/packages/client/ui-shortcuts/README.md b/packages/client/ui-shortcuts/README.md index d6bf0cf06b..d11a2dc521 100644 --- a/packages/client/ui-shortcuts/README.md +++ b/packages/client/ui-shortcuts/README.md @@ -25,6 +25,8 @@ Browse the commands available in the current window and find them by action, Eng ## Use this package +Shortcut save feedback reuses the shared 16px Regular warning and circled-check glyphs. + The Web app bundle mounts this package together with `shortcuts`. The reference shows only registered commands and existing fixed input actions. Desktop shows the effective device keys; commands without a Web default show No shortcut. The Settings entry and Mod+/ open the same single dialog, titled “Keyboard shortcuts” in English and “快捷键” in Chinese. Its 480×600 CSS-pixel card shrinks to fit smaller windows; the header and search remain above an internally scrolling list. The search field receives focus on open without changing its border color. Automatic entry and return focus in the reference, recorder, and reset confirmation omit outlines, including returns after Escape and application close shortcuts. Containers remain outline-free, and Tab and directional navigation retain their visible focus indicators. The Settings entry follows Coding Tools and is labeled “Edit shortcuts”, with an “Open from anywhere” shortcut tooltip, and uses a filled button with the same standard radius as adjacent settings controls and no dropdown icon and reads the same effective binding for its tooltip and `aria-keyshortcuts`; both are absent without a binding. `Mod+/` opens the reference when no modal is open or Settings is in front, and closes it when the reference is in front. While the reference is in front, the Settings command cannot open or close Settings. Held-key repeats are ignored. Recording, pending writes, and a nested confirmation prevent the reference shortcut from closing the dialog. @@ -43,6 +45,8 @@ Hover an application row to highlight its rounded surface and reveal the edit ic
      Implementation internals — click to expand +The search icon and empty query hint use the same foreground role; entered text keeps the primary text color. + The General Settings entry and shell overlay share one declared interaction store. Catalog and configuration updates arrive through injected observable hooks; recording and persistence use injected service callbacks. The shared modal primitive owns top-layer Escape, Tab traversal, and restoration to the invoking control. All fixed actions come from the service's observable fixed catalog. Conversation and approval plugins contribute their own actions; this integration contributes shared menu actions. Rows follow locale updates and disappear when their registration is disposed. diff --git a/packages/client/ui-shortcuts/README.zh.md b/packages/client/ui-shortcuts/README.zh.md index a8f61d7466..c473ba6d68 100644 --- a/packages/client/ui-shortcuts/README.zh.md +++ b/packages/client/ui-shortcuts/README.zh.md @@ -25,6 +25,8 @@ kind: "package-reference" ## 使用此包 +快捷键保存反馈复用共享的 16px Regular 警告与圆环勾选图标。 + Web 应用 bundle 将此包与 `shortcuts` 一同挂载。速查仅展示已注册命令和现有固定输入操作。桌面端展示设备对应的有效键位;没有 Web 默认键位的命令显示“暂无快捷键”。设置入口与 Mod+/打开同一个单实例弹窗,中文标题为“快捷键”,英文标题为“Keyboard shortcuts”。卡片尺寸为 480×600 CSS 像素,小窗口中缩小以保持可见;标题和搜索框位于内部滚动列表上方。打开时聚焦搜索框,边框颜色保持不变。速查窗、录键框及重置确认框内的自动进入和回焦均不绘制外轮廓线,包括通过 Esc 和应用关闭快捷键触发的回焦。容器仍不绘制焦点外框,Tab 和方向键导航保留可见焦点提示。设置入口位于代码工作工具之后,标为“编辑快捷键”,快捷键提示文案为“全局唤起查看”,使用与相邻设置控件一致的标准圆角填充按钮,不带下拉图标,并从同一有效绑定读取提示及 `aria-keyshortcuts`;没有绑定时不显示提示,也不设置该属性。 没有模态弹窗或设置位于最前方时,`Mod+/` 打开速查;速查位于最前方时,该快捷键关闭速查。速查位于前方时,设置命令不能打开或关闭设置。长按产生的重复按键不执行操作。录键期间、写入尚未完成或嵌套确认框打开时,速查快捷键不会关闭弹窗。 @@ -43,6 +45,8 @@ Web 应用 bundle 将此包与 `shortcuts` 一同挂载。速查仅展示已注
      实现细节——点击展开 +搜索图标与空查询提示使用同一前景色角色,已输入文字保留主要文字色。 + 通用设置入口与 shell 弹层共享一个已声明的交互 store。目录与配置通过注入的 observable hook 更新;录键和持久化使用注入的服务回调。共用模态组件负责顶层 Esc、Tab 导航和关闭后恢复触发控件焦点。 所有固定操作均来自服务的可观察固定目录。Conversation 和审批插件贡献各自的操作;本集成贡献共用菜单操作。行内容跟随语言更新,并在其注册被释放时移除。 diff --git a/packages/client/ui-shortcuts/src/client/Icons.tsx b/packages/client/ui-shortcuts/src/client/Icons.tsx index 03dfcf7220..5bb1afa9c6 100644 --- a/packages/client/ui-shortcuts/src/client/Icons.tsx +++ b/packages/client/ui-shortcuts/src/client/Icons.tsx @@ -1,8 +1,8 @@ /** Supplied shortcut-control and feedback artwork, colored by the owning UI. */ +import { IconCheckCircleOutlineRegular, IconWarningOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' + const artwork = { edit: <>, - error: <>, - success: <>, } /** @@ -10,7 +10,9 @@ const artwork = { * @param props - glyph kind and semantic color class. * @returns an ornamental SVG hidden from assistive technology. */ -export function ShortcutIcon({ kind, className }: { kind: keyof typeof artwork; className?: string | undefined }) { - const size = kind === 'edit' ? 12 : 16 +export function ShortcutIcon({ kind, className }: { kind: 'edit' | 'error' | 'success'; className?: string | undefined }) { + if (kind === 'error') return + if (kind === 'success') return + const size = 12 return } diff --git a/packages/client/ui-shortcuts/src/client/Reference.module.css b/packages/client/ui-shortcuts/src/client/Reference.module.css index 09d2e2a0ed..58a5d8cc69 100644 --- a/packages/client/ui-shortcuts/src/client/Reference.module.css +++ b/packages/client/ui-shortcuts/src/client/Reference.module.css @@ -115,7 +115,7 @@ border-radius: 12px; background: var(--dsw-alias-markdown-code-block); } -.searchIcon { flex: none; color: var(--dsw-alias-label-caption); } +.searchIcon { flex: none; color: var(--dsw-alias-label-tertiary); } .search { width: 100%; min-width: 0; diff --git a/packages/client/ui-sidebar-browser/src/client/browser/url.ts b/packages/client/ui-sidebar-browser/src/client/browser/url.ts index 3ced712338..5bcadea93a 100644 --- a/packages/client/ui-sidebar-browser/src/client/browser/url.ts +++ b/packages/client/ui-sidebar-browser/src/client/browser/url.ts @@ -35,7 +35,7 @@ export function parseBrowserAddress(input: string, applicationOrigin?: string): if (applicationOrigin !== undefined && applicationOrigin !== 'null') { try { if (url.origin === new URL(applicationOrigin).origin) return { ok: false, reason: 'application-origin' } - } catch { + } catch (_invalidApplicationOrigin) { // An unavailable application origin cannot grant access to a target. } } diff --git a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml index 91373281f1..64664e552a 100644 --- a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml +++ b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml @@ -27,8 +27,8 @@ en: 595499992ceea693 zh: 83c6147c46a80dca /deepseek-ai-dsh-client-ui-sidebar-documentpreview/office-preview: - en: c683150a3c92be68 - zh: 65b63c0961a8b2fb + en: bebd8e7099be43eb + zh: 36de81ff9913d049 /deepseek-ai-dsh-client-ui-sidebar-documentpreview/navigation: en: 33215200b3e4a8ed zh: 499e4b834f2db95a diff --git a/packages/client/ui-sidebar-documentpreview/README.md b/packages/client/ui-sidebar-documentpreview/README.md index 6453a874e8..2948e4e201 100644 --- a/packages/client/ui-sidebar-documentpreview/README.md +++ b/packages/client/ui-sidebar-documentpreview/README.md @@ -114,6 +114,8 @@ A yellow rounded-triangle warning appears before Reload in the document toolbar
      Office implementation — click to expand +The compact external-open frame precedes the workspace navigator toggle in the preview header. It leaves a separate gap after the display controls. When the action slot has no rendered content, its group contributes no gap, and the remaining icons align with the upper toolbar columns. + Office registration, loading, caching, and font notices live in `src/client/office/`. The injected Office face writes converted PDF bytes, font metadata, and failures through the declared store actions. The Office body triggers loading, binds cancellation to its lifecycle, and declares a nested PDF slot that reuses the lazy PDF body and its tab viewing state. The keyed `sidebar.right.tab.document.action` slot places renderer controls before Reload. The Office action shares the body’s store and reads only the current revision’s font metadata. Registration remains available without the Host renderer; optional `remote.officeKit` and `remote.workspaceFiles` injections supply conversion and freshness callbacks, and their removal restores unavailable guidance. Registrations and tab retention follow effect lifetimes. The [conversion service](../../document/office-kit/README.md) owns the Host Remote methods, mounted by `api/remotes`. The Office Remote returns converted PDFs as native `Uint8Array` values through Connection's multipart binary transport. Renderers borrow retained bytes read-only and copy them before Worker transfer. diff --git a/packages/client/ui-sidebar-documentpreview/README.zh.md b/packages/client/ui-sidebar-documentpreview/README.zh.md index 3e846d1f63..6a8f90214b 100644 --- a/packages/client/ui-sidebar-documentpreview/README.zh.md +++ b/packages/client/ui-sidebar-documentpreview/README.zh.md @@ -114,6 +114,8 @@ CSV 和 TSV 默认使用表格查看器,也可选择纯文本;CSV 还提供
      Office 实现——点击展开 +紧凑的外部打开边框位于预览标题行的工作区导航开关之前。它与显示控件之间留出独立间距。当操作 slot 没有渲染内容时,该组不占间距,剩余图标与上排工具栏共用纵向列。 + Office 注册、加载、缓存和字体提示位于 `src/client/office/`。注入的 Office face 通过已声明的 store action 写入转换后的 PDF 字节、字体元数据和失败。Office 正文触发加载,将取消绑定到自身生命周期,并声明嵌套 PDF slot,复用惰性 PDF 正文及其 tab 阅读状态。keyed slot `sidebar.right.tab.document.action` 将渲染器操作放在刷新按钮前。Office 操作与正文共享 store,仅读取当前 revision 的字体元数据。Host 渲染器缺失时,注册仍然可用;可选的 `remote.officeKit` 和 `remote.workspaceFiles` 注入提供转换与版本检查回调,移除后恢复不可用提示。注册和 tab 状态保留都遵循 effect 生命周期。[转换服务](../../document/office-kit/README.zh.md)拥有 Host Remote 方法,由 `api/remotes` 挂载。 Office Remote 通过 Connection 的 multipart 二进制传输返回原生 `Uint8Array` PDF。渲染器以只读方式借用保留的字节,并在传给 Worker 前复制。 diff --git a/packages/client/ui-sidebar-documentpreview/src/client/PreviewFrame.tsx b/packages/client/ui-sidebar-documentpreview/src/client/PreviewFrame.tsx index 5b529fffee..6387316ea1 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/PreviewFrame.tsx +++ b/packages/client/ui-sidebar-documentpreview/src/client/PreviewFrame.tsx @@ -70,7 +70,7 @@ export function PreviewFrame({
      {tools} - {handoff} +
      {handoff}
      diff --git a/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.module.css b/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.module.css index 5a3c128bd1..80228a5976 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.module.css +++ b/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.module.css @@ -50,6 +50,18 @@ border-bottom: 0.5px solid var(--dsw-alias-border-l3); } +/* Match the trailing icon box above, retaining its internal glyph whitespace. */ +.externalActions { + display: flex; + flex: none; + margin-inline-start: 6px; + margin-inline-end: 6px; +} + +.externalActions:not(:has(:global([data-slot]) > *)) { + display: none; +} + .path { margin-right: 12px; } diff --git a/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx b/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx index 8e0c2b089c..c7da6962d9 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx +++ b/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx @@ -884,7 +884,7 @@ describe('TextPreview — workspace navigator Factories', () => { const toggle = view.container.querySelector('[data-textpreview-path]')?.parentElement?.lastElementChild const handoff = view.container.querySelector('[data-slot="sidebar.right.tab.document.actions"]') expect(handoff?.getAttribute('data-slot-path')).toBe(ABSOLUTE_PATH) - expect(toggle?.previousElementSibling).toBe(handoff) + expect(toggle?.previousElementSibling).toBe(handoff?.parentElement) navigator.tabIndex = 0 navigator.focus() navigator.scrollTop = 64 @@ -898,7 +898,7 @@ describe('TextPreview — workspace navigator Factories', () => { expect(view.container.querySelector('[data-textpreview-path]')?.parentElement?.lastElementChild).toBe(toggle) // The handoff keeps its seat between the tools and the toggle in every state. expect(view.container.querySelector('[data-slot="sidebar.right.tab.document.actions"]')).toBe(handoff) - expect(toggle?.previousElementSibling).toBe(handoff) + expect(toggle?.previousElementSibling).toBe(handoff?.parentElement) expect(document.activeElement).toBe(navigator) expect(navigator.scrollTop).toBe(64) }) diff --git a/packages/client/ui-sidebar-files/README.i18n.yaml b/packages/client/ui-sidebar-files/README.i18n.yaml index dd3d34d879..1c386b73cc 100644 --- a/packages/client/ui-sidebar-files/README.i18n.yaml +++ b/packages/client/ui-sidebar-files/README.i18n.yaml @@ -15,8 +15,8 @@ en: 81cb6e051699a7b4 zh: 566d0278acae69fa /deepseek-ai-dsh-client-ui-sidebar-files/what-it-registers: - en: c4b8f3a52f68bd51 - zh: 30b580320637572c + en: 5816aa2ff177de01 + zh: 63a219b23ad46ab3 /deepseek-ai-dsh-client-ui-sidebar-files/the-navigator: en: 3424600b15bde2d2 zh: 2cf1c99ffef2ad50 @@ -39,5 +39,5 @@ en: f28a32e47e684f5c zh: e5e38014048ebe59 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work/dev-note: - en: 1ec99e9fb6b4c948 - zh: c4f7883934307c3c + en: 753149828a165920 + zh: a4daff5bb946b14e diff --git a/packages/client/ui-sidebar-files/README.md b/packages/client/ui-sidebar-files/README.md index 3991ccec18..a9384768f2 100644 --- a/packages/client/ui-sidebar-files/README.md +++ b/packages/client/ui-sidebar-files/README.md @@ -30,10 +30,10 @@ Browse a Session's workspace tree beside the files you preview. Each pane keeps The `workspace.files` command shows the navigator beside a docked preview or expands the search bar on an existing docked files page, and moves keyboard focus to its search field, keeping the tab; from the conversation it uses the current Session's active dock pane. Elsewhere — a tab without the navigator, a Session without a working directory, a floating tab — it opens or focuses the files page, whose tree always shows. A guide gives way to the files page, and repeated opens retain one files page per pane. Desktop defaults to Mod+P. The guide entry displays the effective shortcut; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves this command unbound by default. - **The type** — `ctx.sidebarRightTabs.register(...)` with kind `files`, id `@deepseek-ai/dsh-client-ui-sidebar-files`, band `builtin`, no patterns, and one guide entry (order 10, its title and description from the `sidebarFiles` namespace, its glyph a yellow folder) that opens the type. -- **The page body** — the keyed `sidebar.right.pane.tab` seat under that id. Its header row spans the page and shows the root through the shared [`PathLabel`](../ui-primitives/README.md#component-catalog) with subdued directories and a primary final segment; a clipped path retains its trailing characters with a left-edge fade, and hovering reveals the full path. The tree's reload control and search-bar toggle precede the Session-scoped `sidebar.right.tab.files.actions` list, which the page's registration declares, with the displayed root passed as `absolutePath`; [`ui-open-in-app`](../ui-open-in-app/README.md) contributes the workspace directory opener. The pane's navigator fills the page below the header, docked or floating, and has no navigator toggle there. +- **The page body** — the keyed `sidebar.right.pane.tab` seat under that id. Its header row spans the page and shows the root through the shared [`PathLabel`](../ui-primitives/README.md#component-catalog) with subdued directories and a primary final segment; a clipped path retains its trailing characters with a left-edge fade, and hovering reveals the full path. The tree's reload control and search-bar toggle precede the Session-scoped `sidebar.right.tab.files.actions` list, which the page's registration declares, with the displayed root passed as `absolutePath`; [`ui-open-in-app`](../ui-open-in-app/README.md) contributes the workspace directory opener. The trailing opener frame aligns with the visible right edge of the upper collapse glyph, inside its hit target. A split opener keeps Search centered under Split. A single-application control keeps its intrinsic width and the ordinary 4px gap, without reserving an alignment column. Without rendered directory actions, this column and its gap disappear, and Search aligns under Collapse. The pane's navigator fills the page below the header, docked or floating, and has no navigator toggle there. - **The rows** — the root-scoped Component Factory `sidebar.files.tree`, with caller-owned entries and a local `accessory` slot; see [Reusable tree Factory](#tree-factory). - **The navigator** — the Session-scoped Component Factory `sidebar.files.navigator`, rendered directly by the page body and [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.md) beside every preview, docked or floating. It draws the [search bar](#search), the tree, and its resize edge without a header of its own: beside a preview the preview's header is the only one, and the tree's reload and directory actions stay on the `files` page. -- **The toggle** — the Session-scoped Factory `sidebar.files.navigator.toggle`, rendered directly at the end of the preview header with `useTabInfo`. Both Factories share the page's store handle and inject face, retaining one open choice per pane; the page body has no navigator toggle. +- **The toggle** — the Session-scoped Factory `sidebar.files.navigator.toggle`, rendered directly at the end of the preview header with `useTabInfo`. The folder artwork uses 16px inside the shared 28px hit target to balance its landscape silhouette against the adjacent toolbar glyphs. Both Factories share the page's store handle and inject face, retaining one open choice per pane; the page body has no navigator toggle. - **The chip title** — the keyed `sidebar.right.pane.tab.title` seat under that id: a shared `FileTypeIcon` folder glyph at 16px before the type's label. The tree's own rows never draw this sheet. The [registration](src/client/index.ts) assembles the page, navigator, toggle, and tree Factories over the shared [files face](src/client/face.ts) and [pane store](src/client/store.ts). @@ -124,6 +124,8 @@ None; directory listings and searches travel over the Remote and assemble no mod
      Working context for maintainers — click to expand +Each nested icon box starts on the parent label column; indentation includes the parent icon box and its text gap, retaining the icon’s internal whitespace. + None. The page refresh shortcut refreshes the files page's tree through its ordinary directory reader while the tree shows; on a preview it reloads the preview. The page's reload control displays the effective binding on hover and keyboard focus. diff --git a/packages/client/ui-sidebar-files/README.zh.md b/packages/client/ui-sidebar-files/README.zh.md index 5c5e776ad2..4ee85ac4f3 100644 --- a/packages/client/ui-sidebar-files/README.zh.md +++ b/packages/client/ui-sidebar-files/README.zh.md @@ -30,10 +30,10 @@ kind: "package-reference" 命令 `workspace.files` 在焦点分栏内显示停靠预览旁的导航栏,或展开已有停靠文件页的搜索栏,并把键盘焦点移到其搜索框,保留该 tab;从聊天区触发时使用当前会话的活动停靠分栏。其他情况下(不带导航栏的 tab、没有工作目录的会话、浮动 tab)打开或聚焦文件页,文件页的目录树始终显示。文件页替换开始页,同一分栏内重复打开仍保留一个文件页。桌面默认键为 Mod+P。开始页入口显示有效快捷键;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 默认不绑定此命令。 - **类型**:`ctx.sidebarRightTabs.register(...)`,kind 为 `files`,id 为 `@deepseek-ai/dsh-client-ui-sidebar-files`,档位 `builtin`,没有 patterns,另有一个打开该类型的引导页入口(order 10,标题与描述取自 `sidebarFiles` 命名空间,图标为黄色文件夹)。 -- **文件页正文**:以该 id 为键的 `sidebar.right.pane.tab` slot。其标题行横跨页面,通过共享的 [`PathLabel`](../ui-primitives/README.zh.md#component-catalog) 显示根路径,目录使用弱化颜色,最后一段使用主色;路径过长时保留尾部字符并在左侧渐隐,悬停显示完整路径。目录树的重新读取控件和搜索栏开关位于由文件页注册声明的 Session 作用域 `sidebar.right.tab.files.actions` 列表之前(通过 `absolutePath` 传入当前显示的根目录);[`ui-open-in-app`](../ui-open-in-app/README.zh.md) 在此提供工作区目录打开按钮。标题行下方由该分栏的导航栏铺满整页,停靠与浮动时都一样,这里没有导航栏开关。 +- **文件页正文**:以该 id 为键的 `sidebar.right.pane.tab` slot。其标题行横跨页面,通过共享的 [`PathLabel`](../ui-primitives/README.zh.md#component-catalog) 显示根路径,目录使用弱化颜色,最后一段使用主色;路径过长时保留尾部字符并在左侧渐隐,悬停显示完整路径。目录树的重新读取控件和搜索栏开关位于由文件页注册声明的 Session 作用域 `sidebar.right.tab.files.actions` 列表之前(通过 `absolutePath` 传入当前显示的根目录);[`ui-open-in-app`](../ui-open-in-app/README.zh.md) 在此提供工作区目录打开按钮。末端打开控件的边框与上排折叠图标的可见右边缘对齐,位于其热区内侧。双按钮打开控件使搜索与上排分屏图标中心对齐。单应用控件按实际宽度自然靠右,保留普通的 4px 间距,不预留对齐列。目录操作没有渲染内容时,该列及其间距消失,搜索与上排折叠图标对齐。标题行下方由该分栏的导航栏铺满整页,停靠与浮动时都一样,这里没有导航栏开关。 - **各行**:root 作用域的 Component Factory `sidebar.files.tree`,接收调用方的条目和局部 `accessory` slot;见[复用目录树 Factory](#tree-factory)。 - **导航栏**:Session 作用域的 Component Factory `sidebar.files.navigator`。文件页正文和 [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.zh.md) 直接渲染它,显示在每个预览旁,无论停靠还是浮动。它绘制[搜索栏](#search)、目录树及其调整宽度的边缘,没有自己的标题行:预览旁只有预览自己的标题行,目录树的重新读取与目录操作留在 `files` 页上。 -- **开关**:Session 作用域的 Factory `sidebar.files.navigator.toggle`,在预览头部末端直接渲染,传入 `useTabInfo`。两个 Factory 共用文件页的 store handle 和 inject face,每个分栏保留一份开关状态;文件页正文没有导航栏开关。 +- **开关**:Session 作用域的 Factory `sidebar.files.navigator.toggle`,在预览头部末端直接渲染,传入 `useTabInfo`。文件夹图形使用 16px,在共用的 28px 热区内补足横向轮廓的视觉尺寸,与相邻工具栏图标保持平衡。两个 Factory 共用文件页的 store handle 和 inject face,每个分栏保留一份开关状态;文件页正文没有导航栏开关。 - **标签页标题**:以该 id 为键的 `sidebar.right.pane.tab.title` slot:类型标签前的一枚 16px 共享 `FileTypeIcon` 文件夹图标。树本身的行不画这枚图标。 [注册入口](src/client/index.ts) 在共享 [files face](src/client/face.ts) 与[分栏 store](src/client/store.ts) 上组装文件页、导航栏、开关和目录树 Factory。 @@ -124,6 +124,8 @@ kind: "package-reference"
      维护者工作上下文——点击展开 +每层子级图标框承接父级文字列;缩进包含父级图标框及图文间距,并保留图标内部留白。 + 无。 页面刷新快捷键在文件页上、目录树显示期间通过常规目录读取器刷新其树,在预览中重新载入预览。文件页的重新读取控件在悬停和键盘聚焦时显示有效绑定。 diff --git a/packages/client/ui-sidebar-files/src/client/FileTree.module.css b/packages/client/ui-sidebar-files/src/client/FileTree.module.css index fe7cf766fc..0179f99c73 100644 --- a/packages/client/ui-sidebar-files/src/client/FileTree.module.css +++ b/packages/client/ui-sidebar-files/src/client/FileTree.module.css @@ -7,7 +7,7 @@ /* Every nested level indents by one step; the root level sits flush. */ .level .level { - padding-left: 18px; + padding-left: calc(16px + 6px); } .item { diff --git a/packages/client/ui-sidebar-files/src/client/FilesBody.module.css b/packages/client/ui-sidebar-files/src/client/FilesBody.module.css index 315d5afae8..f7d552bd0a 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.module.css +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.module.css @@ -158,7 +158,8 @@ /* The page's 38px row flush under the pane's strip: the root's path, then reload and the directory actions. With the strip's 38px above, its rule lies where the conversation header's does - (ui-conversation ConversationRoot `.header`, 76px with the same rule). */ + (ui-conversation ConversationRoot `.header`, 76px with the same rule). + Without a handoff, the final icon shares the upper collapse control’s column. */ .header { display: flex; flex: 0 0 auto; @@ -170,6 +171,27 @@ border-bottom: 0.5px solid var(--dsw-alias-border-l3); } +/* A real handoff aligns its frame to the upper glyph. */ +.header:has(.externalActions > :global([data-slot]) > *) { + padding-right: 13.5px; +} + +.externalActions { + display: flex; + flex: none; + align-items: center; +} + +/* Only a split control needs the extra separation to align Search with Split. */ +.externalActions:has(button[aria-haspopup='menu']) { + margin-left: 4.5px; +} + +/* The renderer retains a display:contents slot anchor when every contribution returns null. */ +.externalActions:not(:has(:global([data-slot]) > *)) { + display: none; +} + /* The margin plus the header's gap keeps the path 16px clear of reload. */ .path { margin-right: 12px; @@ -255,6 +277,12 @@ height: 15px; } +/* The landscape folder needs the full 16px slot to match the adjacent glyphs visually. */ +.tool[data-files-navigator-toggle] svg { + width: 16px; + height: 16px; +} + @media (hover: hover) { .tool:hover { color: var(--dsw-alias-label-primary); diff --git a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx index 0f6b26d7f6..7b9269a927 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx @@ -111,7 +111,9 @@ export function FilesBody(props: FilesBodyProps): ReactNode { - {renderSlot('sidebar.right.tab.files.actions', { absolutePath: cwd })} +
      + {renderSlot('sidebar.right.tab.files.actions', { absolutePath: cwd })} +
      {navigator}
      diff --git a/packages/client/ui-sidebar-right/README.i18n.yaml b/packages/client/ui-sidebar-right/README.i18n.yaml index ae8159f93c..0fbcd1aa5d 100644 --- a/packages/client/ui-sidebar-right/README.i18n.yaml +++ b/packages/client/ui-sidebar-right/README.i18n.yaml @@ -36,8 +36,8 @@ en: b6c64c7649203e12 zh: c9341bbfd548a5eb /deepseek-ai-dsh-client-ui-sidebar-right/the-guide: - en: 68fd575ef382223e - zh: 1ab1653ee20c64e9 + en: 2cc38fa6666dbc17 + zh: 1063018c8fe95012 /deepseek-ai-dsh-client-ui-sidebar-right/copy: en: 67386560b71672a4 zh: 35cf8cb7ddf618ce diff --git a/packages/client/ui-sidebar-right/README.md b/packages/client/ui-sidebar-right/README.md index b336f6f165..7fac795ae6 100644 --- a/packages/client/ui-sidebar-right/README.md +++ b/packages/client/ui-sidebar-right/README.md @@ -126,7 +126,7 @@ A tab type can declare `multiple: true` for independent instances such as termin Default pages depend on the number of registered guide entries, not tab types or open tabs. Exactly one entry opens its page directly; zero or multiple entries open the guide. Explicitly adding a guide always opens the guide. Closing follows the [sole-docked-tab rule](#state). -The guide tab is a muted compass over one entry capsule per `guide` entry the registered types contributed, in `order`, centred in the body; the guide has no words of its own. A capsule shows the entry's glyph — or the guide's quieter cube placeholder when the entry registered none — and its title; while at most four entries are listed, an entry that registered a `description` shows it under the title, and a longer list drops every description. Picking a default capsule or a **More tools** row calls `tab.actions.openTab(entry.kind, { replaceTab: true })` and then `tab.actions.close()`, so the guide gives way to the page it opened and closes itself when that page was revealed; the open-page shortcut from a focused guide does the same. A pane holds at most one guide tab. The strip's add control is drawn only while its pane holds none and opens one there with `openTab('guide', { paneId, revealIfOpened: false })`, so a guide in another pane does not capture the click; opening the guide into a pane that already has one focuses it instead; a guide dragged, dropped, or docked into such a pane merges into it — the arriving guide closes and the pane's own is focused; `duplicateTab` on the guide records nothing. A split, an expanded empty root pane, and the pane a sole tab vacates by dropping on its own edge use the same default-page rule, one tab per new pane; the self-edge drop leaves the dragged tab focused. A plain `openTab('guide')` opens or focuses the guide only within the active or named pane. Splitting an empty pane does nothing and returns no new pane. The product allows two horizontal panes, initially equal, with divider ratios limited to 20%–80%. Insufficient width blocks a new split; with two panes already present, a body drop moves the tab between panes instead of creating a third. At the two-pane limit, split controls are disabled with a focusable reason; closing back to one pane enables them. +The guide tab is a muted compass over one entry capsule per `guide` entry the registered types contributed, in `order`, centred in the body; a guide taller than its pane starts at the top and scrolls. The guide has no words of its own. A capsule shows the entry's glyph — or the guide's quieter cube placeholder when the entry registered none — and its title; while at most four entries are listed, an entry that registered a `description` shows it under the title, and a longer list drops every description. Picking a default capsule or a **More tools** row calls `tab.actions.openTab(entry.kind, { replaceTab: true })` and then `tab.actions.close()`, so the guide gives way to the page it opened and closes itself when that page was revealed; the open-page shortcut from a focused guide does the same. A pane holds at most one guide tab. The strip's add control is drawn only while its pane holds none and opens one there with `openTab('guide', { paneId, revealIfOpened: false })`, so a guide in another pane does not capture the click; opening the guide into a pane that already has one focuses it instead; a guide dragged, dropped, or docked into such a pane merges into it — the arriving guide closes and the pane's own is focused; `duplicateTab` on the guide records nothing. A split, an expanded empty root pane, and the pane a sole tab vacates by dropping on its own edge use the same default-page rule, one tab per new pane; the self-edge drop leaves the dragged tab focused. A plain `openTab('guide')` opens or focuses the guide only within the active or named pane. Splitting an empty pane does nothing and returns no new pane. The product allows two horizontal panes, initially equal, with divider ratios limited to 20%–80%. Insufficient width blocks a new split; with two panes already present, a body drop moves the tab between panes instead of creating a third. At the two-pane limit, split controls are disabled with a focusable reason; closing back to one pane enables them. ## Copy diff --git a/packages/client/ui-sidebar-right/README.zh.md b/packages/client/ui-sidebar-right/README.zh.md index 039062a104..54aef8cc2f 100644 --- a/packages/client/ui-sidebar-right/README.zh.md +++ b/packages/client/ui-sidebar-right/README.zh.md @@ -126,7 +126,7 @@ root 作用域的 `sidebar.right.tab.guide.actions` list 有注册项时,引 默认页取决于已注册的引导入口数,不取决于 tab 类型数或已打开的 tab 数。恰好一个入口时直接打开对应页面;没有入口或有多个入口时打开引导页。显式添加引导页始终打开引导页。关闭遵循[唯一停靠 tab 规则](#state)。 -引导 tab 是一枚弱化的罗盘,下方是各已注册类型贡献的每个 `guide` 条目一个入口胶囊,按 `order` 排列并在正文中居中;引导页自己没有文字。胶囊显示条目的图标——条目没注册图标时用引导页自己更浅的立方体占位符——和标题;列出的条目不超过四个时,注册了 `description` 的条目在标题下显示它,更长的列表则去掉所有描述。点击默认胶囊或**更多工具**菜单行会调用 `tab.actions.openTab(entry.kind, { replaceTab: true })`,再调用 `tab.actions.close()`,于是引导页让位给它打开的页,该页被揭示时引导页关闭自己;在聚焦的引导页上用快捷键打开页时也是如此。一个格最多持有一个引导 tab。tab 条的添加控件只在该格没有引导 tab 时绘制,并以 `openTab('guide', { paneId, revealIfOpened: false })` 在该格打开一个,这样别的格里的引导页不会截走这次点击;把引导页开进已有引导页的格则改为聚焦它;把引导页拖入、放入或收回到这样的格会合并进去——来者关闭,该格自己的被聚焦;对引导页 `duplicateTab` 不记录任何东西。分栏、展开且为空的根格、以及唯一 tab 拖到本格边缘分屏后腾出的格使用相同的默认页规则,每个新格一个 tab;这种本格边缘拖放让被拖的 tab 保持聚焦。普通的 `openTab('guide')` 只在活跃或指定分栏内打开或聚焦引导页。对空分栏执行 split 不产生变化,也不返回新分栏。产品最多保留左右两格,默认均分,分隔条限定在 20%~80%。宽度不足以容纳两格时不允许新分栏;已有两格时,正文拖放用于跨格移动,不再创建第三格。达到两格上限时禁用分栏控件并提供可聚焦的原因提示;关闭回单格后重新启用。 +引导 tab 是一枚弱化的罗盘,下方是各已注册类型贡献的每个 `guide` 条目一个入口胶囊,按 `order` 排列并在正文中居中;引导页高于所在格时从顶部开始排列并可滚动。引导页自己没有文字。胶囊显示条目的图标——条目没注册图标时用引导页自己更浅的立方体占位符——和标题;列出的条目不超过四个时,注册了 `description` 的条目在标题下显示它,更长的列表则去掉所有描述。点击默认胶囊或**更多工具**菜单行会调用 `tab.actions.openTab(entry.kind, { replaceTab: true })`,再调用 `tab.actions.close()`,于是引导页让位给它打开的页,该页被揭示时引导页关闭自己;在聚焦的引导页上用快捷键打开页时也是如此。一个格最多持有一个引导 tab。tab 条的添加控件只在该格没有引导 tab 时绘制,并以 `openTab('guide', { paneId, revealIfOpened: false })` 在该格打开一个,这样别的格里的引导页不会截走这次点击;把引导页开进已有引导页的格则改为聚焦它;把引导页拖入、放入或收回到这样的格会合并进去——来者关闭,该格自己的被聚焦;对引导页 `duplicateTab` 不记录任何东西。分栏、展开且为空的根格、以及唯一 tab 拖到本格边缘分屏后腾出的格使用相同的默认页规则,每个新格一个 tab;这种本格边缘拖放让被拖的 tab 保持聚焦。普通的 `openTab('guide')` 只在活跃或指定分栏内打开或聚焦引导页。对空分栏执行 split 不产生变化,也不返回新分栏。产品最多保留左右两格,默认均分,分隔条限定在 20%~80%。宽度不足以容纳两格时不允许新分栏;已有两格时,正文拖放用于跨格移动,不再创建第三格。达到两格上限时禁用分栏控件并提供可聚焦的原因提示;关闭回单格后重新启用。 ## 文案 diff --git a/packages/client/ui-sidebar-right/src/client/tab-inventory.ts b/packages/client/ui-sidebar-right/src/client/tab-inventory.ts index 1dfc139518..1fc33eeb1b 100644 --- a/packages/client/ui-sidebar-right/src/client/tab-inventory.ts +++ b/packages/client/ui-sidebar-right/src/client/tab-inventory.ts @@ -21,19 +21,21 @@ export class SidebarTabInventory { /** Read saved layouts once before the root service is published. */ constructor() { + let keys: readonly (string | null)[] = [] try { - if (typeof localStorage === 'undefined') return - const keys = Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) - for (const key of keys) { - if (key === null || !key.startsWith(`${sidebarPersistence}.`)) continue - const sessionId = key.slice(sidebarPersistence.length + 1) as SessionId - const saved = readSidebarLayout(sessionId) - if (saved !== undefined) this.sessions.set(sessionId, Object.values(saved.layout.tabs).map(tab => ({ - sessionId, tabId: tab.id, kind: tab.kind, contentId: tab.contentId, - }))) - } - this.publish() - } catch (_storageUnavailable) { /* Adopted in-memory layouts still publish their open tabs. */ } + keys = typeof localStorage === 'undefined' ? [] : Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) + } catch (_storageUnavailable) { + // Inaccessible storage holds no saved layouts; adopted in-memory layouts still publish their open tabs. + } + for (const key of keys) { + if (key === null || !key.startsWith(`${sidebarPersistence}.`)) continue + const sessionId = key.slice(sidebarPersistence.length + 1) as SessionId + const saved = readSidebarLayout(sessionId) + if (saved !== undefined) this.sessions.set(sessionId, Object.values(saved.layout.tabs).map(tab => ({ + sessionId, tabId: tab.id, kind: tab.kind, contentId: tab.contentId, + }))) + } + this.publish() } /** diff --git a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css index b78983aa2d..f3d2133213 100644 --- a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css +++ b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css @@ -2,23 +2,26 @@ stylesheet does not carry them. Tokens only. */ /* The capsules form one centred column at the column's own 14px gap, lifted - above the body's middle by the spacer below. The minimum height centres a - short guide while allowing a tall guide to grow into the pane's scroller. */ + above the body's middle by the spacer below. The guide fills the tab body, + which clips, and scrolls itself; `safe` centring starts a guide taller than + the pane at its top so every capsule stays reachable. The block padding + keeps a scrolled-to-end capsule's focus ring off the pane's edge. */ .guide { --dsl-guide-entry-radius: var(--dsw-radius-xl); display: flex; + flex: 1 1 auto; flex-direction: column; gap: 14px; align-items: center; - justify-content: center; + justify-content: safe center; box-sizing: border-box; - min-height: 100%; - padding: 0 24px; + padding: 14px 24px; + overflow-y: auto; } /* The lift, as a share of the pane's height (a column flex basis resolves against it): the centred column rises 5% of the pane, and a short pane - gives it up before the capsules clip. */ + gives it up before the column overflows. */ .guide::after { content: ''; flex: 0 1 10%; diff --git a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx index 4cff92b514..6c73fa8869 100644 --- a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx +++ b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx @@ -9,8 +9,9 @@ * cannot be outvoted by accident. * * The shipped guide is a muted compass over the pinned entry capsules every - * registered type contributed, centred in the body, with no heading, as a - * browser start page shows its doors without a caption. While at most four + * registered type contributed, centred in the body (scrolling from the top when + * taller than the pane), with no heading, as a browser start page shows its + * doors without a caption. While at most four * capsules are visible, a capsule with a description shows it under the title; * a longer list drops every description to stay light. A More card follows * while `sidebar.right.tab.guide.actions` has registrations. diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index 3d1f634711..1380ed4bab 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Sidebar presentation and tab subscriptions through the production slot renderer. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -81,7 +82,7 @@ async function mountSeat(viewportWidth = 1440, canShow = true, entryCount = 0, o const catalog = createSnapshotStore([]) runtime.ctx.provide('shortcuts', { register: () => () => {}, catalog } as never) runtime.slots.installLocale(locale) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.declare({ 'sidebar-right.test.opener': { kind: 'single', scope: 'session' }, 'rightbar': { kind: 'single', scope: 'root' }, diff --git a/packages/client/ui-sidebar-terminal/README.i18n.yaml b/packages/client/ui-sidebar-terminal/README.i18n.yaml index 60a2d06ff0..bb25f5d57f 100644 --- a/packages/client/ui-sidebar-terminal/README.i18n.yaml +++ b/packages/client/ui-sidebar-terminal/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 1fa9a72d1ee045cc /deepseek-ai-dsh-client-ui-sidebar-terminal/use-this-package: - en: c8b04f4eb202d344 - zh: d0cd8d7d998baa02 + en: 1dfcc29a0848ee45 + zh: a6d6875c156f0d78 /deepseek-ai-dsh-client-ui-sidebar-terminal/understand-the-implementation: en: 005b5496578870d3 zh: 9883a41eef2a18a5 diff --git a/packages/client/ui-sidebar-terminal/README.md b/packages/client/ui-sidebar-terminal/README.md index d41d13e07e..b40e41e62e 100644 --- a/packages/client/ui-sidebar-terminal/README.md +++ b/packages/client/ui-sidebar-terminal/README.md @@ -25,6 +25,8 @@ Choose an installed shell from the right sidebar's Start page to run commands in ## Use this package +Terminal tab titles reuse the shared 16px Regular terminal prompt glyph. + The `terminal.new` command creates a separate terminal in the focused dock pane, replacing a guide and retaining existing content pages. From the conversation or a floating content page, it uses the active dock pane. The guide card right-aligns the current effective shortcut as unboxed text without a duplicate tooltip. Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves the command unbound by default. Open the right sidebar and click **New terminal** to open the remembered available shell immediately. The separate arrow beside the title opens the installed-shell menu; selecting an item remembers it and opens that shell directly. Discovery runs when the menu opens and does not allocate a terminal. A failed lookup offers Retry in the menu. Use **New tab** to return to the guide and open another terminal. diff --git a/packages/client/ui-sidebar-terminal/README.zh.md b/packages/client/ui-sidebar-terminal/README.zh.md index 43be2ef82a..7cfd5818cf 100644 --- a/packages/client/ui-sidebar-terminal/README.zh.md +++ b/packages/client/ui-sidebar-terminal/README.zh.md @@ -25,6 +25,8 @@ kind: "package-reference" ## 使用此包 +终端页签标题复用共享的 16px Regular 终端提示符图标。 + 命令 `terminal.new` 在焦点停靠分栏创建独立终端,替换开始页并保留已有内容页。从聊天区或浮动内容页触发时,使用活动停靠分栏。开始页卡片右侧对齐显示当前有效快捷键的无背景文字,不额外弹出重复提示。Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 默认不绑定此命令。 展开右侧栏,点击**新建终端**即可直接打开上次选择且仍可用的 shell。标题旁的独立箭头展开已安装 shell 菜单;选择后立即记住该项并打开终端。菜单展开时才查询 shell,不分配终端进程;查询失败可在菜单内重试。通过**新标签页**回到开始页并打开更多终端。 diff --git a/packages/client/ui-sidebar-terminal/src/client/TerminalIcon.tsx b/packages/client/ui-sidebar-terminal/src/client/TerminalIcon.tsx deleted file mode 100644 index a875c26837..0000000000 --- a/packages/client/ui-sidebar-terminal/src/client/TerminalIcon.tsx +++ /dev/null @@ -1,13 +0,0 @@ -/** Terminal glyph for sidebar tab titles. */ -import type { ReactNode } from 'react' - -/** - * Render the tab title's terminal prompt in the surrounding text color. - * @returns a decorative sixteen-pixel line glyph. - */ -export function TerminalIcon(): ReactNode { - return -} diff --git a/packages/client/ui-sidebar-terminal/src/client/TerminalTitle.tsx b/packages/client/ui-sidebar-terminal/src/client/TerminalTitle.tsx index 30b9fb0a03..ec94da279b 100644 --- a/packages/client/ui-sidebar-terminal/src/client/TerminalTitle.tsx +++ b/packages/client/ui-sidebar-terminal/src/client/TerminalTitle.tsx @@ -1,8 +1,7 @@ /** Live terminal names in docked and floating tab chrome. */ import { useLayoutEffect, useRef, useState, type ReactNode } from 'react' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import { Tag } from '@deepseek-ai/dsh-client-ui-primitives' -import { TerminalIcon } from './TerminalIcon.tsx' +import { IconApiOutlineRegular, Tag } from '@deepseek-ai/dsh-client-ui-primitives' import type { TerminalInjected } from './face.ts' import type {} from './locales.ts' import css from './TerminalTitle.module.css' @@ -40,7 +39,7 @@ export function TerminalTitle({ useTabInfo, useTerminal, view, t }: PropsRuntime input.current?.select() }, [editing]) return <> - + {/* The badge precedes the name because the tab's close button covers the end of the title. One badge at a time: Agent control first, then the sandbox of a taken-over terminal. */} {agentControl diff --git a/packages/client/ui-sidebar/README.i18n.yaml b/packages/client/ui-sidebar/README.i18n.yaml index efee3bf75b..0713c88064 100644 --- a/packages/client/ui-sidebar/README.i18n.yaml +++ b/packages/client/ui-sidebar/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6bc49e22f0f73f07 zh: 10883997ccb7d145 /deepseek-ai-dsh-client-ui-sidebar/use-this-package/global-panel-entries: - en: 8bc0f930af6ce312 - zh: 97112bb5262cedf3 + en: e7cfc9a3d175045d + zh: 2bf0d5d6d0c64de8 /deepseek-ai-dsh-client-ui-sidebar/use-this-package/collapse-behavior: en: 61d563b0f82ff658 zh: f27504350dd14d4c @@ -30,14 +30,14 @@ en: 28e3639ed58492e0 zh: 4896acd767287c8a /deepseek-ai-dsh-client-ui-sidebar/use-this-package/scrollbars: - en: 9e7b31acee759f2b - zh: 3a6beb63b23d26ae + en: dd59917acefeab78 + zh: 28d70c963795c0a0 /deepseek-ai-dsh-client-ui-sidebar/use-this-package/click-analytics: en: 3e84ffdf6c7c1731 zh: 3f7b19cac6d6674f /deepseek-ai-dsh-client-ui-sidebar/understand-the-implementation: - en: c13373b1c2fabd64 - zh: e01fbc5d5d760b2c + en: 4d08c745534fc8f4 + zh: 164418412f91c02a /deepseek-ai-dsh-client-ui-sidebar/understand-the-implementation/slot-discipline: en: 6eefc5c45abe8a8f zh: 20b651e48a0ea903 diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index 1608bbfb4c..0328dd05fa 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -39,7 +39,7 @@ The expanded brand row renders `sidebar.brand.mark` and `sidebar.brand.name` as ### Global panel entries -Plugins add an icon component to the root-scoped `sidebar.panellist` list with an `id`, optional `order`, and a string or locale-aware `label`. The same id addresses the component registered in the layout's root-scoped `main` keyed slot; selecting a missing main entry throws without changing the current selection. The label supplies plain visible text, the accessible name, and the collapsed tooltip. Expanded navigation rows are 32px high with a 2px gap; collapsed rail controls remain 36px high with a 12px gap. Each row reads its own selected state through `usePanelInfo`; moving DOM focus to search or a directory picker does not change the displayed panel or its selected row. With no panel registrations, neither the list nor spacing for it is rendered. The shipped composition registers no example panel. +Plugins add an icon component to the root-scoped `sidebar.panellist` list with an `id`, optional `order`, and a string or locale-aware `label`. The same id addresses the component registered in the layout's root-scoped `main` keyed slot; selecting a missing main entry throws without changing the current selection. The label supplies plain visible text, the accessible name, and the collapsed tooltip. Expanded navigation rows are 32px high with a 2px gap; collapsed rail controls remain 36px high with a 12px gap. Expanded navigation keeps an 8px bottom margin before the Workspace header. Each row reads its own selected state through `usePanelInfo`; moving DOM focus to search or a directory picker does not change the displayed panel or its selected row. With no panel registrations, neither the list nor spacing for it is rendered. The shipped composition registers no example panel. A panel may also register non-interactive inline content in the root-scoped `sidebar.panellist.trailing` list with the same `id`, such as a count. It receives `wide` and `active`. The expanded row lays it out after the title and before the space the unpin action takes, as a Session row lays out its trailing icons, so a row without content keeps its full title width and the unpin action shows beside the content. The collapsed rail shows it over the icon's top trailing corner. It renders inside the row button, so it holds no interactive elements; its text becomes the button's accessible description, so decorative parts must be `aria-hidden`. @@ -63,7 +63,7 @@ Under `html[data-platform='darwin']` (set only by the desktop preload) the expan ### Scrollbars -Scrollbars in the column are a pointer affordance: the shell rebinds the scrollbar indirection to `transparent` whenever the pointer is outside the column and keeps the thumb drawn for 2s after the pointer leaves, so a list nobody is pointing at carries no bar. The reservation that keeps rows from moving belongs to the scrolling region (ui-workspace), so revealing a thumb never reflows. +Scrollbars in the column are a pointer affordance: the shell rebinds the scrollbar indirection to `transparent` whenever the pointer is outside the column, so a list nobody is pointing at carries no bar. After the pointer leaves, the thumb stays drawn for 500ms and then fades out linearly over 200ms; a pointer that returns before the fade ends redraws it at once, and reduced motion keeps the delay without the fade. Outside is decided by the column's box for every pointer move that reaches the column, so a pointer over the fixed-position Settings panel or a portalled menu outside the box also counts as outside. The reservation that keeps rows from moving belongs to the scrolling region (ui-workspace), so revealing a thumb never reflows. ### Click analytics @@ -84,12 +84,14 @@ On Desktop, the official navigation controls report `sidebar_menu_click` with `m The shell is pure composition: `SidebarRootComponentProps` composes the layout owner share, the global `useSessions` and `useWorkspaces` hooks, the declared brand, the `sidebar.workspaces` and `sidebar.settings` child slots, and injected navigation callbacks. The sidebar declares the `sidebar.panel.icon` Component Factory, which owns the `sidebar.panellist` list, and the `sidebar.panel.trailing` Component Factory, which owns the `sidebar.panellist.trailing` list; panel rows and the More menu render a panel's registered icon through the first, and panel rows its trailing content through the second. Panel metadata is derived from list registrations and locale changes; selection belongs to the layout store. The injected `trackEntryClick(attributes)` forwards to `ctx.get('productAnalytics')?.track('sidebar_menu_click', attributes)`, and `selectPanel` only selects, so each control supplies its own entry and position. -Expanded navigation uses 8px outer gutters, hover and selected fills inset 3px on each side, and a 16px leading cell with a 6px label gap. New Session centers its content with 4px side margins. Its initial 12px gap above navigation combines 4px outside the scrollport and an 8px gap that scrolls away. The logo row has no bottom margin; its content starts 16px from the column's left edge, with 5px between mark and name. Only the macOS non-fullscreen top toggle shifts 4px right while expanded, retaining that offset throughout its fade-out. Collapsed geometry stays independent. +Expanded navigation uses 8px outer gutters, hover and selected fills inset 3px on each side, and a 16px leading cell with a 6px label gap. New Session centers its content; its row keeps 4px side margins and a 6px bottom margin. Navigation adds a further 4px outside the scrollport and an 8px gap inside it that scrolls away. The logo row has no bottom margin; its content starts 16px from the column's left edge, with 5px between mark and name. Only the macOS non-fullscreen top toggle shifts 4px right while expanded, retaining that offset throughout its fade-out. Collapsed geometry stays independent. Expanded panel navigation and the `sidebar.workspaces` section share one vertical-only viewport below the fixed brand and New Session controls; footer actions and Settings stay outside it. Horizontal overflow is clipped so toolbar edge offsets do not create a horizontal scrollbar. The viewport hides its own scrollbar and only scrolls the navigation away: the section is at most one viewport tall and scrolls its rows in its own scroller, which draws the only visible scrollbar; a section that fits leaves the viewport nothing to scroll. While expanded, the viewport carries `data-sidebar-scrollport`, a stable marker for tests and integrations. The shell owns the bottom fade. Scrolling down moves the navigation away before the section scroller moves; scrolling up returns the section scroller to its top before the navigation reappears. A wheel or trackpad gesture whose first event must move the viewport, or starts outside the section scroller, is split between the two in JavaScript until it ends, including its momentum, so one gesture crosses the boundary; wheel events less than 100ms apart count as one gesture. A gesture the section scroller can take alone keeps native scrolling; when an uncancelable native gesture reaches the section scroller's top, the viewport takes the rest. Events another listener already canceled, pinch-zoom (Ctrl), and mostly horizontal wheel events keep native scrolling. Content inside the viewport must not own vertical scrolling unless it cancels its own wheel events. The section receives this capability through `sidebar.workspaces`: each render supplies `hookContext.useSectionScroller`, and the occupant's `useSectionScroller()` returns the same `{ bindScrollerRef }` object for one sidebar. An occupant that binds no scroller keeps native scrolling. The region around the viewport is a size container with the viewport's height, and the viewport is a scroll-state container, so a section scroller can refuse native scrolling until the viewport reaches its end. +Wheel scrolling is unreliable during a native drag, and WebKit and Firefox do not autoscroll the section scroller, so the sidebar scrolls itself during a drag; in Chromium this adds to its native drag autoscroll. While a drag's pointer is within 48px of the top or bottom edge of the section scroller's visible part, or of the viewport without a bound scroller, the two scroll in the same order as wheel scrolling, at up to 1000px per second; the speed rises linearly toward the edge and stays at the maximum past it. Scrolling stops at `drop`, `dragend`, a `dragleave` out of the viewport, or 600ms without `dragover`. + The sidebar root supplies inherited CSS properties to `sidebar.workspaces` and `sidebar.settings`: `--dsh-sidebar-inline-padding: 8px`, `--dsh-sidebar-row-padding: 12px`, `--dsh-sidebar-label-gap: 6px`, and `--dsh-sidebar-paint-inset: 3px`. Occupants consume these values for expanded row alignment; standalone compositions must provide them on an ancestor. The paint inset reduces the fill without moving content: rows subtract it from their inline padding and use it as a transparent border. The expanded viewport hides its own scrollbar; its trailing grid column keeps navigation and the section 8px from the sidebar edge, and the section's scroller places its scrollbar 2px from that edge. ### Slot discipline diff --git a/packages/client/ui-sidebar/README.zh.md b/packages/client/ui-sidebar/README.zh.md index 0a1c796be0..e68792963e 100644 --- a/packages/client/ui-sidebar/README.zh.md +++ b/packages/client/ui-sidebar/README.zh.md @@ -39,7 +39,7 @@ dsh Web 客户端的侧边栏让用户识别当前构建、启动新会话、将 ### 全局面板入口 -插件在 root 作用域的 `sidebar.panellist` list 中注册图标组件,提供 `id`、可选 `order`,以及字符串或 locale-aware 的 `label`。同一个 id 寻址布局中 root 作用域 `main` keyed slot 的组件;选择不存在的主面板条目会抛错,并保留当前选中态。标签提供普通可见文字、无障碍名称和折叠提示。展开态导航行高 32px,间距为 2px;折叠窄栏控件保持 36px 高和 12px 间距。每一行通过 `usePanelInfo` 读取自己的选中态;DOM 焦点移到搜索框或目录选择器时,显示的面板及其列表项选中态不变。没有面板注册项时,列表及其间距均不渲染。产品随附的组合不注册示例面板。 +插件在 root 作用域的 `sidebar.panellist` list 中注册图标组件,提供 `id`、可选 `order`,以及字符串或 locale-aware 的 `label`。同一个 id 寻址布局中 root 作用域 `main` keyed slot 的组件;选择不存在的主面板条目会抛错,并保留当前选中态。标签提供普通可见文字、无障碍名称和折叠提示。展开态导航行高 32px,间距为 2px;折叠窄栏控件保持 36px 高和 12px 间距。展开态导航区域与工作区标题行之间保留 8px 底部外边距。每一行通过 `usePanelInfo` 读取自己的选中态;DOM 焦点移到搜索框或目录选择器时,显示的面板及其列表项选中态不变。没有面板注册项时,列表及其间距均不渲染。产品随附的组合不注册示例面板。 面板还可以用相同 `id` 在 root 作用域的 `sidebar.panellist.trailing` list 中注册不可交互的行内内容,例如数量。它接收 `wide` 与 `active`。展开的行把它排在标题之后、取消固定操作所占空间之前,与会话行排布行尾图标的方式相同:没有内容的行保留完整的标题宽度,取消固定操作显示在内容旁边。收起的窄栏在图标右上角显示它。它渲染在行按钮内,因此不能包含可交互元素;它的文字成为按钮的无障碍描述,因此装饰性的部分必须设为 `aria-hidden`。 @@ -63,7 +63,7 @@ root 作用域的 `sidebar.session.action` 是包裹新建会话行内容的 HOC ### 滚动条 -栏内的滚动条是一种指针可供性:只要指针不在栏内,外壳就把滚动条间接层重新绑定为 `transparent`;指针离开后滑块再保留 2 秒,因此没人指向的列表不会带着滚动条。避免行位移的空间预留属于滚动区域本身(ui-workspace),所以显示滑块不会引起重排。 +栏内的滚动条是一种指针可供性:只要指针不在栏内,外壳就把滚动条间接层重新绑定为 `transparent`,因此没人指向的列表不会带着滚动条。指针离开后,滑块先保留 500ms,再在 200ms 内线性淡出;淡出结束前指针返回会立即重新显示滑块,减弱动态效果时保留延迟但不淡出。是否在栏内按栏的矩形范围判定,对每次到达该栏的指针移动都会判定,因此指针位于固定定位的设置面板或栏外的 portal 菜单上时,同样算作在栏外。避免行位移的空间预留属于滚动区域本身(ui-workspace),所以显示滑块不会引起重排。 ### 点击埋点 @@ -84,12 +84,14 @@ root 作用域的 `sidebar.session.action` 是包裹新建会话行内容的 HOC 外壳是纯组合:`SidebarRootComponentProps` 组合布局 owner share、全局 `useSessions` 与 `useWorkspaces` 钩子、已声明的品牌、`sidebar.workspaces` 与 `sidebar.settings` 子 slot,以及注入的导航回调。侧边栏声明 `sidebar.panel.icon` Component Factory,由它拥有 `sidebar.panellist` list,并声明 `sidebar.panel.trailing` Component Factory,由它拥有 `sidebar.panellist.trailing` list;面板行和更多菜单通过前者渲染面板注册的图标,面板行通过后者渲染行尾内容。面板元数据由列表注册和 locale 变化派生;选中态属于布局存储。注入的 `trackEntryClick(attributes)` 转发到 `ctx.get('productAnalytics')?.track('sidebar_menu_click', attributes)`;`selectPanel` 只负责选中,因此由各控件自行提供入口与位置。 -展开态导航的左右外距为 8px,悬停与选中底色在两侧各内缩 3px,前置单元宽 16px,与标签间隔 6px。新会话内容居中,左右外边距为 4px。它与导航的初始 12px 间距由滚动区外的 4px 和随内容滚走的 8px 组成。logo 行无底部外边距;内容从侧栏左边缘向内 16px 开始,标记与名称间隔 5px。仅 macOS 非全屏、侧栏展开时,顶部开关向右偏移 4px,并在整个淡出期间保持该偏移。折叠态尺寸独立保留。 +展开态导航的左右外距为 8px,悬停与选中底色在两侧各内缩 3px,前置单元宽 16px,与标签间隔 6px。新会话内容居中,所在行保留 4px 左右外边距及 6px 底部外边距。导航额外保留滚动区外的 4px 与滚动区内、随内容滚走的 8px 间距。logo 行无底部外边距;内容从侧栏左边缘向内 16px 开始,标记与名称间隔 5px。仅 macOS 非全屏、侧栏展开时,顶部开关向右偏移 4px,并在整个淡出期间保持该偏移。折叠态尺寸独立保留。 展开态的面板导航与 `sidebar.workspaces` 区块共用一个仅纵向滚动的视口,位于固定的品牌和新会话控件下方;底部操作与设置位于视口之外。横向溢出被裁切,工具栏边缘偏移不会产生横向滚动条。视口隐藏自身滚动条,只负责把导航滚走:区块最高为一个视口,在自己的滚动容器中滚动列表行,并由该容器绘制唯一可见的滚动条;区块放得下时,视口没有可滚动的距离。展开时视口带有 `data-sidebar-scrollport`,这是供测试和集成方定位的稳定标记。外壳负责底部渐隐。 向下滚动时先把导航滚走,再滚动区块;向上滚动时先让区块回到顶部,导航再重新出现。如果一次滚轮或触控板手势的第一个事件需要移动视口,或者手势从区块滚动容器之外开始,JavaScript 会在整次手势(包括惯性)结束前一直把滚动量分配给两者,因此一次手势可以越过边界;间隔不足 100ms 的滚轮事件视为同一次手势。区块滚动容器能独自处理的手势保持浏览器原生滚动;不可取消的原生手势到达区块滚动容器顶部时,剩余距离交给视口。已被其他监听器取消的事件、双指缩放(Ctrl)事件以及以横向为主的滚轮事件保持浏览器原生滚动。视口内的内容不得自带纵向滚动,除非它自己取消这些滚轮事件。区块通过 `sidebar.workspaces` 获得这项能力:每次渲染都会提供 `hookContext.useSectionScroller`,同一个侧边栏中,占用者调用 `useSectionScroller()` 始终得到同一个 `{ bindScrollerRef }` 对象。未绑定滚动容器的占用者保持原生滚动。视口外层的区域是高度与视口相同的尺寸容器,视口本身是滚动状态容器,因此区块的滚动容器可以在视口滚到底之前拒绝原生滚动。 +原生拖拽期间滚轮滚动并不可靠,WebKit 和 Firefox 也不会自动滚动区块滚动容器,因此侧栏在拖拽期间自行滚动;在 Chromium 中,它与原生拖拽自动滚动叠加。当拖拽指针位于区块滚动容器可见部分(若未绑定滚动容器,则为视口)顶部或底部边缘 48px 以内时,二者按与滚轮滚动相同的顺序滚动,速度最高为每秒 1000px;越靠近边缘速度越快(线性增加),越过边缘后保持最大值。遇到 `drop`、`dragend`、移出视口的 `dragleave`,或 600ms 内没有 `dragover` 时,滚动停止。 + 侧边栏根节点向 `sidebar.workspaces` 与 `sidebar.settings` 提供可继承的 CSS 属性:`--dsh-sidebar-inline-padding: 8px`、`--dsh-sidebar-row-padding: 12px`、`--dsh-sidebar-label-gap: 6px` 和 `--dsh-sidebar-paint-inset: 3px`。占用者使用这些值对齐展开态行;独立组合必须在祖先节点提供这些值。底色内缩不移动内容:行从左右内边距中减去该内缩值,并以等宽透明边框承载内缩。展开态视口隐藏自身滚动条;其尾部网格列使导航和区块与侧栏边缘保持 8px,区块的滚动容器把滚动条放在距该边缘 2px 处。 ### slot 纪律 diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css index f6713f0512..023dd4a0c6 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css @@ -124,16 +124,25 @@ } /* Scrollbars in the column are a pointer affordance: the shell adds this - class whenever the pointer is not inside (SidebarRoot.tsx owns the linger), + class whenever the pointer is not inside (SidebarRoot.tsx tracks it), and rebinding ui-theme's indirection pair to `transparent` takes the thumb out of every scroll region nested under it — the workspace browser's session list. `transparent` rather than `display: none` on the bar: the reservation (`scrollbar-gutter: stable` on the list) stays in force, so revealing the thumb never reflows a row. Rebinding contract and the two - rendering paths it reaches: ui-theme's README. */ + rendering paths it reaches: ui-theme's README. + The thumb stays drawn for 500ms after the pointer leaves, then fades out + linearly over 200ms; an eased or shorter fade of this pale thumb completes + most of its change in a few frames and reads as a cut. Only the quiet state + carries the transition, so a reveal is immediate and a pointer that returns + during the delay sees no change. The collapse rule's `transition: width` + outranks this one, so a leave during collapse or expand hides at once. */ .root.quietBars { --dsh-scrollbar-thumb: transparent; --dsh-scrollbar-thumb-hover: transparent; + transition: + --dsh-scrollbar-thumb 200ms linear 500ms, + --dsh-scrollbar-thumb-hover 200ms linear 500ms; } /* Collapse phase 1: the whole frozen-width content fades out in place over @@ -426,7 +435,7 @@ display: flex; align-items: center; gap: 6px; - margin: 0 calc(var(--dsh-sidebar-paint-inset) + 1px); + margin: 0 calc(var(--dsh-sidebar-paint-inset) + 1px) 6px; } /* New Session: 38px bar, 12px radius (figma 133:7634 geometry, squared-off @@ -861,4 +870,9 @@ transition: none; animation: none; } + + /* The delay is not motion: keep it and drop only the fade. */ + .root.quietBars { + transition-duration: 0s; + } } diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx index c487ffc5c7..2be8c62182 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx @@ -19,6 +19,7 @@ * pointing at carries no bar. */ import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' +import type { PointerEvent as ReactPointerEvent } from 'react' import clsx from 'clsx' import { FishLogo, IconAppsAddOutlineRegular, IconNewChatOutlineMedium, IconNewChatOutlineRegular, @@ -37,14 +38,6 @@ import css from './SidebarRoot.module.css' /** Wide-content unmount delay; matches the 150ms wide-content fade-out. */ const COLLAPSE_SETTLE_MS = 150 -/** - * How long the column's scrollbars stay drawn after the pointer leaves it. - * The bar is a pointer affordance here, and hiding it on the leave event - * itself makes it blink out while the pointer is only crossing the column's - * edge — on the way to the conversation, or around a portalled menu. - */ -const SCROLLBAR_LINGER_MS = 2000 - /** Format complete-build metadata for the local brand badge. */ function localBuildVersion(): string | undefined { const version = process.env.DSH_CLIENT_VERSION @@ -213,10 +206,9 @@ export function SidebarRoot({ const animateRail = useRef(!collapsed) if (drawer || !collapsed) animateRail.current = !collapsed - // Scrollbars in the column follow the pointer (.quietBars rebinds them - // away): drawn while it is inside, and for SCROLLBAR_LINGER_MS after it - // leaves. A pointer that returns within that window cancels the pending - // hide rather than restarting from a hidden bar. + // Scrollbars in the column follow the pointer: .quietBars rebinds them away + // whenever the pointer is outside, and its stylesheet owns the delay and + // fade, so a pointer that returns before the fade starts sees no change. const column = useRef(null) const sidebarFocus = useRef(null) useModalLayer(column, drawer && !collapsed, toggleSidebar) @@ -231,42 +223,18 @@ export function SidebarRoot({ if (opener != null && !isBehindModal(opener)) focusWithoutRing(opener, { preventScroll: true }) }, [drawer, collapsed]) const [pointerInside, setPointerInside] = useState(false) - const lingerTimer = useRef(undefined) - const armLinger = (): void => { - if (lingerTimer.current !== undefined) return - lingerTimer.current = window.setTimeout(() => { - lingerTimer.current = undefined - setPointerInside(false) - }, SCROLLBAR_LINGER_MS) - } - const cancelLinger = (): void => { - window.clearTimeout(lingerTimer.current) - lingerTimer.current = undefined - } - // Leaving is decided by the column's BOX, not by DOM containment, and only - // while the bars are drawn. ui-settings renders its full-viewport panel as a - // fixed-position DESCENDANT of this column, so a pointer moved onto that - // panel — or onto the conversation once it closes — fires no `pointerleave` - // here, and the bars would stay drawn over a column nobody is pointing at. - // The element's own leave stays as the one signal geometry cannot give: a + // Inside is decided by the column's BOX, not by DOM containment, for every + // pointer move that reaches the column. ui-settings renders its + // full-viewport panel as a fixed-position DESCENDANT of this column, and the + // column's menus and tooltips are React portals, so a pointer over them + // fires no `pointerleave` here while their moves still bubble to it. The + // element's own leave stays as the one signal geometry cannot give: a // pointer that leaves the window emits no further moves. - useEffect(() => { - if (!pointerInside) return - const onMove = (event: PointerEvent): void => { - const rect = column.current?.getBoundingClientRect() - /* v8 ignore next -- the listener only exists while the column is mounted and revealed. */ - if (rect === undefined) return - const inside = event.clientX >= rect.left && event.clientX < rect.right - && event.clientY >= rect.top && event.clientY < rect.bottom - if (inside) cancelLinger() - else armLinger() - } - document.addEventListener('pointermove', onMove) - return () => { - document.removeEventListener('pointermove', onMove) - cancelLinger() - } - }, [pointerInside]) + const trackPointer = (event: ReactPointerEvent): void => { + const rect = event.currentTarget.getBoundingClientRect() + setPointerInside(event.clientX >= rect.left && event.clientX < rect.right + && event.clientY >= rect.top && event.clientY < rect.bottom) + } const buildVersion = localBuildVersion() // The local-build fallbacks copy the badge text; the brand button below @@ -321,11 +289,9 @@ export function SidebarRoot({ !drawer && collapsed && wide && css.fading, !pointerInside && css.quietBars, )} style={wide ? { width: !drawer && collapsed ? lastWideWidth.current : width } : undefined} - onPointerEnter={() => { - cancelLinger() - setPointerInside(true) - }} - onPointerLeave={() => { armLinger() }} + onPointerEnter={trackPointer} + onPointerMove={trackPointer} + onPointerLeave={() => { setPointerInside(false) }} > {/* macOS hiddenInset titlebar: the strip shares the row with the traffic lights and keeps the toggle at the sidebar's top-right. */} diff --git a/packages/client/ui-sidebar/src/client/scroll-handoff.ts b/packages/client/ui-sidebar/src/client/scroll-handoff.ts index f6cf64f714..47514a6e96 100644 --- a/packages/client/ui-sidebar/src/client/scroll-handoff.ts +++ b/packages/client/ui-sidebar/src/client/scroll-handoff.ts @@ -6,13 +6,17 @@ * JavaScript until it ends, including its momentum; both elements are then written * synchronously in each event, so one gesture continues across the boundary. A gesture the * section scroller can take alone keeps native scrolling. + * + * A drag over the viewport scrolls the same way when the pointer nears the top or bottom edge + * of the visible scrolling area, because wheel scrolling is unreliable during a native drag and + * WebKit and Firefox do not autoscroll a section scroller nested in the viewport. */ import type { RefCallback } from 'react' import type { SectionScroller, UseSectionScroller } from './contract/slots.ts' /** Sidebar-owned state of one hand-off. */ export interface ScrollHandoff { - /** Ref callback for the sidebar's own viewport; binds the wheel listener. */ + /** Ref callback for the sidebar's own viewport; binds the wheel hand-off and the drag edge-scrolling listeners. */ readonly bindViewportRef: RefCallback /** Hook handed to the `sidebar.workspaces` occupant through the slot's hookContext. */ readonly useSectionScroller: UseSectionScroller @@ -24,6 +28,21 @@ export interface ScrollHandoff { */ const GESTURE_GAP_MS = 100 +/** Distance from the visible scrolling area's top or bottom edge within which a drag scrolls. */ +const DRAG_EDGE_PX = 48 + +/** Drag scrolling speed with the pointer on or past an edge; it falls linearly to zero across the edge band. */ +const DRAG_MAX_SPEED_PX_PER_MS = 1 + +/** + * A drag that sends no `dragover` for this long has left without `dragleave`, `drop`, or `dragend`. + * HTML drag processing repeats `dragover` every 350ms ±200ms while the pointer rests over a target. + */ +const DRAG_STALE_MS = 600 + +/** Longest interval one drag frame scrolls for, so a delayed frame does not jump. */ +const DRAG_MAX_STEP_MS = 50 + /** * Vertical wheel distance in pixels. Pinch-zoom and mostly horizontal events return undefined * and keep native scrolling. @@ -42,6 +61,41 @@ function scrollClamped(element: HTMLElement, delta: number): number { return element.scrollTop - before } +/** + * Scroll `delta` across both elements: down moves the viewport before the section scroller, + * up moves the section scroller before the viewport. + */ +function scrollSplit(viewport: HTMLElement, scroller: HTMLElement | null, delta: number): void { + if (scroller === null) { + scrollClamped(viewport, delta) + return + } + if (delta > 0) { + const rest = delta - scrollClamped(viewport, delta) + if (rest > 0) scrollClamped(scroller, rest) + return + } + const rest = delta - scrollClamped(scroller, delta) + if (rest < 0) scrollClamped(viewport, rest) +} + +/** + * Drag scrolling velocity in pixels per millisecond for a pointer at `y`; positive scrolls down. + * The edges are those of the section scroller's part inside the viewport, or of the viewport alone. + */ +function dragVelocity(viewport: HTMLElement, scroller: HTMLElement | null, y: number): number { + const outer = viewport.getBoundingClientRect() + const inner = scroller?.getBoundingClientRect() ?? outer + const top = Math.max(outer.top, inner.top) + const bottom = Math.min(outer.bottom, inner.bottom) + const band = Math.min(DRAG_EDGE_PX, (bottom - top) / 2) + if (band <= 0) return 0 + const speed = (depth: number): number => DRAG_MAX_SPEED_PX_PER_MS * Math.min(1, depth / band) + if (y < top + band) return -speed(top + band - y) + if (y > bottom - band) return speed(y - (bottom - band)) + return 0 +} + /** Whether the viewport has scrolled the navigation away; sub-pixel remainders count as the end. */ function atEnd(viewport: HTMLElement): boolean { return viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop < 1 @@ -73,13 +127,35 @@ export function createScrollHandoff(): ScrollHandoff { } event.preventDefault() lastSplit = event.timeStamp - if (delta > 0) { - const rest = delta - scrollClamped(viewport, delta) - if (rest > 0) scrollClamped(scroller, rest) + scrollSplit(viewport, scroller, delta) + } + // The pointer of the latest dragover and the frame loop that scrolls toward it. + let drag: { y: number; at: number } | undefined + let frame: number | undefined + let lastFrame = 0 + const stopDrag = (): void => { + drag = undefined + if (frame !== undefined) cancelAnimationFrame(frame) + frame = undefined + } + const step = (viewport: HTMLElement, now: number): void => { + frame = undefined + if (drag === undefined || now - drag.at > DRAG_STALE_MS) { + drag = undefined return } - const rest = delta - scrollClamped(scroller, delta) - if (rest < 0) scrollClamped(viewport, rest) + const velocity = dragVelocity(viewport, scroller, drag.y) + if (velocity === 0) return + // A frame timestamp can precede the performance.now() of the dragover that requested it. + scrollSplit(viewport, scroller, velocity * Math.min(Math.max(now - lastFrame, 0), DRAG_MAX_STEP_MS)) + lastFrame = now + frame = requestAnimationFrame((time) => { step(viewport, time) }) + } + const dragOver = (viewport: HTMLElement, event: DragEvent): void => { + drag = { y: event.clientY, at: performance.now() } + if (frame !== undefined || dragVelocity(viewport, scroller, event.clientY) === 0) return + lastFrame = drag.at + frame = requestAnimationFrame((time) => { step(viewport, time) }) } const sectionScroller: SectionScroller = { bindScrollerRef: (element) => { scroller = element }, @@ -90,8 +166,24 @@ export function createScrollHandoff(): ScrollHandoff { releaseViewport = undefined if (element === null) return const onWheel = (event: WheelEvent): void => { handle(element, event) } + const onDragOver = (event: DragEvent): void => { dragOver(element, event) } + const onDragLeave = (event: DragEvent): void => { + if (!element.contains(event.relatedTarget as Node | null)) stopDrag() + } element.addEventListener('wheel', onWheel, { passive: false }) - releaseViewport = () => { element.removeEventListener('wheel', onWheel) } + // Capture: drop targets inside the viewport stop dragover propagation. + element.addEventListener('dragover', onDragOver, true) + element.addEventListener('dragleave', onDragLeave, true) + element.addEventListener('drop', stopDrag, true) + element.addEventListener('dragend', stopDrag, true) + releaseViewport = () => { + stopDrag() + element.removeEventListener('wheel', onWheel) + element.removeEventListener('dragover', onDragOver, true) + element.removeEventListener('dragleave', onDragLeave, true) + element.removeEventListener('drop', stopDrag, true) + element.removeEventListener('dragend', stopDrag, true) + } }, useSectionScroller: () => sectionScroller, } diff --git a/packages/client/ui-sidebar/tests/pointer-scrollbars.client.spec.tsx b/packages/client/ui-sidebar/tests/pointer-scrollbars.client.spec.tsx index 7b06396d72..d358115b03 100644 --- a/packages/client/ui-sidebar/tests/pointer-scrollbars.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/pointer-scrollbars.client.spec.tsx @@ -8,7 +8,7 @@ import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' */ import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render } from '@testing-library/react' +import { cleanup, fireEvent, render } from '@testing-library/react' import { allowAllAccess } from '@deepseek-ai/dsh-client-test-runtime' import type { SidebarRootComponentProps, SidebarSectionOwnerProps } from '../src/client/contract/slots.ts' import { SidebarRoot } from '../src/client/SidebarRoot.tsx' @@ -31,7 +31,6 @@ const useSessionStatus: SidebarRootComponentProps['useSessionStatus'] = selector afterEach(() => { cleanup() - vi.useRealTimers() }) /** @@ -79,96 +78,50 @@ function mountColumn(): { column: HTMLElement; quiet: () => boolean } { */ function movePointer(column: HTMLElement, direction: 'in' | 'out'): void { const outside = document.body - if (direction === 'in') fireEvent.pointerOver(column, { relatedTarget: outside }) - else fireEvent.pointerOut(column, { relatedTarget: outside }) + if (direction === 'in') fireEvent.pointerOver(column, { relatedTarget: outside, clientX: 40, clientY: 300 }) + else fireEvent.pointerOut(column, { relatedTarget: outside, clientX: COLUMN_WIDTH + 40, clientY: 300 }) } /** - * Move the pointer over the document, as a pointer crossing a fixed overlay - * that is a DOM descendant of the column does. + * Move the pointer over a descendant of the column, as a pointer crossing a + * fixed-position overlay rendered inside it does: the move bubbles to the + * column without any leave. + * @param target - the descendant the pointer is over. * @param x - client x coordinate. * @param y - client y coordinate. */ -function movePointerOverDocument(x: number, y: number): void { - fireEvent.pointerMove(document, { clientX: x, clientY: y }) +function movePointerOver(target: Element, x: number, y: number): void { + fireEvent.pointerMove(target, { clientX: x, clientY: y }) } describe('SidebarRoot pointer-revealed scrollbars', () => { - it('draws them only while the pointer is inside, and lingers on the way out', () => { - vi.useFakeTimers() + it('draws them only while the pointer is inside', () => { const { column, quiet } = mountColumn() // At rest — the pointer has never been over the column — the bars are off. expect(quiet()).toBe(true) movePointer(column, 'in') expect(quiet()).toBe(false) + // The quiet state applies on the leave itself; its stylesheet owns the + // delay and fade (scrollbar-quiet-styles.client.spec.ts). movePointer(column, 'out') - // The linger: still drawn just before the window closes, gone just after. - act(() => { vi.advanceTimersByTime(1999) }) - expect(quiet()).toBe(false) - act(() => { vi.advanceTimersByTime(1) }) expect(quiet()).toBe(true) - }) - - it('cancels a pending hide when the pointer comes back', () => { - vi.useFakeTimers() - const { column, quiet } = mountColumn() movePointer(column, 'in') - movePointer(column, 'out') - act(() => { vi.advanceTimersByTime(1000) }) - movePointer(column, 'in') - // The first leave's timer would fire here; a cancelled one leaves the bars - // drawn, which is what keeps a pointer skirting the edge from blinking them. - act(() => { vi.advanceTimersByTime(5000) }) expect(quiet()).toBe(false) }) - it('hides when the pointer moves outside the column box without leaving its subtree', () => { + it('follows the column box while the pointer is over a descendant overlay', () => { // ui-settings renders its full-viewport panel as a fixed-position // DESCENDANT of the column, so DOM containment reports the pointer as // still inside while it is visually somewhere else entirely. - vi.useFakeTimers() const { column, quiet } = mountColumn() + const overlay = column.querySelector('[data-testid="region"]') + if (overlay === null) throw new Error('region not rendered') movePointer(column, 'in') - expect(quiet()).toBe(false) - movePointerOverDocument(COLUMN_WIDTH + 400, 300) - act(() => { vi.advanceTimersByTime(2000) }) + movePointerOver(overlay, COLUMN_WIDTH + 400, 300) expect(quiet()).toBe(true) - }) - - it('does not restart the window when the pointer keeps moving outside', () => { - vi.useFakeTimers() - const { column, quiet } = mountColumn() - movePointer(column, 'in') - movePointer(column, 'out') - act(() => { vi.advanceTimersByTime(1500) }) - // A pending hide is left alone rather than re-armed: otherwise a pointer - // resting outside the column would keep pushing the bars' disappearance - // out, one move at a time. - movePointerOverDocument(COLUMN_WIDTH + 400, 300) - act(() => { vi.advanceTimersByTime(600) }) - expect(quiet()).toBe(true) - }) - - it('keeps them drawn while the pointer moves inside the column box', () => { - vi.useFakeTimers() - const { column, quiet } = mountColumn() - movePointer(column, 'in') - movePointer(column, 'out') - // A move landing back inside the box cancels the pending hide, the same - // way re-entering the element does. - movePointerOverDocument(COLUMN_WIDTH - 10, 300) - act(() => { vi.advanceTimersByTime(5000) }) + movePointerOver(overlay, COLUMN_WIDTH - 10, COLUMN_HEIGHT - 10) expect(quiet()).toBe(false) - }) - - it('drops the pending hide when the column unmounts', () => { - vi.useFakeTimers() - const { column } = mountColumn() - movePointer(column, 'in') - movePointer(column, 'out') - cleanup() - // A timer surviving the unmount would call setState on a dead component. - expect(() => { vi.advanceTimersByTime(5000) }).not.toThrow() - expect(vi.getTimerCount()).toBe(0) + movePointerOver(overlay, 10, COLUMN_HEIGHT + 10) + expect(quiet()).toBe(true) }) }) diff --git a/packages/client/ui-sidebar/tests/scroll-handoff.client.spec.ts b/packages/client/ui-sidebar/tests/scroll-handoff.client.spec.ts index d1f9438ac4..80acf4e4c8 100644 --- a/packages/client/ui-sidebar/tests/scroll-handoff.client.spec.ts +++ b/packages/client/ui-sidebar/tests/scroll-handoff.client.spec.ts @@ -1,5 +1,5 @@ // @vitest-environment jsdom -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createScrollHandoff } from '../src/client/scroll-handoff.ts' /** A scroll container whose scrollTop the browser would clamp to `[0, max]`; jsdom has no layout. */ @@ -154,6 +154,142 @@ describe('createScrollHandoff', () => { expect(wheel(next, { deltaY: 40 }).defaultPrevented).toBe(false) }) + describe('drag scrolling', () => { + let frames: Map + let now: number + + beforeEach(() => { + frames = new Map() + now = 1000 + let next = 0 + vi.spyOn(performance, 'now').mockImplementation(() => now) + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++next, callback) + return next + }) + vi.stubGlobal('cancelAnimationFrame', (id: number) => { frames.delete(id) }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + /** Run the pending frame `ms` after the previous one. */ + function tick(ms = 16): void { + now += ms + const pending = [...frames.values()] + frames.clear() + for (const callback of pending) callback(now) + } + + function place(element: HTMLElement, top: number, bottom: number): void { + element.getBoundingClientRect = () => DOMRect.fromRect({ x: 0, y: top, width: 200, height: bottom - top }) + } + + function dragEvent(target: HTMLElement, type: string, init: MouseEventInit = {}): void { + // jsdom has no DragEvent; the hand-off reads only MouseEvent members. + target.dispatchEvent(new MouseEvent(type, { bubbles: true, ...init })) + } + + /** The section scroller is visible from 140px to the viewport's bottom edge at 600px. */ + function dragBound() { + const parts = bound() + place(parts.viewport, 0, 600) + place(parts.scroller, 140, 900) + return parts + } + + it('moves the navigation away, then the section scroller, while a drag rests at the bottom edge', () => { + const { viewport, scroller } = dragBound() + dragEvent(scroller, 'dragover', { clientY: 600 }) + tick(50) + expect(viewport.scrollTop).toBe(50) + tick(100) + expect(viewport.scrollTop).toBe(100) + tick(50) + expect(viewport.scrollTop).toBe(130) + expect(scroller.scrollTop).toBe(20) + }) + + it('slows toward the inner side of the edge band and stops outside it', () => { + const { viewport, scroller } = dragBound() + dragEvent(scroller, 'dragover', { clientY: 576 }) + tick(40) + expect(viewport.scrollTop).toBe(20) + dragEvent(scroller, 'dragover', { clientY: 300 }) + tick(40) + expect(viewport.scrollTop).toBe(20) + expect(frames.size).toBe(0) + dragEvent(scroller, 'dragover', { clientY: 300 }) + expect(frames.size).toBe(0) + }) + + it('returns the section scroller to its top before the navigation at the top edge', () => { + const { viewport, scroller } = dragBound() + viewport.scrollTop = 130 + scroller.scrollTop = 30 + dragEvent(scroller, 'dragover', { clientY: 100 }) + tick(50) + expect(scroller.scrollTop).toBe(0) + expect(viewport.scrollTop).toBe(110) + }) + + it('uses the viewport edges without a bound section scroller', () => { + const { handoff, viewport } = dragBound() + handoff.useSectionScroller().bindScrollerRef(null) + dragEvent(viewport, 'dragover', { clientY: 590 }) + tick(30) + expect(viewport.scrollTop).toBeGreaterThan(0) + }) + + it('ignores an area too small for an edge band', () => { + const { scroller } = dragBound() + place(scroller, 700, 900) + dragEvent(scroller, 'dragover', { clientY: 599 }) + expect(frames.size).toBe(0) + }) + + it.each(['drop', 'dragend'])('stops at %s', (type) => { + const { viewport, scroller } = dragBound() + dragEvent(scroller, 'dragover', { clientY: 600 }) + dragEvent(scroller, type) + expect(frames.size).toBe(0) + tick(50) + expect(viewport.scrollTop).toBe(0) + }) + + it('stops when the drag leaves the viewport but not when it moves between its children', () => { + const { viewport, scroller } = dragBound() + dragEvent(scroller, 'dragover', { clientY: 600 }) + dragEvent(scroller, 'dragleave', { relatedTarget: viewport }) + expect(frames.size).toBe(1) + dragEvent(scroller, 'dragleave', { relatedTarget: document.body }) + expect(frames.size).toBe(0) + }) + + it('stops once dragover stops arriving', () => { + const { viewport, scroller } = dragBound() + dragEvent(scroller, 'dragover', { clientY: 600 }) + tick(50) + tick(700) + expect(viewport.scrollTop).toBe(50) + expect(frames.size).toBe(0) + }) + + it('keeps one frame loop across repeated dragover and cancels it on unbind', () => { + const { handoff, viewport, scroller } = dragBound() + dragEvent(scroller, 'dragover', { clientY: 600 }) + dragEvent(scroller, 'dragover', { clientY: 600 }) + expect(frames.size).toBe(1) + handoff.bindViewportRef(null) + expect(frames.size).toBe(0) + dragEvent(scroller, 'dragover', { clientY: 600 }) + expect(frames.size).toBe(0) + expect(viewport.scrollTop).toBe(0) + }) + }) + it('hands every caller the same scroller binding', () => { const handoff = createScrollHandoff() expect(handoff.useSectionScroller()).toBe(handoff.useSectionScroller()) diff --git a/packages/client/ui-sidebar/tests/scrollbar-quiet-styles.client.spec.ts b/packages/client/ui-sidebar/tests/scrollbar-quiet-styles.client.spec.ts index b0ee9383a0..60e9c78251 100644 --- a/packages/client/ui-sidebar/tests/scrollbar-quiet-styles.client.spec.ts +++ b/packages/client/ui-sidebar/tests/scrollbar-quiet-styles.client.spec.ts @@ -12,19 +12,43 @@ const css = readFileSync(fileURLToPath(new URL('../src/client/SidebarRoot.module /** Declarations only: the sheet's prose names the properties it explains. */ const declarationText = css.replace(/\/\*[\s\S]*?\*\//g, ' ') +/** + * The quiet rule's declarations, trimmed. + * @returns each declaration of `.root.quietBars` as written. + */ +function quietDeclarations(): string[] { + const rule = /\.root\.quietBars\s*\{([^{}]*)\}/.exec(declarationText) + expect(rule).not.toBeNull() + return (rule![1] ?? '').split(';').map(part => part.trim()).filter(Boolean) +} + describe('SidebarRoot.module.css quiet column', () => { it('rebinds the ui-theme indirection pair to transparent', () => { // The pair, not the resting thumb alone: rebinding one leaves the other // painting its base-surface colour the moment the pointer reaches the bar. - const rule = /\.root\.quietBars\s*\{([^{}]*)\}/.exec(declarationText) - expect(rule).not.toBeNull() - const declarations = (rule![1] ?? '').split(';').map(part => part.trim()).filter(Boolean).sort() + const declarations = quietDeclarations().filter(part => !part.startsWith('transition')).sort() expect(declarations).toEqual([ '--dsh-scrollbar-thumb-hover: transparent', '--dsh-scrollbar-thumb: transparent', ].sort()) }) + it('fades both halves of the pair out after a delay, and only on the way to quiet', () => { + const transition = quietDeclarations().find(part => part.startsWith('transition:')) + expect(transition?.replace(/\s+/g, ' ')).toBe( + 'transition: --dsh-scrollbar-thumb 200ms linear 500ms, --dsh-scrollbar-thumb-hover 200ms linear 500ms', + ) + // A reveal has no transition: the base rule declares none. + const base = /(?:^|\})\s*\.root\s*\{([^{}]*)\}/.exec(declarationText) + expect(base).not.toBeNull() + expect(base![1]).not.toMatch(/transition/) + }) + + it('keeps the delay and drops the fade under reduced motion', () => { + const reduced = /@media \(prefers-reduced-motion: reduce\)\s*\{([\s\S]*)\}\s*$/.exec(declarationText) + expect(reduced?.[1]).toMatch(/\.root\.quietBars\s*\{\s*transition-duration:\s*0s;\s*\}/) + }) + it('leaves the gutter reservation to the scrolling region', () => { // Hiding the thumb must not move a row: the reservation lives on the list // (ui-workspace), so the column states colour only. diff --git a/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts b/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts index aa54025244..789c7cd550 100644 --- a/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts +++ b/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts @@ -111,7 +111,7 @@ describe('SidebarRoot.module.css', () => { it('keeps the reviewed expanded spacing separate from rail and caption controls', () => { expect(declarations('.logoRow')?.get('padding')).toBe('8px 0 8px 8px') expect(declarations('.logoRow')?.get('margin-bottom')).toBe('0') - expect(declarations('.newSessionRow')?.get('margin')).toBe('0 calc(var(--dsh-sidebar-paint-inset) + 1px)') + expect(declarations('.newSessionRow')?.get('margin')).toBe('0 calc(var(--dsh-sidebar-paint-inset) + 1px) 6px') expect(declarations('.newSession')?.get('margin')).toBe('0') expect(declarations('.newSessionContent')?.get('justify-content')).toBe('center') expect(declarations(":global(html[data-platform='darwin']:not([data-fullscreen])) .root:not(.collapsed) > .topStrip > .toggle")?.get('transform')).toBe('translateX(4px)') diff --git a/packages/client/ui-skill/src/client/SkillRow.tsx b/packages/client/ui-skill/src/client/SkillRow.tsx index cee91367cf..fb3c3710ca 100644 --- a/packages/client/ui-skill/src/client/SkillRow.tsx +++ b/packages/client/ui-skill/src/client/SkillRow.tsx @@ -27,16 +27,17 @@ function firstLine(text: string): string { /** Skill names are the only call argument the compact row presents. */ function skillName(argsRaw: string, callId: string): string { + let parsed: unknown try { - const parsed: unknown = JSON.parse(argsRaw) - if (typeof parsed === 'object' && parsed !== null) { - const name = (parsed as Record).name - if (typeof name === 'string' && name !== '') return firstLine(name) - } - } catch { + parsed = JSON.parse(argsRaw) + } catch (_truncatedArgs) { // Streaming can expose a truncated JSON prefix; its first line is still // more useful than replacing the call with an unrelated catalog lookup. } + if (typeof parsed === 'object' && parsed !== null) { + const name = (parsed as Record).name + if (typeof name === 'string' && name !== '') return firstLine(name) + } return argsRaw === '' ? callId : firstLine(argsRaw) } diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 7381b1f9d5..0666bc24d6 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-subagent/README.md /: - en: ff1b1fbd0d7f629b - zh: c68a59640e73c0ce + en: 49ee66424b5c8618 + zh: 4441c8abb6dc84d3 /deepseek-ai-dsh-client-ui-subagent: en: 930db612ece65ad4 zh: ad7e9d9afb4545ac /deepseek-ai-dsh-client-ui-subagent/summary: - en: 6e0bbf514ad3bef7 - zh: 5a29d88c124d35cc + en: bf25f4c1e4529221 + zh: f47270149bb0466f /deepseek-ai-dsh-client-ui-subagent/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-subagent/use-this-package: - en: c7a9485c0cdcd9de - zh: 903ad54e44d79eae + en: e912edfd1406cc33 + zh: da0a59a27fb4a65c /deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree: - en: 35e983f0276188d0 - zh: df588dc1523031da + en: da87d582146106c4 + zh: f640b3a3fcc11209 /deepseek-ai-dsh-client-ui-subagent/use-this-package/continuing-a-conversation: en: e4ec261d3b122eb5 zh: 320bb2efc93dccdc @@ -30,17 +30,17 @@ en: c158f12dcaed87b7 zh: e5d315e7b1fb4fa9 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation: - en: 3c06acc93d7d4d59 - zh: b967155aec39df0c + en: 00965349c6aa0639 + zh: 465e3585dc7c9131 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens: - en: dcbc58d4cad47fa8 - zh: e962a8cbdfd4a914 + en: 88ac879a43f1a8d7 + zh: f62c7b02e3658507 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/composer-election: - en: 8ff34f93e40fbdc2 - zh: cc3430130c9df0a4 + en: b56cfe4a6bc89088 + zh: c0d15e2b96df11ae /deepseek-ai-dsh-client-ui-subagent/further-exploration: - en: 1766e9012e307178 - zh: f3ee637f5941aae5 + en: 24c8ea783899b577 + zh: baa248477f0b9474 /deepseek-ai-dsh-client-ui-subagent/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -57,8 +57,8 @@ en: de2762a99572475f zh: 9b41107ad14ebf8a /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work: - en: ea983111988e4b9b - zh: c0ed7a583d2cad52 + en: de28efa7934ae6aa + zh: 5f3f682c10c1ce4c /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 555c6fd2d9..f64c1a7b2c 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -1,5 +1,5 @@ --- -description: "Subagent conversation catalog, continuation routing UI, and '@' reference source for the dsh web client." +description: "Subagent conversation catalog in the Session panel, breadcrumb sibling switcher, continuation routing UI, and '@' reference source for the dsh web client." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Browse local subagent conversations and external tasks from the parent header. Local conversations show activity, token usage, and duration; continuable children accept follow-up prompts and support Stop. External tasks appear as non-navigable leaves without an execution status. Historical one-shot conversations open as read-only records. The ordinary sidebar omits subagent conversations, and the separate `@` source inserts a running child's label without granting continuation authority. +Browse local subagent conversations and external tasks in the Session panel's Subagents section, and switch between siblings from a child conversation's breadcrumb. Local conversations show activity, token usage, and duration; continuable children accept follow-up prompts and support Stop. External tasks appear as non-navigable leaves without an execution status. Historical one-shot conversations open as read-only records. The ordinary sidebar omits subagent conversations, and the separate `@` source inserts a running child's label without granting continuation authority. ## Table of Contents @@ -25,21 +25,21 @@ Browse local subagent conversations and external tasks from the parent header. L ## Use this package -The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and discovers the next level on explicit activation. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. +The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. Each subagent breadcrumb title is a switcher over its parent's direct catalog that marks the title's Session as current; root Sessions have no switcher. The [Session panel](../ui-session-panel/README.md#contribute-a-section) section `subagents` (order 200, titled “Subagents”) lists the current Session's direct catalog, in root and child conversations alike, when the catalog has entries or a read has failed. Showing the section reads nothing; expanding a branch prepares that branch. An absent or empty catalog hides the section and its title unless a footer contribution is available and the Session's enabled `agentTeam` projection has nondeleted shared tasks or a task-record error. Enabling Team mode alone does not show an empty section. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. Either action closes the panel's overlay or the switcher menu that holds the row. -This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. +This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. A Workspace picked in a blank child's Hero opens that Workspace's blank Session as the main Session and moves the draft to it, as the main Conversation does. -Every open catalog menu is 360px wide with 6px outer padding, constrained to fit the layout viewport. The root menu shows noncollapsible Subagents and Shared tasks headers only when Team mode is enabled, at least one nondeleted shared task exists, and the footer contribution is available. The Subagents header uses a Users icon and counts direct entries in completed, in progress, not running, and external order; zero counts are omitted and the separator matches the input task list. External tasks never count as running or completed. An empty Subagents section shows “No subagents” only alongside shared tasks. With Team mode off or no shared tasks, the menu shows only the subagent list, without section headers, a shared-task module, empty-state copy, or a divider; a real task-record failure remains a separate alert. Shared tasks have a 4px top margin rather than a divider. Both section headers keep a 7px icon/title gap and an additional 4px before their counts. Only the menu scrolls; sections have no nested scrolling. In WebKit-compatible browsers, the native 5px scrollbar sits in the right 6px inset with inset track ends and a stable gutter, preserving content width when scrolling becomes necessary. Other browsers retain their standard native scrollbar. +The section's title control (`conversation.session.panel.section.actions`, key `subagents`) shows direct-member progress: completed, in progress, not running, and external counts in that order, with zero counts omitted and the separator matching the input task list. External tasks never count as running or completed. The section lists running subagents first, the most recently started first, and then the others, the most recently updated first. It shows five rows and then the Session panel's fold control, “Show {count} more”, which shows the rest and then reads “Show less”; the list folds only when that holds back two rows or more, the choice holds for the Session, also after the panel is hidden and shown again, and an expanded branch's own rows all show. The section hides with its title while the Session has no subagents and no failed catalog read. While direct subagents run and the panel does not show, a blue dot on the panel toggle (`conversation.session.panel.indicator`) says so and names their number for assistive technology; external tasks do not count. The Session panel scrolls the section; the tree has no nested scrolling. The breadcrumb switcher menu is 360px wide with 6px outer padding, constrained to fit the layout viewport, and only the menu scrolls. In WebKit-compatible browsers, its native 5px scrollbar sits in the right 6px inset with inset track ends and a stable gutter, preserving content width when scrolling becomes necessary. Other browsers retain their standard native scrollbar. -The root catalog exposes `conversation.session.header.actions.subagent.footer` for shared tasks. Child and ancestor breadcrumb catalogs show navigation only, without section headers. +Breadcrumb switcher menus show navigation only. -The wide root count trigger shows a 14px Users icon in its 14px slot when no child is running and the shared ongoing loader otherwise, without a dropdown arrow. As the title row narrows, passive preset text hides at widths of 540px or less and the count text hides at 460px or less. The compact trigger always shows the Users icon, including while children are running; running indicators remain inside the menu. It matches More and sidebar controls: a 28×28px action with no padding, a 15px glyph in a 15px slot, secondary ink, and ghost hover and active backgrounds. Header actions use an 8px gap in compact layout and 10px in wide layout. The icon-only tooltip exposes the full count. Resizing preserves focus on the trigger. Subagent switchers retain their description-first text and existing icon. +The switcher title is at most 244px wide, ellipsizes, and is followed by an up-down chevron icon. The current Session's title uses primary ink at weight 500; an ancestor's title uses tertiary ink at regular weight. ### Browsing the tree -Count, owner, and sidebar-action tooltips appear after 500ms of hover. Hovering a text-visible trigger opens its catalog after 150ms; leaving both trigger and catalog closes it after 120ms. Clicking the descendant-count trigger opens and pins its catalog, or closes an already pinned catalog. The icon-only count trigger does not open on hover, including when a pending hover crosses into the narrow layout. Clicking toggles its pinned menu; ArrowDown opens and pins the menu and focuses its first row. Outside click or Escape dismisses a pinned menu. Clicking moves focus into the panel, where ArrowDown/Home enters the first tree row and ArrowUp/End enters the last; Escape returns focus when it was inside. Breadcrumb-title clicks navigate to the corresponding conversation. +The sidebar-action tooltip appears after 500ms of hover. Hovering a switcher with a non-touch pointer opens its menu after 150ms; leaving both the switcher and its menu closes it after 120ms. Clicking the current Session's title opens and pins the menu and moves focus into it, and a pinned menu ignores pointer leave; clicking an ancestor's title navigates to that ancestor instead. ArrowDown on a switcher opens its menu and focuses the first row; on an open menu it moves focus into the menu, to the first row once the rows have loaded. An outside press or Escape closes the menu, and Escape returns focus to the switcher when focus was inside the menu. -Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. Only rows with confirmed children show an expansion arrow. Clicking or keyboard-opening the menu reads its catalog and its direct children; expanding a branch does the same for that branch. Each activation reads direct children sequentially through the existing projection reader, which reuses completed reads and merges in-flight requests. It does not recursively discover deeper descendants. Hover and rendering do not initiate reads. Once started, a level read may finish after the menu closes. Missing catalogs show no expansion arrow or unknown marker; shared projection updates reveal confirmed branches while preserving the agent activity marker. Failed reads keep navigation available and offer Retry. +Rows show the creation description, or an available Session title, with the agent name, which is unique among its siblings: in switcher menus the name sits below the title, and in the Session panel each row is one 28px line whose hover card, after 500ms of hover, shows the title, the name as its owner, the activity with the mode, and the token total and exact duration. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding. In the Session panel they follow the panel's columns: the status glyph's center 14px from the row start, titles at 30px, and the sidebar arrow's center 14px from the row end. In switcher menus, their clickable content uses 6px horizontal padding and 7px gaps while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow, a 24px target whose glyph darkens on hover without a fill in the panel and in switcher menus alike. Primary titles use 13px text and secondary names use 12px. Switcher rows wrap descriptions and names in full, including on touch screens; panel titles clip with an ellipsis, and the row's accessible name keeps the name, mode, activity, and measures. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same status column, 16px in the panel and 14px in switcher menus, centering smaller dots so titles align with the loader state. In switcher menus the trailing column stacks total durable provider usage above active-turn duration; panel rows show only the compact duration, in 12px text. In the tree, Enter or Space opens the focused row, ArrowRight/ArrowLeft expand and collapse branches, and ArrowUp/ArrowDown, Home, and End move between rows. An unlabeled one-shot row falls back to its session id. Only rows with confirmed children show an expansion arrow. Preparing a level reads its catalog and its direct children sequentially through the existing projection reader, which reuses completed reads and merges in-flight requests; it does not recursively discover deeper descendants. Once started, a level read may finish after the panel hides or the menu closes. Missing catalogs show no expansion arrow or unknown marker; shared projection updates reveal confirmed branches while preserving the agent activity marker. Failed reads keep navigation available and offer Retry. ### Continuing a conversation @@ -61,17 +61,17 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and ### Catalog derivation -The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering and hovering use only local projections and never request missing catalogs. An unread empty menu says “Subagents not loaded”; the loading notice appears only during a request. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. +The Subagents section, its progress control, and the breadcrumb switcher read `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-tree subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Showing the section, rendering, and hovering use only local projections and never request missing catalogs. An unread empty switcher menu says “Subagents not loaded”; the loading notice appears only during a request. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. -Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. +The Session panel owns showing, scrolling, and dismissing the section. The switcher menu is a body-mounted `MenuSurface`; CSS anchors keep it attached to its title within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. -Explicit menu activation, branch expansion, and failed-read retries call `prepareCatalog` to read the current catalog and its direct children. Ancestor-title clicks navigate to that Session. The Session object layer deduplicates reads and refreshes previously requested projections after reconnect. +A pinning click or ArrowDown on a switcher title, branch expansion, and failed-read retries call `prepareCatalog` to read the current catalog and its direct children; a rejected preparation is logged to the console. Ancestor-title clicks navigate to that Session. The Session object layer deduplicates reads and refreshes previously requested projections after reconnect. Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors. ### Duration, completion, and tokens -Each visible catalog level advances its own clock while it contains a running child; collapsing the level or closing the menu releases that clock. Token totals sum the four disjoint `tokenUsage` buckets. The `subagentTiming` projection sums completed-turn duration and supplies `latestTurnCompleted` for both the success dot and completed count; opening another turn clears that completion until its own `turn/end`. Duration advances once per second only for an open turn on a running child and freezes after the child becomes inactive; an interrupted open turn is bounded by its same-cut `active.through`, never by newer session metadata. +Each visible catalog level advances its own clock while it contains a running child; collapsing the level, hiding the panel, or closing the switcher menu releases that clock. Token totals sum the four disjoint `tokenUsage` buckets. The `subagentTiming` projection sums completed-turn duration and supplies `lastTurnCompleted` for both the success dot and completed count; opening another turn clears that completion until its own `turn/end`. Duration advances once per second only for an open turn on a running child and freezes after the child becomes inactive; an interrupted open turn is bounded by its same-cut `active.through`, never by newer session metadata. ### Composer election @@ -79,7 +79,7 @@ One-shot and unknown-mode children elect a read-only composer. Continuable child Unknown-mode catalog rows remain visible and clickable, using the child id when no label is available. Their composer is read-only until child history establishes a supported mode; a read failure is reported in the child conversation. -Lineage-menu highlights follow the [standard menu edge geometry](../../../docs/ui-radius.md#nested-hover). Each branch disclosure target covers its 28px left gutter and full row height without overlapping adjacent rows; only the 12px glyph rotates in place, and disclosure clicks do not trigger row or sidebar navigation. Disclosure hover highlights only its arrow; navigation-body hover and keyboard focus retain their background highlight. Thin level-3 border connectors align with the first-line glyph centers, cross reserved disclosure space to reach leaf status glyphs, and end the final vertical stem at its glyph center. +Catalog row highlights use the standard menu item radius from the [nested geometry rules](../../../docs/ui-radius.md#nested-hover). Each branch disclosure target covers its 28px left gutter and full row height without overlapping adjacent rows; only the 12px glyph rotates in place, and disclosure clicks do not trigger row or sidebar navigation. Disclosure hover highlights only its arrow; navigation-body hover and keyboard focus retain their background highlight. Thin level-3 border connectors align with the first-line glyph centers, cross reserved disclosure space to reach leaf status glyphs, and end the final vertical stem at its glyph center.
      @@ -90,7 +90,8 @@ Lineage-menu highlights follow the [standard menu edge geometry](../../../docs/u These pages cover the conversation surface, the host seam, and the design notes. -- [ui-conversation](../ui-conversation/README.md) — the chat surface hosting the header action and composer chain. +- [ui-conversation](../ui-conversation/README.md) — the chat surface hosting the breadcrumb lineage and composer chain. +- [ui-session-panel](../ui-session-panel/README.md) — the Session panel hosting the Subagents section. - [ui-input-trigger](../ui-input-trigger/README.md) — the suggestion machinery hosting the `@` source. - [subagent](../../subagent/subagent/README.md) — the host-side capability seam behind continuable children. - [historical Web subagent conversations](../../../.agents/notes/archived/feature/2026-07-27-web-subagent-conversations.md) — the catalog and composer specification. @@ -125,6 +126,7 @@ These limits define what the catalog can show and what `@` references mean; they - **Non-completed inactive outcomes remain grouped** — the catalog distinguishes a latest normal completion from other inactive states, but does not distinguish failure, cancellation, refusal, token exhaustion, or a child with no closed turn; the UI exposes no Activation identity, and stopping is limited to the composer's current-turn Stop for a running continuable child. - **Ancestor menus require keyboard activation for uncached branches** — hovering does not read, and clicking the ancestor title navigates. Focus the title and press ArrowDown to prepare that level without leaving the current Session. - **Level discovery stops on interruption** — an unexpected read rejection stops later siblings and is logged to the console. A reconnect can interrupt discovery before direct children are read; explicitly reopen the menu to prepare the level again. +- **The Session panel section has no level activation** — showing the section reads nothing, so a direct subagent whose catalog the Session list has not cached offers no expansion arrow there until its catalog arrives, for example after its own conversation opens or a sibling's breadcrumb switcher prepares the level. - **`@` references remain display-title text** — duplicate or renamed labels are ambiguous, so they intentionally do not acquire continuation semantics. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 056fad6cde..4a794b4476 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -1,5 +1,5 @@ --- -description: "dsh Web 客户端的 subagent 对话目录、续接路由 UI 与 '@' 引用 source。" +description: "dsh Web 客户端会话面板中的 subagent 对话目录、面包屑同级切换器、续接路由 UI 与 '@' 引用 source。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -从父会话页头浏览本地子代理对话与外部任务。本地对话展示活跃状态、token 用量和耗时;可继续子代理接受后续提示词并支持 Stop。外部任务显示为不可打开的叶子项,不展示执行状态。历史一次性对话以只读记录打开。普通侧边栏省略子代理对话;独立的 `@` 来源插入运行中子代理的标签,不授予继续执行权限。 +在会话面板的「子智能体」分栏中浏览本地子代理对话与外部任务,并从子会话的面包屑切换同级子代理。本地对话展示活跃状态、token 用量和耗时;可继续子代理接受后续提示词并支持 Stop。外部任务显示为不可打开的叶子项,不展示执行状态。历史一次性对话以只读记录打开。普通侧边栏省略子代理对话;独立的 `@` 来源插入运行中子代理的标签,不授予继续执行权限。 ## 目录 @@ -25,21 +25,21 @@ kind: "package-reference" ## 使用本包 -会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并在用户显式打开时发现下一层目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。 +会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。每个 subagent 面包屑标题都是覆盖其父会话直接目录的切换器,并把该标题对应的 Session 标为当前项;根 Session 没有切换器。[会话面板](../ui-session-panel/README.zh.md#contribute-a-section)分栏 `subagents`(order 200,标题为“子智能体”)在根会话和子会话中都列出当前 Session 的直接目录,前提是目录有子项或读取失败。显示分栏不读取任何内容;展开分支时准备该分支。目录缺席或为空时,分栏连同标题一起隐藏,除非存在可用的 footer 扩展,且 Session 已开启的 `agentTeam` 投影含有未删除的共享任务或任务记录错误。仅开启 Team 模式不会显示空分栏。选择任意深度的本地 child,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。两种操作都会关闭面板浮层或该行所在的切换器菜单。 -本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。 +本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。在空白 child 的 Hero 中选择工作区时,与主 Conversation 一样,把该工作区的空白 Session 打开为主 Session,并把草稿移过去。 -每个打开的目录菜单宽度均为 360px,外层内边距为 6px,并受布局视口可用宽度约束。仅当 Team 模式已开启、存在至少一个未删除的共享任务且 footer 扩展可用时,根菜单才显示不可折叠的“子智能体”和“共享任务”标题。“子智能体”标题使用 Users 图标,仅统计直接条目,依次显示已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。空的“子智能体”区域仅在同时展示共享任务时显示“暂无子智能体”。Team 模式关闭或没有共享任务时,菜单仅显示 subagent 列表,不显示区域标题、共享任务模块、空状态文案或分隔线;真实的任务记录错误仍以独立警告显示。共享任务上方保留 4px 外边距,不显示分隔线。两个区域标题均保留 7px 图标与文字间距,并在统计数量前额外留出 4px。仅菜单本身滚动,各区域不单独滚动。在兼容 WebKit 的浏览器中,原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 +分栏的标题控件(`conversation.session.panel.section.actions`,键为 `subagents`)显示直接成员进度:依次为已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。分栏把运行中的子智能体排在最前,最近开始的在前,然后是其余的,最近更新的在前。它只显示五行,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变;展开某个分支后,该分支自己的行全部显示。会话没有子智能体且目录读取未失败时,分栏连同标题一起隐藏。直接子智能体运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;外部任务不计入。会话面板负责分栏滚动,目录树不单独滚动。面包屑切换器菜单宽度为 360px,外层内边距为 6px,并受布局视口可用宽度约束,仅菜单本身滚动。在兼容 WebKit 的浏览器中,其原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 -根会话目录通过 `conversation.session.header.actions.subagent.footer` 提供共享任务扩展。子会话与祖先面包屑目录只显示导航,不显示区域标题。 +面包屑切换器菜单只显示导航。 -宽布局下,根会话数量触发器在没有运行中 child 时,于 14px 图标位内显示 14px Users 图标,否则显示共享 ongoing loader,不带下拉箭头。标题行变窄时,静态预设文字在宽度不超过 540px 时隐藏,数量文字在不超过 460px 时隐藏。紧凑触发器始终显示 Users 图标,包括 child 运行期间;运行指示器仍在菜单内显示。它与更多及侧边栏控件一致:28×28px 操作区域,无内边距,15px 图标位内显示 15px 图标,使用次级前景色以及 ghost 悬停和按下背景。页头操作在紧凑布局中间距为 8px,宽布局中为 10px。纯图标工具提示提供完整数量。调整宽度不会丢失触发器焦点。subagent 切换器保留描述优先的文本与原有图标。 +切换器标题最宽 244px,超出时以省略号截断,后接上下双向箭头图标。当前 Session 的标题使用主前景色、字重 500;祖先标题使用三级前景色、常规字重。 ### 浏览目录 -数量、负责人及侧边栏操作的工具提示在悬停 500ms 后显示。悬停文字可见的触发器 150ms 后打开目录;指针离开触发器和目录后,经过 120ms 关闭。点击后代数量触发器会打开并固定目录,或关闭已固定的目录。纯图标数量触发器不会因悬停而打开,包括等待悬停打开期间切换到窄布局的情况。点击可切换固定菜单的开关状态;ArrowDown 会打开并固定菜单,并将焦点移至首行。点击外部或按 Escape 可关闭已固定的菜单。点击会将焦点移入面板,此时 ArrowDown/Home 进入首个树行,ArrowUp/End 进入最后一个树行;Escape 在焦点原本位于面板内时将其送回。点击面包屑标题会导航至对应会话。 +侧边栏操作的工具提示在悬停 500ms 后显示。非触摸指针悬停切换器 150ms 后打开其菜单;指针离开切换器和菜单后,经过 120ms 关闭。点击当前 Session 的标题会打开并固定菜单,并将焦点移入菜单,已固定的菜单不因指针离开而关闭;点击祖先标题则导航至该祖先。在切换器上按 ArrowDown 会打开菜单,并将焦点移至首行;菜单已打开时,焦点移入菜单,行加载完成后移至首行。点击外部或按 Escape 可关闭菜单;焦点原本位于菜单内时,Escape 将焦点送回切换器。 -目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。点击或通过键盘打开菜单时,读取当前目录及其直属子节点的目录;展开分支时对该分支执行相同操作。每次打开操作通过现有投影读取器依次读取直接子节点,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。悬停与渲染不触发读取。已开始的单层读取可能在菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 +目录行显示创建描述(缺少时使用可用的 Session title)和智能体名称,名称在同级子智能体中唯一:切换器菜单中名称位于标题下方;会话面板中每行只占 28px 一行,悬停 500ms 后的悬停卡片显示标题、作为负责人的名称、活动状态与模式,以及 token 总计和精确耗时。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距。在会话面板中,它们遵循面板的列:状态图标中心距行起始 14px,标题从 30px 开始,侧边栏箭头中心距行末端 14px。在切换器菜单中,可点击内容使用 6px 水平内边距和 7px 间距,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头:点击区域 24px,在面板和切换器菜单中都是悬停时箭头变深、没有底色。主标题使用 13px 文字,次级名称使用 12px。切换器菜单中的行将描述与名称换行完整展示,包括在触屏上;面板中的标题以省略号截断,行的无障碍名称仍包含名称、模式、活动状态与度量。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的列宽(面板中 16px,切换器菜单中 14px),并将较小的圆点居中,使 title 与 loading 状态对齐。切换器菜单中,尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时;面板中的行只以 12px 文字显示简短耗时。在目录树中,Enter 或 Space 打开获得焦点的行,ArrowRight/ArrowLeft 展开和折叠分支,ArrowUp/ArrowDown、Home 与 End 在行间移动。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。准备一层时,通过现有投影读取器依次读取其目录及直接子节点的目录,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。已开始的单层读取可能在面板隐藏或菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 ### 续接对话 @@ -61,17 +61,17 @@ kind: "package-reference" ### 目录派生 -页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 +「子智能体」分栏、其进度控件与面包屑切换器通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需逐树订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。显示分栏、渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空切换器菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 -每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 +会话面板负责分栏的显示、滚动和关闭。切换器菜单是挂载到 body 的 `MenuSurface`;CSS 锚点让菜单跟随其标题,并按布局视口限制尺寸。浏览器缩放和平移时菜单随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 -显式激活菜单、展开分支或重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 +在切换器标题上固定打开的点击或按 ArrowDown、展开分支以及重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点;准备被拒绝时记录到控制台。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。 ### 耗时、完成状态与 token -每个可见目录层在包含运行中 child 时独立推进时钟;折叠该层或关闭菜单会释放时钟。token 用量总计为四个互不重叠的 `tokenUsage` 桶之和。`subagentTiming` 投影会累加已结束轮次的耗时,并提供 `latestTurnCompleted`,用于成功圆点与已完成数量;新轮次开始时会清除该完成状态,直到自身的 `turn/end` 到达。耗时仅在运行中 child 存在未结束轮次时每秒递增一次,并在 child 变为 inactive 后冻结;被中断的未结束轮次以其同一切面的 `active.through` 为上界,绝不使用更新的会话元数据。 +每个可见目录层在包含运行中 child 时独立推进时钟;折叠该层、隐藏面板或关闭切换器菜单会释放时钟。token 用量总计为四个互不重叠的 `tokenUsage` 桶之和。`subagentTiming` 投影会累加已结束轮次的耗时,并提供 `lastTurnCompleted`,用于成功圆点与已完成数量;新轮次开始时会清除该完成状态,直到自身的 `turn/end` 到达。耗时仅在运行中 child 存在未结束轮次时每秒递增一次,并在 child 变为 inactive 后冻结;被中断的未结束轮次以其同一切面的 `active.through` 为上界,绝不使用更新的会话元数据。 ### 编辑器选举 @@ -79,7 +79,7 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 模式未知的目录项仍可见、可点击,没有标签时显示子会话 id。读取子历史并确认受支持模式前,输入区保持只读;读取失败在该子会话中报告。 -会话树菜单高亮遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover)。每个分支展开控件的点击区域覆盖左侧 28px 空间与所在行的完整高度,不与相邻行重叠;仅原位的 12px 图标旋转,点击展开控件不会触发行导航或侧边栏导航。悬停展开控件仅高亮箭头;悬停导航主体或键盘聚焦时仍保留背景高亮。细连接线使用三级边框颜色,与首行图标中心对齐,跨过预留的展开控件空间连接叶子状态图标,末端竖线止于对应图标中心。 +目录行高亮使用[嵌套几何规则](../../../docs/ui-radius.zh.md#nested-hover)中的标准菜单项圆角。每个分支展开控件的点击区域覆盖左侧 28px 空间与所在行的完整高度,不与相邻行重叠;仅原位的 12px 图标旋转,点击展开控件不会触发行导航或侧边栏导航。悬停展开控件仅高亮箭头;悬停导航主体或键盘聚焦时仍保留背景高亮。细连接线使用三级边框颜色,与首行图标中心对齐,跨过预留的展开控件空间连接叶子状态图标,末端竖线止于对应图标中心。
      @@ -90,7 +90,8 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 以下页面覆盖对话界面、宿主 seam 与设计笔记。 -- [ui-conversation](../ui-conversation/README.zh.md)——承载页头操作与编辑器链的聊天界面。 +- [ui-conversation](../ui-conversation/README.zh.md)——承载面包屑谱系与编辑器链的聊天界面。 +- [ui-session-panel](../ui-session-panel/README.zh.md)——承载「子智能体」分栏的会话面板。 - [ui-input-trigger](../ui-input-trigger/README.zh.md)——承载 `@` source 的建议机制。 - [subagent](../../subagent/subagent/README.zh.md)——可继续 child 背后的宿主能力 seam。 - [历史Web subagent 对话](../../../.agents/notes/archived/feature/2026-07-27-web-subagent-conversations.md)——目录与编辑器规范。 @@ -125,6 +126,7 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 - **非完成的 inactive 结果仍合并显示**:目录能区分最近一次正常完成与其他 inactive 状态,但不区分失败、取消、拒绝、token 耗尽或尚无已结束轮次的 child;UI 不公开 Activation 身份,停止能力仅限编辑器上针对运行中可继续 child 的当前轮次 Stop。 - **祖先菜单的未缓存分支需要键盘激活**:悬停不读取,点击祖先标题会导航。聚焦标题后按 ArrowDown,可在不离开当前 Session 的情况下准备这一层。 - **单层发现会在中断后停止**:意外的读取拒绝会停止后续兄弟节点,并记录到控制台。重连可能在直接子节点读取前中断发现;需再次显式打开菜单来准备这一层。 +- **会话面板分栏没有层级激活**:显示分栏不读取任何内容,因此 Session 列表未缓存其目录的直接子智能体在分栏中没有展开箭头,直到其目录到达,例如打开它自己的对话后,或在兄弟会话的面包屑切换器中准备这一层后。 - **`@` 引用仍是显示标题文本**:重复或改名后的 label 会有歧义,因此它们刻意不获得继续执行语义。 diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index f6b08201bc..0f3ac4e008 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -34,10 +34,11 @@ "@deepseek-ai/dsh-client-resources", "@deepseek-ai/dsh-client-ui-chat", "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives", - "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-input-trigger", + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel", "@deepseek-ai/dsh-client-ui-session-status", + "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-workspace" ], "platform": "web" @@ -52,28 +53,29 @@ "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", + "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-api-session-controller": "workspace:*", - "@deepseek-ai/dsh-client-connection": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", - "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", - "@deepseek-ai/dsh-client-ui-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", - "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", - "@deepseek-ai/dsh-agent-team": "workspace:*" + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css similarity index 74% rename from packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css rename to packages/client/ui-subagent/src/client/SubagentCatalog.module.css index c450098395..86cc042428 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css @@ -11,7 +11,6 @@ margin-left: 6px; } -.trigger, .switcherTrigger { display: inline-flex; align-items: center; @@ -26,10 +25,6 @@ cursor: pointer; } -.trigger { - gap: 4px; -} - .switcherTrigger { gap: 4px; min-width: 0; @@ -57,25 +52,6 @@ flex: none; } -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-primary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-primary); - } -} - .switcherTrigger:focus-visible { color: var(--dsw-alias-label-primary); } @@ -100,55 +76,6 @@ transition: transform 120ms ease; } -.trigger .compactIcon { - display: none; -} - -/* The title-row container drops passive preset text at 540px; this action yields later. */ -@container (max-width: 460px) { - .trigger .compactIcon { - display: block; - } - - .trigger .textModeActivity { - display: none; - } - - .trigger .count { - display: none; - } - - .trigger { - box-sizing: border-box; - width: 28px; - height: 28px; - padding: 0; - justify-content: center; - color: var(--dsw-alias-label-secondary); - } - - .trigger .activitySlot, - .trigger .activitySlot > svg { - width: 15px; - height: 15px; - } - - .trigger:focus-visible { - color: var(--dsw-alias-label-secondary); - } - - .trigger:active { - background: var(--dsw-alias-interactive-bg-active); - } - - @media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - background: var(--dsw-alias-interactive-bg-hover); - } - } -} - .menu { position: fixed; z-index: 100; @@ -193,47 +120,112 @@ } } -.sectionHeader { - display: flex; - align-items: flex-start; - gap: 7px; - padding: 4px 7px 8px; -} - -.sectionIcon { - display: grid; - flex: none; - place-items: center; - width: 14px; - height: 24px; - color: var(--dsw-alias-label-tertiary); -} - -.sectionTitle { - flex: none; - margin: 0; - color: var(--dsw-alias-label-primary); - font-size: 13px; - font-weight: 500; - line-height: 24px; -} - +/* Progress beside the Session panel section title, one line that clips before the title does. */ .sectionProgress { - margin-inline-start: 4px; - flex: 1 1 auto; min-width: 0; - padding-top: 2px; + overflow: hidden; color: var(--dsw-alias-label-tertiary); - font-size: 13px; - line-height: 20px; - overflow-wrap: anywhere; + font: var(--dsw-font-xxs-12); + font-variant-numeric: tabular-nums; + text-overflow: ellipsis; + white-space: nowrap; } -.sectionEmpty { - margin: 0; - padding: 0 7px 8px 28px; +/* The panel toggle sizes and places this dot; it names the state for assistive technology. */ +.runningIndicator { + background: var(--dsw-alias-state-business-primary); +} + +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +/* The Session panel section supplies the inset and scrolling. Rows share the + panel's columns: the status glyph's center 14px from the row start, text at + 30px, and the chevron's center 14px from the row end. */ +.sectionBody { + display: flex; + flex-direction: column; + min-width: 0; +} + +/* One 28px line per row: the name clips, and its owner, state, and tokens show in the row's hover card. */ +.sectionBody .row { + gap: 8px; + min-height: 28px; + padding: 4px 6px; +} + +.sectionBody .clickarea { + gap: 8px; + border-radius: var(--dsw-radius-sm); +} + +.sectionBody .rowActivitySlot { + width: 16px; + height: 20px; +} + +.sectionBody .disclosure, +.sectionBody .disclosureSpace { + width: 16px; + height: 20px; +} + +.sectionBody .label { + overflow: hidden; + line-height: 20px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sectionBody .duration { + flex: none; color: var(--dsw-alias-label-tertiary); font-size: 12px; + font-variant-numeric: tabular-nums; + line-height: 20px; + white-space: nowrap; +} + +/* The tree's spine sits on the status column's center, and leaves a parent row + just below its 6px dot. Each row sits in its hover card's anchor wrapper. */ +.sectionBody .children { + --branch-anchor-y: 14px; + margin-left: 14px; +} + +.sectionBody .children::before { + top: -10px; + height: 10px; +} + +.sectionBody .children > .node > :first-child > .row::before { + content: ''; + position: absolute; + top: calc(var(--branch-anchor-y) - 0.25px); + left: -3px; + width: 9px; + border-top: 0.5px solid var(--dsw-alias-border-l3); +} + +.sectionBody .children > .node > :first-child > .row:has(> .disclosureSpace)::before { + width: 33px; +} + +/* In the panel's columns the arrow's 24px target centers on the trailing column + and overhangs the 20px line, so the row keeps its 28px. */ +.sectionBody .sidebarButton, +.sectionBody .sidebarSpace { + align-self: center; + width: 24px; + height: 24px; + margin: -2px -4px; } .node { @@ -390,7 +382,6 @@ grid-row: 2; } -.sidebarButton, .sidebarSpace { box-sizing: border-box; flex: none; @@ -405,26 +396,32 @@ color: var(--dsw-alias-label-primary); } +/* The arrow shares its row's highlight: a 24px target whose glyph darkens + without a fill, in the panel and in the switcher menu alike. In the menu it + keeps the 28px trailing column the current row's check also fills. */ .sidebarButton { + box-sizing: border-box; display: inline-flex; + flex: none; align-items: center; justify-content: center; - padding: 6px; + width: 24px; + height: 24px; + margin: 6px 2px; + padding: 0; border: 0; - border-radius: var(--dsw-radius-sm); + border-radius: var(--dsw-radius-xs); background: transparent; color: var(--dsw-alias-label-tertiary); cursor: pointer; } .sidebarButton:focus-visible { - background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } @media (hover: hover) { .sidebarButton:hover { - background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } } diff --git a/packages/client/ui-subagent/src/client/SubagentCatalog.tsx b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx new file mode 100644 index 0000000000..ced031b05b --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx @@ -0,0 +1,602 @@ +/** Subagent catalog tree shared by the Session panel section and the breadcrumb switcher. */ +import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +import type { + SessionListState, SessionProjectionMap, SessionProjectionSnapshot, SessionSummary, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + HoverCard, IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconRefreshOutlineRegular, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-token-meter/client' +import css from './SubagentCatalog.module.css' + +/** One Session's direct subagents with their live activity. */ +export type SubagentCatalogSnapshot = Omit & { + state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' + entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] +} + +/** Catalogs of every Session whose projections the Client holds. */ +export type Catalogs = Readonly> + +/** Business actions supplied by the slot registrations. */ +export type SubagentCatalogInjected = { + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + /** Read this catalog and its direct children after explicit activation or retry. */ + prepareCatalog: (parentSessionId: SessionId) => Promise +} + +interface CatalogRowsProps { + parentSessionId: SessionId + currentSessionId: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: Readonly> + expanded: ReadonlySet + level: number + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + toggleBranch: (childSessionId: SessionId) => void + closeCatalog: () => void + panelDetails: CatalogTreeProps['panelDetails'] +} + +/** + * List the focusable rows of a catalog tree in display order. + * @param root - the tree or an element that contains it. + * @returns the rows that accept focus. + */ +export function treeItems(root: HTMLElement): HTMLElement[] { + return Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) +} + +/** Compact token count shared in shape with the conversation stats strip. */ +function formatTokens(value: number, t: TranslateNS): string { + const scaled = (next: number): string => next >= 100 + ? String(Math.round(next)) + : String(Math.round(next * 10) / 10) + if (value < 1_000) return String(value) + if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) + return t('tokens.million', { value: scaled(value / 1_000_000) }) +} + +/** Sum the four disjoint durable provider-usage buckets. */ +function tokenTotal( + usage: SessionProjectionMap['tokenUsage'] | undefined, +): number | undefined { + return usage === undefined + ? undefined + : usage.uncachedInputTokens + usage.outputTokens + + usage.cacheReadTokens + usage.cacheWriteTokens +} + +/** Exact whole-second active-turn duration for one catalog row. */ +function activityDuration( + summary: SessionSummary | undefined, + activity: 'running' | 'inactive', + now: number, +): number | undefined { + if (summary === undefined) return undefined + const timing: SessionProjectionMap['subagentTiming'] | undefined + = summary.projectionValues?.subagentTiming + if (timing === undefined) return undefined + if (timing.active === undefined) return timing.settledMs + const end = activity === 'running' + ? now + : timing.active.through + return timing.settledMs + Math.max(0, end - timing.active.since) +} + +interface DurationParts { + seconds: number + minutes: number + hours: number + days: number + totalMinutes: number + totalHours: number +} + +function splitDuration(ms: number): DurationParts { + const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) + const totalMinutes = Math.floor(totalSeconds / 60) + const totalHours = Math.floor(totalMinutes / 60) + return { + seconds: totalSeconds % 60, + minutes: totalMinutes % 60, + hours: totalHours % 24, + days: Math.floor(totalHours / 24), + totalMinutes, + totalHours, + } +} + +/** Format a duration with decreasing visual precision at larger scales. */ +function formatDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) + if (days >= 365) { + const years = Math.floor(days / 365) + const months = Math.floor((days % 365) / 30) + return months === 0 + ? t('duration.years', { years }) + : t('duration.yearsMonths', { years, months }) + } + if (days >= 30) { + const months = Math.floor(days / 30) + const remainingDays = days % 30 + return remainingDays === 0 + ? t('duration.months', { months }) + : t('duration.monthsDays', { months, days: remainingDays }) + } + if (days > 0) { + return hours === 0 + ? t('duration.days', { days }) + : t('duration.daysHours', { days, hours }) + } + if (totalHours > 0) { + return t('duration.hours', { + hours: totalHours, + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) + } + if (totalMinutes > 0) { + return t('duration.minutes', { + minutes: totalMinutes, + seconds: String(seconds).padStart(2, '0'), + }) + } + return t('duration.seconds', { seconds }) +} + +/** Preserve exact whole seconds for hover and accessible naming. */ +function formatExactDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days } = splitDuration(ms) + return days === 0 + ? formatDuration(ms, t) + : t('duration.exactDays', { + days, + hours: String(hours).padStart(2, '0'), + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) +} + +/** Render catalog loading without inventing child membership. */ +function CatalogLoadingRows({ t }: { t: TranslateNS }) { + return
      {t('loading.label')}
      +} + +/** Only confirmed child membership exposes a branch disclosure. */ +function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { + return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 + && summaries[entry.id]?.formatStatus !== 'migration-required' + && catalogs[entry.id]?.state !== 'migration-required' +} + +/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ +/** + * Name a catalog entry when it has no description. + * @param entry - catalog entry. + * @returns the entry's display name. + */ +export function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { + return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id +} + +/** Only a local child's last closed, normally completed turn receives the completed marker. */ +function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { + return entry.mode !== 'external' && entry.activity === 'inactive' + && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true +} + +/** Count direct catalog members without treating external or other inactive entries as completed. */ +function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + let completed = 0 + let active = 0 + let inactive = 0 + let external = 0 + for (const entry of entries) { + if (entry.mode === 'external') external++ + else if (entry.activity === 'running') active++ + else if (completedEntry(entry, summaries[entry.id])) completed++ + else inactive++ + } + return [ + ...completed > 0 ? [t('progress.completed', { count: completed })] : [], + ...active > 0 ? [t('progress.active', { count: active })] : [], + ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], + ...external > 0 ? [t('progress.external', { count: external })] : [], + ].join('\u2002·\u2002') +} + +/** Render one catalog level and recurse only through explicitly expanded rows. */ +function CatalogRows({ + parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, + openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, panelDetails, t, +}: CatalogRowsProps & { t: TranslateNS }) { + const dense = panelDetails !== undefined + const [now, setNow] = useState(() => Date.now()) + const running = catalog.entries.some(entry => entry.activity === 'running') + useEffect(() => { + if (!running) return + const timer = setInterval(() => { setNow(Date.now()) }, 1_000) + return () => { clearInterval(timer) } + }, [running]) + const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 + const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) + return ( + <> + {catalog.state === 'idle' && catalog.entries.length === 0 && ( +
      {t('load.idle')}
      + )} + {emptyLoading && ( + + )} + {catalog.state === 'error' && ( +
      + {catalog.error?.message ?? t('load.error')} + +
      + )} + {catalog.entries.map((entry) => { + const external = entry.mode === 'external' + const childCatalog = catalogs[entry.id] + const isCurrent = entry.id === currentSessionId + const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' + || childCatalog?.state === 'migration-required' + const canExpand = canExpandCatalog(entry, catalogs, summaries) + const isExpanded = canExpand && expanded.has(entry.id) + const summary = summaries[entry.id] + const description = entry.label || summary?.title + const name = entryName(entry) + const primaryLabel = description || name + const secondaryLabel = description ? name : undefined + const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') + : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') + const completed = completedEntry(entry, summary) + const activity = external ? undefined : entry.activity === 'running' + ? t('activity.running') + : completed + ? t('activity.completed') + : t('activity.inactive') + const secondary = [secondaryLabel, mode, activity] + .filter(value => value !== undefined) + .join(' · ') + const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) + const durationMs = activityDuration( + summary, + entry.activity, + now, + ) + const tokenMetric = totalTokens === undefined + ? undefined + : t('tokens.total', { value: formatTokens(totalTokens, t) }) + const durationMetric = durationMs === undefined + ? undefined + : { + compact: formatDuration(durationMs, t), + exact: formatExactDuration(durationMs, t), + } + const metrics = [tokenMetric, durationMetric?.exact] + .filter(value => value !== undefined) + .join(' · ') + const dotState = entry.activity === 'running' ? 'ongoing' : completed ? 'done' : 'idle' + + const open = (): void => { + if (external) return + openChild({ + parentSessionId, + childSessionId: entry.id, + mode: entry.mode, + }) + closeCatalog() + } + const handleKey = (event: KeyboardEvent): void => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + event.stopPropagation() + open() + } else if ( + (event.key === 'ArrowRight' && canExpand && !isExpanded) + || (event.key === 'ArrowLeft' && isExpanded) + ) { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + } + const toggle = (event: MouseEvent): void => { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + + const row = ( +
      value !== '').join(' ')} + {...canExpand ? { 'aria-expanded': isExpanded } : {}} + className={css.row} + onClick={open} + onKeyDown={handleKey} + > + {!canExpand + ? reserveDisclosure && + : ( + + )} +
      + + + + + {primaryLabel} + {!dense && secondaryLabel !== undefined && ( + {secondaryLabel} + )} + + {dense + ? durationMetric !== undefined && {durationMetric.compact} + : metrics !== '' && ( + + {tokenMetric !== undefined && {tokenMetric}} + {durationMetric !== undefined && ( + {durationMetric.compact} + )} + + )} + {isCurrent + ? ( + + + + ) + : external ? : ( + + + + )} +
      +
      + ) + const details = panelDetails?.({ + title: primaryLabel, + lines: secondaryLabel === undefined ? [] : [t('hover.owner', { name: secondaryLabel })], + status: { state: dotState, label: [activity, mode].filter(value => value !== undefined).join(' · ') }, + facts: [ + ...tokenMetric === undefined ? [] : [{ kind: 'tokens' as const, label: tokenMetric }], + ...durationMetric === undefined ? [] : [{ kind: 'duration' as const, label: durationMetric.exact }], + ], + }) + + return ( +
      + {dense ? : row} + {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( +
      + {t('load.error')} + +
      + )} + {childCatalog !== undefined && isExpanded && ( +
      + +
      + )} +
      + ) + })} + + ) +} + +/** + * Build every held Session's catalog from its projection and live status. + * @param projections - projection snapshots by Session. + * @param summaries - Session list rows by id. + * @param statuses - live Session statuses. + * @returns catalogs keyed by parent Session. + */ +export function deriveCatalogs( + projections: SessionListState['projectionsBySession'], + summaries: SessionListState['byId'], + statuses: SessionStatusSnapshot, +): Catalogs { + return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { + const projected = snapshot.values.subagentCatalog + const state = snapshot.state === 'idle' + ? projected === undefined ? 'idle' : 'ready' + : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state + return [id, { + state, + error: snapshot.error, + entries: (projected ?? []).map(entry => ({ + ...entry, + activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true + ? 'running' as const : 'inactive' as const, + })), + } satisfies SubagentCatalogSnapshot] + })) +} + +/** + * The direct subagents of `catalog`'s Session plus progress, as one phrase such as "2 of 3 done". + * @param catalog - catalog whose entries are counted. + * @param summaries - Session list rows by id. + * @param t - subagent copy. + * @returns the progress phrase, or an empty string without entries. + */ +export function progressOf(catalog: SubagentCatalogSnapshot, summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + return catalogProgress(catalog.entries, summaries, t) +} + +/** + * Bind catalog preparation as a fire-and-forget level read; a rejection is + * logged, and the next activation or retry prepares the level again. + * @param prepareCatalog - the injected catalog action. + * @returns a callback that prepares one level. + */ +export function levelPreparer(prepareCatalog: SubagentCatalogInjected['prepareCatalog']): (sessionId: SessionId) => void { + return (sessionId) => { + void prepareCatalog(sessionId).catch((error: unknown) => { + console.error('[ui-subagent] catalog discovery failed:', error) + }) + } +} + +/** Props of one subagent tree. */ +export interface CatalogTreeProps { + /** Session whose direct catalog roots the tree. */ + rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId?: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: CatalogRowsProps['summaries'] + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + /** Read a level's catalog and its direct children; the tree calls it on branch expansion and retry. */ + prepareLevel: (parentSessionId: SessionId) => void + /** Called after a row opened a Session, so a surrounding popover or overlay can close. */ + onOpened: () => void + /** Focus the first row on mount, as a keyboard-opened popover does. */ + focusFirst?: boolean + /** + * Renders the Session panel's row details. With it the tree lists one-line + * rows, as the Session panel does, and each row shows its name, owner, + * state, and measures in a hover card. + */ + panelDetails?: ((details: PanelDetailsProps) => ReactNode) | undefined + t: TranslateNS +} + +/** + * Render a subagent tree with expandable branches and roving arrow-key focus. + * A row offers expansion only after its own catalog has entries; expanding it + * prepares that level, and collapsing a branch also collapses its descendants. + * @param props - catalog data, actions, and copy. + * @returns the tree. + */ +export function CatalogTree({ + rootSessionId, currentSessionId, catalog, catalogs, summaries, + openChild, openChildAside, prepareLevel, onOpened, focusFirst = false, panelDetails, t, +}: CatalogTreeProps) { + const [expanded, setExpanded] = useState>(() => new Set()) + const treeRef = useRef(null) + useEffect(() => { + // Effects run after commit, when the tree element is attached. + if (focusFirst) treeItems(treeRef.current as HTMLDivElement)[0]?.focus() + }, [focusFirst]) + + const closeBranch = (root: SessionId): void => { + const closing = new Set() + const visit = (parentSessionId: SessionId): void => { + if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return + closing.add(parentSessionId) + for (const entry of catalogs[parentSessionId]?.entries ?? []) visit(entry.id) + } + visit(root) + setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) + } + + const toggleBranch = (childSessionId: SessionId): void => { + if (expanded.has(childSessionId)) { + closeBranch(childSessionId) + return + } + setExpanded(current => new Set(current).add(childSessionId)) + prepareLevel(childSessionId) + } + + const navigate = (event: KeyboardEvent): void => { + const items = treeItems(event.currentTarget) + const index = items.indexOf(document.activeElement as HTMLElement) + const focusAt = (next: number): void => { items[(next + items.length) % items.length]?.focus() } + if (items.length === 0) return + if (event.key === 'Home') focusAt(0) + else if (event.key === 'End') focusAt(items.length - 1) + else if (event.key === 'ArrowDown') focusAt(index + 1) + else if (event.key === 'ArrowUp') focusAt(index < 0 ? items.length - 1 : index - 1) + else return + event.preventDefault() + } + + return ( +
      + +
      + ) +} diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index 8cbb5be217..aff8538a83 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -1,182 +1,22 @@ -import { useMemo, useEffect, useId, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +/** Breadcrumb switcher for subagent Sessions: the current title opens its siblings' tree. */ +import { useMemo, useEffect, useId, useRef, useState } from 'react' import { createPortal } from 'react-dom' -import { - type SessionProjectionMap, type SessionSummary, - type SessionProjectionSnapshot, -} from '@deepseek-ai/dsh-api-session-controller/client' -import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { - IconChevronRightOutlineRegular, IconRefreshOutlineRegular, IconUsersOutlineRegular, - IconCheckOutlineRegular, MenuSurface, StateDot, Tooltip, -} from '@deepseek-ai/dsh-client-ui-primitives' -import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { MenuSurface } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import { NS } from './locales.ts' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import type {} from '@deepseek-ai/dsh-token-meter/client' -import type {} from '@deepseek-ai/dsh-agent-team/client' -import type {} from './slots.ts' -import css from './SubagentHeaderLineage.module.css' +import { + CatalogTree, deriveCatalogs, entryName, levelPreparer, treeItems, type SubagentCatalogInjected, type SubagentCatalogSnapshot, +} from './SubagentCatalog.tsx' +import css from './SubagentCatalog.module.css' -type SubagentCatalogSnapshot = Omit & { - state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' - entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] -} -type Catalogs = Readonly> - -/** Business actions supplied by the slot registration. */ -export type SubagentCatalogInjected = { - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - /** Read this catalog and its direct children after explicit activation or retry. */ - prepareCatalog: (parentSessionId: SessionId) => Promise -} - -/** Root catalog actions and availability of its optional footer. */ -export type SubagentCatalogActionInjected = SubagentCatalogInjected & { - hooks: { - /** Whether the catalog footer currently has a registered contributor. */ - footerAvailable: HostObservable - } -} +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' /** Full props for the session-header lineage renderer. */ export type SubagentHeaderLineageProps = PropsRuntime<'conversation.session.header.lineage'> & InjectFace & PropsLocale -interface CatalogRowsProps { - parentSessionId: SessionId - currentSessionId: SessionId | undefined - catalog: SubagentCatalogSnapshot - catalogs: Catalogs - summaries: Readonly> - expanded: ReadonlySet - level: number - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - toggleBranch: (childSessionId: SessionId) => void - closeCatalog: () => void -} - -function treeItems(root: HTMLDivElement | null): HTMLElement[] { - return root === null - ? [] - : Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) -} - -/** Compact token count shared in shape with the conversation stats strip. */ -function formatTokens(value: number, t: TranslateNS): string { - const scaled = (next: number): string => next >= 100 - ? String(Math.round(next)) - : String(Math.round(next * 10) / 10) - if (value < 1_000) return String(value) - if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) - return t('tokens.million', { value: scaled(value / 1_000_000) }) -} - -/** Sum the four disjoint durable provider-usage buckets. */ -function tokenTotal( - usage: SessionProjectionMap['tokenUsage'] | undefined, -): number | undefined { - return usage === undefined - ? undefined - : usage.uncachedInputTokens + usage.outputTokens - + usage.cacheReadTokens + usage.cacheWriteTokens -} - -/** Exact whole-second active-turn duration for one catalog row. */ -function activityDuration( - summary: SessionSummary | undefined, - activity: 'running' | 'inactive', - now: number, -): number | undefined { - if (summary === undefined) return undefined - const timing: SessionProjectionMap['subagentTiming'] | undefined - = summary.projectionValues?.subagentTiming - if (timing === undefined) return undefined - if (timing.active === undefined) return timing.settledMs - const end = activity === 'running' - ? now - : timing.active.through - return timing.settledMs + Math.max(0, end - timing.active.since) -} - -interface DurationParts { - seconds: number - minutes: number - hours: number - days: number - totalMinutes: number - totalHours: number -} - -function splitDuration(ms: number): DurationParts { - const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) - const totalMinutes = Math.floor(totalSeconds / 60) - const totalHours = Math.floor(totalMinutes / 60) - return { - seconds: totalSeconds % 60, - minutes: totalMinutes % 60, - hours: totalHours % 24, - days: Math.floor(totalHours / 24), - totalMinutes, - totalHours, - } -} - -/** Format a duration with decreasing visual precision at larger scales. */ -function formatDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) - if (days >= 365) { - const years = Math.floor(days / 365) - const months = Math.floor((days % 365) / 30) - return months === 0 - ? t('duration.years', { years }) - : t('duration.yearsMonths', { years, months }) - } - if (days >= 30) { - const months = Math.floor(days / 30) - const remainingDays = days % 30 - return remainingDays === 0 - ? t('duration.months', { months }) - : t('duration.monthsDays', { months, days: remainingDays }) - } - if (days > 0) { - return hours === 0 - ? t('duration.days', { days }) - : t('duration.daysHours', { days, hours }) - } - if (totalHours > 0) { - return t('duration.hours', { - hours: totalHours, - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) - } - if (totalMinutes > 0) { - return t('duration.minutes', { - minutes: totalMinutes, - seconds: String(seconds).padStart(2, '0'), - }) - } - return t('duration.seconds', { seconds }) -} - -/** Preserve exact whole seconds for hover and accessible naming. */ -function formatExactDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days } = splitDuration(ms) - return days === 0 - ? formatDuration(ms, t) - : t('duration.exactDays', { - days, - hours: String(hours).padStart(2, '0'), - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) -} - function SubagentSwitcherIcon() { return ( }) { - return
      {t('loading.label')}
      -} -/** Only confirmed child membership exposes a branch disclosure. */ -function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { - return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 - && summaries[entry.id]?.formatStatus !== 'migration-required' - && catalogs[entry.id]?.state !== 'migration-required' -} - -/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ -function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { - return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id -} - -/** Only a local child's last closed, normally completed turn receives the completed marker. */ -function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { - return entry.mode !== 'external' && entry.activity === 'inactive' - && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true -} - -/** Count direct catalog members without treating external or other inactive entries as completed. */ -function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { - let completed = 0 - let active = 0 - let inactive = 0 - let external = 0 - for (const entry of entries) { - if (entry.mode === 'external') external++ - else if (entry.activity === 'running') active++ - else if (completedEntry(entry, summaries[entry.id])) completed++ - else inactive++ - } - return [ - ...completed > 0 ? [t('progress.completed', { count: completed })] : [], - ...active > 0 ? [t('progress.active', { count: active })] : [], - ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], - ...external > 0 ? [t('progress.external', { count: external })] : [], - ].join('\u2002·\u2002') -} - -/** Render one catalog level and recurse only through explicitly expanded rows. */ -function CatalogRows({ - parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, - openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, t, -}: CatalogRowsProps & { t: TranslateNS }) { - const [now, setNow] = useState(() => Date.now()) - const running = catalog.entries.some(entry => entry.activity === 'running') - useEffect(() => { - if (!running) return - const timer = setInterval(() => { setNow(Date.now()) }, 1_000) - return () => { clearInterval(timer) } - }, [running]) - const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 - const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) - return ( - <> - {catalog.state === 'idle' && catalog.entries.length === 0 && ( -
      {t('load.idle')}
      - )} - {emptyLoading && ( - - )} - {catalog.state === 'error' && ( -
      - {catalog.error?.message ?? t('load.error')} - -
      - )} - {catalog.entries.map((entry) => { - const external = entry.mode === 'external' - const childCatalog = catalogs[entry.id] - const isCurrent = entry.id === currentSessionId - const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' - || childCatalog?.state === 'migration-required' - const canExpand = canExpandCatalog(entry, catalogs, summaries) - const isExpanded = canExpand && expanded.has(entry.id) - const summary = summaries[entry.id] - const description = entry.label || summary?.title - const name = entryName(entry) - const primaryLabel = description || name - const secondaryLabel = description ? name : undefined - const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') - : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') - const completed = completedEntry(entry, summary) - const activity = external ? undefined : entry.activity === 'running' - ? t('activity.running') - : completed - ? t('activity.completed') - : t('activity.inactive') - const secondary = [secondaryLabel, mode, activity] - .filter(value => value !== undefined) - .join(' · ') - const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) - const durationMs = activityDuration( - summary, - entry.activity, - now, - ) - const tokenMetric = totalTokens === undefined - ? undefined - : t('tokens.total', { value: formatTokens(totalTokens, t) }) - const durationMetric = durationMs === undefined - ? undefined - : { - compact: formatDuration(durationMs, t), - exact: formatExactDuration(durationMs, t), - } - const metrics = [tokenMetric, durationMetric?.exact] - .filter(value => value !== undefined) - .join(' · ') - - const open = (): void => { - if (external) return - openChild({ - parentSessionId, - childSessionId: entry.id, - mode: entry.mode, - }) - closeCatalog() - } - const handleKey = (event: KeyboardEvent): void => { - if (event.key === 'Enter' || event.key === ' ') { - event.preventDefault() - event.stopPropagation() - open() - } else if ( - (event.key === 'ArrowRight' && canExpand && !isExpanded) - || (event.key === 'ArrowLeft' && isExpanded) - ) { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - } - const toggle = (event: MouseEvent): void => { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - - return ( -
      -
      value !== '').join(' ')} - {...canExpand ? { 'aria-expanded': isExpanded } : {}} - className={css.row} - onClick={open} - onKeyDown={handleKey} - > - {!canExpand - ? reserveDisclosure && - : ( - - )} -
      - - - - - {primaryLabel} - {secondaryLabel !== undefined && ( - {secondaryLabel} - )} - - {metrics !== '' && ( - - {tokenMetric !== undefined && {tokenMetric}} - {durationMetric !== undefined && ( - - {durationMetric.compact} - - )} - - )} - {isCurrent - ? ( - - - - ) - : external ? : ( - - - - )} -
      -
      - {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( -
      - {t('load.error')} - -
      - )} - {childCatalog !== undefined && isExpanded && ( -
      - -
      - )} -
      - ) - })} - - ) -} - -interface CatalogDropdownSharedProps extends InjectFace { - /** Session whose direct catalog roots the tree. */ +interface SwitcherProps extends InjectFace { + /** Parent Session whose direct catalog roots the tree. */ rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId: SessionId + /** Visible title included in the switcher's hover target. */ + displayTitle: string + /** Optional ancestor navigation when the combined title is clicked. */ + openTitle?: () => void useSessions: SubagentHeaderLineageProps['useSessions'] useSessionStatus: SubagentHeaderLineageProps['useSessionStatus'] t: TranslateNS - /** Section labels are useful only beside a visible shared-task list. */ - hasSharedTasks?: boolean - /** Retain an empty catalog's entry for shared tasks or a task-board error. */ - hasBoardContent?: boolean - renderFooter?: () => ReactNode } -type CatalogDropdownProps = CatalogDropdownSharedProps & ( - | { - /** Descendant-count control. */ - variant: 'count' - currentSessionId?: never - displayTitle?: never - openTitle?: never - } - | { - /** Current-title sibling switcher. */ - variant: 'switcher' - /** Selected descendant highlighted in the catalog. */ - currentSessionId: SessionId - /** Visible title included in the switcher's hover target. */ - displayTitle: string - /** Optional ancestor navigation when the combined title is clicked. */ - openTitle?: () => void - } -) - -/** One trigger-plus-tree dropdown over the catalog rooted at `rootSessionId`. */ -function CatalogDropdown(props: CatalogDropdownProps) { - const { - rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, hasSharedTasks = false, - } = props - const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined +/** + * Title-and-chevron dropdown over the parent's subagent tree. Hover opens it + * after 150ms and leaving both surfaces closes it after 120ms; a click pins it + * until an outside press or Escape. With `openTitle`, a click navigates to the + * ancestor instead. Hovering reads nothing; a pinning click or ArrowDown + * prepares the parent's level. + * @param props - tree root, current Session, title, Session hooks, actions, and copy. + * @returns the switcher. + */ +function Switcher({ + rootSessionId, currentSessionId, displayTitle, openTitle, + useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, +}: SwitcherProps) { const projections = useSessions(state => state.projectionsBySession) const summaries = useSessions(state => state.byId) const statuses = useSessionStatus(value => value) - const catalogs = useMemo(() => { - return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { - const projected = snapshot.values.subagentCatalog - const state = snapshot.state === 'idle' - ? projected === undefined ? 'idle' : 'ready' - : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state - return [id, { - state, - error: snapshot.error, - entries: (projected ?? []).map(entry => ({ - ...entry, - activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true - ? 'running' as const : 'inactive' as const, - })), - } satisfies SubagentCatalogSnapshot] - })) - }, [projections, summaries, statuses]) - const catalog = catalogs[rootSessionId] - const prepareLevel = (sessionId: SessionId): void => { - void prepareCatalog(sessionId).catch((error: unknown) => { - console.error('[ui-subagent] catalog discovery failed:', error) - }) - } - const [open, setOpen] = useState(false) - const [expanded, setExpanded] = useState>(() => new Set()) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + const catalog: SubagentCatalogSnapshot = catalogs[rootSessionId] ?? { entries: [], state: 'idle', error: null } + const prepareLevel = levelPreparer(prepareCatalog) + const [open, setOpen] = useState<'closed' | 'hover' | 'pinned' | 'keyboard'>('closed') const rootRef = useRef(null) const triggerRef = useRef(null) - const countRef = useRef(null) - const activityId = useId() const menuRef = useRef(null) - const anchorName = `--dsh-subagents-${activityId.replaceAll(':', '')}` - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - // A click-opened (pinned) menu ignores hover-out; only explicit dismissal closes it. - const pinnedRef = useRef(false) - const currentEntry = currentSessionId === undefined - ? undefined - : catalog?.entries.find(entry => entry.id === currentSessionId) - const switcherDisplayTitle = currentEntry !== undefined - ? currentEntry.label || entryName(currentEntry) - : displayTitle - const directChildren = catalog?.entries ?? [] - const directCount = directChildren.length - const runningCount = directChildren.filter(entry => entry.activity === 'running').length - const progress = catalogProgress(directChildren, summaries, t) - const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other' - const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other' - const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent - ? { entries: [], state: 'idle', error: null } - : undefined) + const anchorName = `--dsh-subagents-${useId().replaceAll(':', '')}` + const hoverTimer = useRef | undefined>(undefined) + const currentEntry = catalog.entries.find(entry => entry.id === currentSessionId) + const title = currentEntry !== undefined ? currentEntry.label || entryName(currentEntry) : displayTitle + const shown = open !== 'closed' - const cancelHoverClose = (): void => { - if (hoverCloseTimer.current === undefined) return - clearTimeout(hoverCloseTimer.current) - hoverCloseTimer.current = undefined + const cancelHover = (): void => { + clearTimeout(hoverTimer.current) + hoverTimer.current = undefined } - - const cancelHoverOpen = (): void => { - if (hoverOpenTimer.current === undefined) return - clearTimeout(hoverOpenTimer.current) - hoverOpenTimer.current = undefined - } - - const changeOpen = (next: boolean, restoreFocus = false): void => { - cancelHoverOpen() - cancelHoverClose() - if (next) { - const trigger = triggerRef.current - /* v8 ignore next -- a queued callback can outlive the trigger */ - if (trigger === null) return - setOpen(true) - } - else { - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - } + const close = (restoreFocus = false): void => { + cancelHover() + setOpen('closed') if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } - // CSS owns the header-width breakpoint; interaction reads its result only when scheduling hover. - const allowsHoverOpen = (): boolean => variant === 'switcher' - || (countRef.current !== null && getComputedStyle(countRef.current).display !== 'none') - - const scheduleHoverOpen = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (allowsHoverOpen()) changeOpen(true) - }, 150) - } - - const scheduleHoverClose = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (pinnedRef.current) return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - changeOpen(false) - }, 120) - } - - const closeBranch = (root: SessionId): void => { - const closing = new Set() - const visit = (parentSessionId: SessionId): void => { - if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return - closing.add(parentSessionId) - const branch = catalogs[parentSessionId] - for (const entry of branch?.entries ?? []) { - visit(entry.id) - } - } - visit(root) - setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) - } - - const toggleBranch = (childSessionId: SessionId): void => { - if (expanded.has(childSessionId)) { - closeBranch(childSessionId) - return - } - setExpanded(current => new Set(current).add(childSessionId)) - prepareLevel(childSessionId) - } - useEffect(() => { - if (!open) return + if (!shown) return const closeOutside = (event: PointerEvent): void => { - if ( - event.target instanceof Node - && !rootRef.current?.contains(event.target) - && !menuRef.current?.contains(event.target) - ) { - changeOpen(false) - } + if (event.target instanceof Node && !rootRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close() } - document.addEventListener('pointerdown', closeOutside) const dismiss = (event: globalThis.KeyboardEvent): void => { if (event.key !== 'Escape') return event.preventDefault() - changeOpen(false, menuRef.current?.contains(document.activeElement) === true) + close(menuRef.current?.contains(document.activeElement) === true) } + document.addEventListener('pointerdown', closeOutside) document.addEventListener('keydown', dismiss) return () => { document.removeEventListener('pointerdown', closeOutside) document.removeEventListener('keydown', dismiss) } - }, [open]) + }, [shown]) + useEffect(() => cancelHover, []) - useEffect(() => () => { - cancelHoverOpen() - cancelHoverClose() - }, []) - - const visible = presentedCatalog !== undefined - && (variant === 'switcher' - || props.hasBoardContent || presentedCatalog.state === 'error' - || presentedCatalog.entries.length > 0) - useEffect(() => { - if (visible) return - cancelHoverOpen() - cancelHoverClose() - if (!open) return - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - }, [visible, open]) - - if (!visible) return null - - const focusAt = (index: number): void => { - const items = treeItems(menuRef.current) - if (items.length === 0) return - items[(index + items.length) % items.length]?.focus() + const hoverIn = (pointerType: string): void => { + if (pointerType === 'touch') return + cancelHover() + if (shown) return + hoverTimer.current = setTimeout(() => { setOpen('hover') }, 150) } - - const navigate = (event: KeyboardEvent): void => { - if (event.target instanceof Element - && event.target !== triggerRef.current && event.target !== menuRef.current - && event.target.closest('[role="tree"]') === null) return - const items = treeItems(menuRef.current) - const index = items.indexOf(document.activeElement as HTMLElement) - if (event.key === 'Home') { - event.preventDefault() - focusAt(0) - } else if (event.key === 'End') { - event.preventDefault() - focusAt(items.length - 1) - } else if (event.key === 'ArrowDown') { - event.preventDefault() - focusAt(index + 1) - } else if (event.key === 'ArrowUp') { - event.preventDefault() - focusAt(index < 0 ? items.length - 1 : index - 1) - } + const hoverOut = (): void => { + cancelHover() + if (open !== 'hover') return + hoverTimer.current = setTimeout(() => { setOpen('closed') }, 120) } return ( -
      - + - - {variant === 'count' && runningCount > 0 && ( - - )} - {open && createPortal(( + {title} + + + {shown && createPortal(( { - if (event.pointerType !== 'touch') cancelHoverClose() + onKeyDown={(event) => { + // A pinned menu takes focus itself; the tree handles keys once a row has focus. + if (event.target !== event.currentTarget) return + const items = treeItems(event.currentTarget) + const row = event.key === 'ArrowDown' || event.key === 'Home' ? items[0] + : event.key === 'ArrowUp' || event.key === 'End' ? items.at(-1) : undefined + if (row === undefined) return + event.preventDefault() + row.focus() }} - onPointerLeave={scheduleHoverClose} + onPointerEnter={(event) => { if (event.pointerType !== 'touch') cancelHover() }} + onPointerLeave={hoverOut} >
      - {hasSharedTasks && ( -
      - -

      {t('section.title')}

      - {progress && {progress}} -
      - )} - {hasSharedTasks && presentedCatalog.state === 'ready' && directCount === 0 && ( -

      {t('section.empty')}

      - )} -
      - { changeOpen(false) }} - t={t} - /> -
      - {props.renderFooter?.()} + { close() }} + focusFirst={open === 'keyboard'} + t={t} + />
      ), document.body)} @@ -829,56 +206,9 @@ function CatalogDropdown(props: CatalogDropdownProps) { ) } -/** Full props for the root-session catalog entry in the header actions band. */ -export type SubagentCatalogActionProps = - PropsRuntime<'conversation.session.header.actions'> & InjectFace & PropsLocale - & Omit, 'SessionProvider'> - /** - * Session-header catalog action for root sessions: the descendant count and - * its dropdown after the preset label in the header actions band. Child sessions render nothing - * here — their breadcrumb switcher in the lineage slot owns the same - * navigation. - * @param props - Session standard props plus the catalog actions and translator. - * @returns The count dropdown, or null on a child session. - */ -export function SubagentCatalogAction(props: SubagentCatalogActionProps) { - const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) - const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') - if (addressedChild || listedChild) return null - return -} - -/** Bind task-board visibility only in root conversations. */ -function RootCatalogAction({ - sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable, - openChild, openChildAside, refreshProjection, prepareCatalog, t, renderSlot, -}: SubagentCatalogActionProps) { - const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true - && team.tasks.some(task => task.status !== 'deleted')) - const hasTaskFailure = useProjection('agentTeam', team => team?.enabled === true && team.failure !== undefined) - const footerAvailable = useFooterAvailable(value => value) - return ( - renderSlot('conversation.session.header.actions.subagent.footer', {})} - useSessions={useSessions} - useSessionStatus={useSessionStatus} - openChild={openChild} - openChildAside={openChildAside} - refreshProjection={refreshProjection} - prepareCatalog={prepareCatalog} - t={t} - /> - ) -} - -/** - * Render one breadcrumb title together with its subagent navigation. + * Render one breadcrumb title together with its sibling switcher. The + * Session's own subagents are listed by the Session panel section. * @param props - Breadcrumb title, session standard props, and catalog actions. * @returns A title-and-chevron sibling switcher, or nothing on a root session. */ @@ -895,29 +225,21 @@ export function SubagentHeaderLineage({ const summary = state.byId[lineageSessionId] return summary?.origin === 'subagent' ? summary.parentId : undefined }) - const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t } - // Root sessions carry no breadcrumb; their descendant count lives in the - // header actions band (SubagentCatalogAction). if (parentId === undefined) return null return ( - <> - - {openTitle === undefined && ( - - )} - + ) } diff --git a/packages/client/ui-subagent/src/client/SubagentsSection.tsx b/packages/client/ui-subagent/src/client/SubagentsSection.tsx new file mode 100644 index 0000000000..deb1492470 --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentsSection.tsx @@ -0,0 +1,170 @@ +/** Session panel section listing the current Session's subagents. */ +import { useCallback, useMemo } from 'react' +import { HoverCardGroup } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' +import { + CatalogTree, deriveCatalogs, levelPreparer, progressOf, type Catalogs, type SubagentCatalogInjected, type SubagentCatalogSnapshot, +} from './SubagentCatalog.tsx' +import type { createSubagentsSectionStore } from './subagents-store.ts' +import css from './SubagentCatalog.module.css' + +/** Full props of the subagents section. */ +export type SubagentsSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderFactories + & InjectFace + & PropsStore> + & PropsLocale + +/** Rows the list shows before its fold control holds the rest back. */ +const FOLD_LIMIT = 5 + +const NO_ENTRIES: SubagentCatalogSnapshot['entries'] = [] + +/** Full props of the section's progress title control. */ +export type SubagentsProgressProps = + PropsRuntime<'conversation.session.panel.section.actions'> & PropsLocale + +/** Full props of the running dot on the Session panel toggle. */ +export type SubagentsRunningIndicatorProps = + PropsRuntime<'conversation.session.panel.indicator'> & PropsLocale + +function deriveSummaries(state: Parameters[0]>[0]) { + return state.byId +} + +/** + * Read every held Session's catalog from the standard Session hooks. + * @param props - Session list and status hooks. + * @returns catalogs keyed by parent Session, and the Session list rows. + */ +function useCatalogs({ useSessions, useSessionStatus }: Pick): { + readonly catalogs: Catalogs + readonly summaries: ReturnType +} { + const projections = useSessions(state => state.projectionsBySession) + const summaries = useSessions(deriveSummaries) + const statuses = useSessionStatus(value => value) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + return { catalogs, summaries } +} + +/** + * Order the section's rows: running subagents first, the most recently started + * first, then the others, the most recently active first. A running subagent + * sorts by the start of its open turn and another one by its Session's last + * update. A subagent the Client holds neither for sorts by when its parent + * created it: its turn timing is not read yet, or its Session is not in the + * Host list, whose stand-in row carries no update time. Rows that tie keep + * their catalog order. + * @param entries - the Session's direct subagents in catalog order. + * @param summaries - Session list rows by id. + * @returns the entries in display order. + */ +function sectionOrder( + entries: SubagentCatalogSnapshot['entries'], summaries: ReturnType, +): SubagentCatalogSnapshot['entries'] { + return entries + .map((entry) => { + const summary = summaries[entry.id] + const running = entry.activity === 'running' + // A Session is last updated after it is created, so the later of the two is the update time when the Client has one. + const at = running + ? summary?.projectionValues?.subagentTiming?.active?.since ?? entry.createdAt + : Math.max(summary?.updatedAt ?? 0, entry.createdAt) + return { entry, running, at } + }) + .sort((left, right) => Number(right.running) - Number(left.running) || right.at - left.at) + .map(row => row.entry) +} + +/** + * Render the Session's subagent tree, running subagents first and then the + * most recently active ones. The list shows five rows and then a fold control + * that shows the rest, once that holds back two rows or more; the choice is + * kept per Session. The section renders nothing while the Session has no + * subagents and no failed catalog read. Showing it reads nothing: rows offer + * expansion from locally known catalogs, and expanding a branch or retrying a + * failed read prepares that level. Opening a subagent closes the panel's + * overlay. + * @param props - Session hooks, panel owner values, the fold store, catalog actions, and copy. + * @returns the section body, or null with nothing to show. + */ +export function SubagentsSection({ + sessionId, dismissOverlay, useSessions, useSessionStatus, useStore, actions, openChild, openChildAside, prepareCatalog, + renderFactorySlot, t, +}: SubagentsSectionProps) { + const { catalogs, summaries } = useCatalogs({ useSessions, useSessionStatus }) + const catalog = catalogs[sessionId] + const unfolded = useStore(state => state.unfolded) + const prepareLevel = useMemo(() => levelPreparer(prepareCatalog), [prepareCatalog]) + const panelDetails = useCallback( + (details: PanelDetailsProps) => renderFactorySlot('conversation.session.panel.details', details), [renderFactorySlot], + ) + const ordered = useMemo(() => catalog === undefined ? NO_ENTRIES : sectionOrder(catalog.entries, summaries), [catalog, summaries]) + // Folding holds back two rows or more, since the fold control takes a row itself. + const foldable = ordered.length > FOLD_LIMIT + 1 + const shown = useMemo( + () => catalog === undefined ? undefined : { ...catalog, entries: foldable && !unfolded ? ordered.slice(0, FOLD_LIMIT) : ordered }, + [catalog, ordered, foldable, unfolded], + ) + if (shown === undefined || (shown.state !== 'error' && ordered.length === 0)) return null + const label = unfolded ? t('list.less') : t('list.more', { count: ordered.length - FOLD_LIMIT }) + return ( +
      + {/* Moving between rows swaps their hover cards without another dwell. */} + + + + {foldable && renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded, + label, + name: t('list.foldName', { label }), + onToggle: () => { actions.unfoldedSet(!unfolded) }, + })} +
      + ) +} + +/** + * Render the direct subagents' progress beside the section title. + * @param props - Session hooks and copy. + * @returns the progress phrase, or null without subagents. + */ +export function SubagentsProgress({ sessionId, useSessions, useSessionStatus, t }: SubagentsProgressProps) { + const { catalogs, summaries } = useCatalogs({ useSessions, useSessionStatus }) + const catalog = catalogs[sessionId] + const progress = catalog === undefined ? '' : progressOf(catalog, summaries, t) + if (progress === '') return null + return {progress} +} + +/** + * Show on the panel toggle that direct subagents run while the panel does not + * show them. External tasks do not count, as in the section's progress. + * @param props - Session hooks, whether the panel shows, and copy. + * @returns the dot with its name for assistive technology, or null with nothing to report. + */ +export function SubagentsRunningIndicator({ sessionId, panelShown, useSessions, useSessionStatus, t }: SubagentsRunningIndicatorProps) { + const { catalogs } = useCatalogs({ useSessions, useSessionStatus }) + const running = catalogs[sessionId]?.entries.filter(entry => entry.mode !== 'external' && entry.activity === 'running').length ?? 0 + if (panelShown || running === 0) return null + return ( + + {t('indicator.running', { count: running })} + + ) +} diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index d6fe29b2d8..9ab568f2ba 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -3,7 +3,10 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { SubagentCatalogAction, SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected } from './SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from './SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +import { SubagentsProgress, SubagentsRunningIndicator, SubagentsSection } from './SubagentsSection.tsx' +import { createSubagentsSectionStore } from './subagents-store.ts' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' @@ -12,11 +15,11 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type SubagentKey } from './locales.ts' -export type * from './slots.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { @@ -25,16 +28,17 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { - SubagentCatalogActionProps, SubagentCatalogInjected, SubagentCatalogActionInjected, SubagentHeaderLineageProps, -} from './SubagentHeaderLineage.tsx' +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +export type { SubagentHeaderLineageProps } from './SubagentHeaderLineage.tsx' +export type { SubagentsProgressProps, SubagentsRunningIndicatorProps, SubagentsSectionProps } from './SubagentsSection.tsx' export type { SubagentReadOnlyComposerProps, SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' /** * Required services for subagent presentation and navigation. `uiSession.sessionStatus` provides the - * `useSessionStatus` hook the lineage header renders with, so the plugin unloads and reloads with it. + * `useSessionStatus` hook the lineage header and the Session panel entries render with, so the plugin unloads and + * reloads with it. */ export const inject = ['sessions', 'uiWorkspace', 'slots', 'locale', 'sidebarRight', 'uiSession.sessionStatus'] @@ -48,11 +52,13 @@ function selectReadOnlySubagent(owner: ComposerChainProps): SubagentReadOnlyMatc } /** - * Client plugin body: register the subagent catalog and read-only composer seats. + * Client plugin body: register the breadcrumb switcher, the Session panel + * subagents section, and the read-only composer. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-subagent: dictionaries') + const t = ctx.locale.bind(NS) ctx.inject(['resources', 'sidebarRightTabs'], (scope) => { registerSidebarChat(scope, ctx.locale.bind(NS)) }) @@ -83,10 +89,6 @@ export function apply(ctx: ClientContext): void { void ctx.sessions.refreshProjections(parentSessionId) }, }) - const footerAvailable = { - getSnapshot: () => ctx.slots.entries('conversation.session.header.actions.subagent.footer').length > 0, - subscribe: (listener: () => void) => ctx.slots.subscribe('conversation.session.header.actions.subagent.footer', listener), - } ctx.slots.inject( 'conversation.session.header.lineage', () => ctx.slots.register({ @@ -95,20 +97,30 @@ export function apply(ctx: ClientContext): void { inject: catalogActions, }, SubagentHeaderLineage), ) - ctx.slots.inject( - 'conversation.session.header.actions', - () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'subagent-catalog', - // Between the preset label (-10) and background tasks (20). - order: 10, + ctx.slots.inject('conversation.session.panel.section', function* () { + yield ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'subagents', + // After change requests (100), before shared tasks (250). + order: 200, + label: () => t('section.title'), locale: NS, - inject: (sessionId): SubagentCatalogActionInjected => ({ - ...catalogActions(sessionId), hooks: { footerAvailable }, - }), - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, - }, SubagentCatalogAction), - ) + store: createSubagentsSectionStore(), + inject: catalogActions, + }, SubagentsSection) + yield ctx.slots.register({ + name: 'conversation.session.panel.section.actions', + key: 'subagents', + locale: NS, + }, SubagentsProgress) + }) + ctx.slots.inject('conversation.session.panel.indicator', () => ctx.slots.register({ + name: 'conversation.session.panel.indicator', + id: 'subagents.running', + // Below an attention mark, which paints above running dots. + order: 10, + locale: NS, + }, SubagentsRunningIndicator)) ctx.slots.inject( 'conversation.composer', () => ctx.slots.register({ diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 83754edd6c..0e1c80e59b 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -6,11 +6,14 @@ export const NS = 'subagent' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { 'section.title': '子智能体', - 'section.empty': '暂无子智能体', + 'indicator.running': '{count} 个子智能体运行中', 'progress.completed': '{count} 已完成', 'progress.active': '{count} 进行中', 'progress.inactive': '{count} 未运行', 'progress.external': '{count} 外部任务', + 'list.more': '显示其余 {count} 个', + 'list.less': '收起', + 'list.foldName': '{label}(子智能体)', 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}小时{minutes}分{seconds}秒', @@ -21,10 +24,10 @@ export const zh = { 'duration.years': '约{years}年', 'duration.yearsMonths': '约{years}年{months}个月', 'duration.exactDays': '{days}天{hours}小时{minutes}分{seconds}秒', - 'duration.exactTitle': '总活跃耗时:{duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': '负责人:{name}', 'loading.label': '正在加载子智能体…', 'load.idle': '尚未加载子智能体', 'load.error': '无法加载子智能体', @@ -39,10 +42,6 @@ export const zh = { 'activity.inactive': '当前未运行', 'branch.collapse': '收起 {label} 的下级子智能体', 'branch.expand': '展开 {label} 的下级子智能体', - 'count.total.one': '{count} 个子智能体', - 'count.total.other': '{count} 个子智能体', - 'count.running.one': '{count} 个子智能体,正在运行', - 'count.running.other': '{count} 个子智能体,正在运行', 'switcher.aria': '切换子智能体:{title}', 'tree.aria': '子智能体会话', 'open.sidebar': '在侧边栏打开', @@ -57,11 +56,14 @@ export const zh = { /** English dictionary, key-identical to the Chinese source of truth. */ export const en: Record = { 'section.title': 'Subagents', - 'section.empty': 'No subagents', + 'indicator.running': 'Subagents running: {count}', 'progress.completed': '{count} completed', 'progress.active': '{count} in progress', 'progress.inactive': '{count} not running', 'progress.external': '{count} external', + 'list.more': 'Show {count} more', + 'list.less': 'Show less', + 'list.foldName': '{label} (subagents)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -72,10 +74,10 @@ export const en: Record = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Total active duration: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': 'Owner: {name}', 'loading.label': 'Loading subagents…', 'load.idle': 'Subagents not loaded', 'load.error': 'Unable to load subagents', @@ -90,10 +92,6 @@ export const en: Record = { 'activity.inactive': 'not running', 'branch.collapse': 'Collapse {label} descendants', 'branch.expand': 'Expand {label} descendants', - 'count.total.one': '{count} subagent', - 'count.total.other': '{count} subagents', - 'count.running.one': '{count} subagent running', - 'count.running.other': '{count} subagents running', 'switcher.aria': 'Switch subagent: {title}', 'tree.aria': 'Subagent sessions', 'open.sidebar': 'Open in sidebar', @@ -111,11 +109,14 @@ export type SubagentKey = keyof typeof zh /** Japanese copy, checked against the English keys. */ export const ja = { 'section.title': 'サブエージェント', - 'section.empty': 'サブエージェントはありません', + 'indicator.running': '実行中のサブエージェント: {count}', 'progress.completed': '{count}件完了', 'progress.active': '{count}件進行中', 'progress.inactive': '{count}件停止中', 'progress.external': '{count}件外部タスク', + 'list.more': '残り{count}件を表示', + 'list.less': '折りたたむ', + 'list.foldName': '{label}(サブエージェント)', 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}時間{minutes}分{seconds}秒', @@ -126,10 +127,10 @@ export const ja = { 'duration.years': '約{years}年', 'duration.yearsMonths': '約{years}年{months}ヶ月', 'duration.exactDays': '{days}日{hours}時間{minutes}分{seconds}秒', - 'duration.exactTitle': '合計アクティブ時間: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': '担当:{name}', 'loading.label': 'サブエージェントを読み込み中…', 'load.idle': 'サブエージェントは未読み込みです', 'load.error': 'サブエージェントを読み込めません', @@ -144,10 +145,6 @@ export const ja = { 'activity.inactive': '停止中', 'branch.collapse': '{label}の子孫を折りたたむ', 'branch.expand': '{label}の子孫を展開', - 'count.total.one': 'サブエージェント{count}件', - 'count.total.other': 'サブエージェント{count}件', - 'count.running.one': '実行中のサブエージェント{count}件', - 'count.running.other': '実行中のサブエージェント{count}件', 'switcher.aria': 'サブエージェントを切り替え: {title}', 'tree.aria': 'サブエージェントセッション', 'open.sidebar': 'サイドバーで開く', @@ -162,11 +159,14 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { 'section.title': 'Subagentes', - 'section.empty': 'No hay subagentes', + 'indicator.running': 'Subagentes en ejecución: {count}', 'progress.completed': '{count} completado', 'progress.active': '{count} en progreso', 'progress.inactive': '{count} sin ejecutar', 'progress.external': '{count} externos', + 'list.more': 'Mostrar {count} más', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (subagentes)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -177,10 +177,10 @@ export const es = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Duración total activa: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': 'Tok {value}', + 'hover.owner': 'Responsable: {name}', 'loading.label': 'Cargando subagentes…', 'load.idle': 'Subagentes sin cargar', 'load.error': 'No se pueden cargar subagentes', @@ -195,10 +195,6 @@ export const es = { 'activity.inactive': 'no corriendo', 'branch.collapse': 'Contraer descendientes de {label}', 'branch.expand': 'Ampliar descendientes de {label}', - 'count.total.one': 'Subagente {count}', - 'count.total.other': 'Subagentes {count}', - 'count.running.one': 'Subagente {count} ejecutándose', - 'count.running.other': 'Subagentes {count} ejecutándose', 'switcher.aria': 'Cambiar subagente: {title}', 'tree.aria': 'Sesiones de subagente', 'open.sidebar': 'Abrir en la barra lateral', @@ -213,11 +209,14 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { 'section.title': 'Sous-agents', - 'section.empty': 'Aucun sous-agent', + 'indicator.running': 'Sous-agents en cours : {count}', 'progress.completed': '{count} terminé', 'progress.active': '{count} en cours', 'progress.inactive': '{count} à l’arrêt', 'progress.external': '{count} externes', + 'list.more': 'Afficher {count} de plus', + 'list.less': 'Afficher moins', + 'list.foldName': '{label} (sous-agents)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -228,10 +227,10 @@ export const fr = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': "Durée totale d'activité : {duration}", 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': 'Jeton {value}', + 'hover.owner': 'Responsable : {name}', 'loading.label': 'Chargement des sous-agents…', 'load.idle': 'Sous-agents non chargés', 'load.error': 'Impossible de charger les sous-agents', @@ -246,10 +245,6 @@ export const fr = { 'activity.inactive': 'ne fonctionne pas', 'branch.collapse': 'Réduire les descendants de {label}', 'branch.expand': 'Développer les descendants de {label}', - 'count.total.one': 'Sous-agent {count}', - 'count.total.other': 'Sous-agents {count}', - 'count.running.one': "Sous-agent {count} en cours d'exécution", - 'count.running.other': "Sous-agents {count} en cours d'exécution", 'switcher.aria': 'Changer de sous-agent : {title}', 'tree.aria': 'Sessions de sous-agents', 'open.sidebar': 'Ouvrir dans la barre latérale', @@ -264,11 +259,14 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { 'section.title': 'Subagenten', - 'section.empty': 'Keine Subagenten', + 'indicator.running': 'Laufende Subagenten: {count}', 'progress.completed': '{count} abgeschlossen', 'progress.active': '{count} in Bearbeitung', 'progress.inactive': '{count} nicht aktiv', 'progress.external': '{count} extern', + 'list.more': '{count} weitere anzeigen', + 'list.less': 'Weniger anzeigen', + 'list.foldName': '{label} (Subagenten)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -279,10 +277,10 @@ export const de = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Gesamte aktive Dauer: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value}-Token', + 'hover.owner': 'Zuständig: {name}', 'loading.label': 'Subagenten werden geladen…', 'load.idle': 'Subagenten nicht geladen', 'load.error': 'Subagenten können nicht geladen werden', @@ -297,10 +295,6 @@ export const de = { 'activity.inactive': 'läuft nicht', 'branch.collapse': '{label}-Nachkommen reduzieren', 'branch.expand': 'Erweitern Sie {label}-Nachkommen', - 'count.total.one': '{count}-Subagent', - 'count.total.other': '{count}-Subagenten', - 'count.running.one': '{count}-Subagent läuft', - 'count.running.other': '{count} Subagenten laufen', 'switcher.aria': 'Subagent wechseln: {title}', 'tree.aria': 'Subagentensitzungen', 'open.sidebar': 'In der Seitenleiste öffnen', @@ -315,11 +309,14 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { 'section.title': 'Субагенты', - 'section.empty': 'Нет субагентов', + 'indicator.running': 'Выполняется субагентов: {count}', 'progress.completed': '{count} завершено', 'progress.active': '{count} в процессе', 'progress.inactive': '{count} не выполняются', 'progress.external': '{count} внешних', + 'list.more': 'Показать ещё {count}', + 'list.less': 'Свернуть', + 'list.foldName': '{label} (субагенты)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -330,10 +327,10 @@ export const ru = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Общая активная продолжительность: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} ток', + 'hover.owner': 'Ответственный: {name}', 'loading.label': 'Загрузка субагентов…', 'load.idle': 'Субагенты не загружены', 'load.error': 'Невозможно загрузить субагенты', @@ -348,10 +345,6 @@ export const ru = { 'activity.inactive': 'не работает', 'branch.collapse': 'Свернуть потомков {label}', 'branch.expand': 'Развернуть потомков {label}', - 'count.total.one': 'Субагент {count}', - 'count.total.other': 'Субагенты {count}', - 'count.running.one': 'Субагент {count} работает', - 'count.running.other': 'Субагенты {count} работают', 'switcher.aria': 'Переключить субагент: {title}', 'tree.aria': 'Сеансы субагента', 'open.sidebar': 'Открыть в боковой панели', @@ -366,11 +359,14 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { 'section.title': 'Subagentes', - 'section.empty': 'Nenhum subagente', + 'indicator.running': 'Subagentes em execução: {count}', 'progress.completed': '{count} concluído', 'progress.active': '{count} em andamento', 'progress.inactive': '{count} sem execução', 'progress.external': '{count} externos', + 'list.more': 'Mostrar mais {count}', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (subagentes)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -381,10 +377,10 @@ export const pt = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}a {months}mês', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Duração total ativa: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} valor', + 'hover.owner': 'Responsável: {name}', 'loading.label': 'Carregando subagentes…', 'load.idle': 'Subagentes não carregados', 'load.error': 'Não foi possível carregar subagentes', @@ -399,10 +395,6 @@ export const pt = { 'activity.inactive': 'não está funcionando', 'branch.collapse': 'Recolher {label} descendentes', 'branch.expand': 'Expandir {label} descendentes', - 'count.total.one': '{count} subagente', - 'count.total.other': '{count} subagentes', - 'count.running.one': '{count} subagente em execução', - 'count.running.other': '{count} subagentes em execução', 'switcher.aria': 'Alternar subagente: {title}', 'tree.aria': 'Sessões de subagente', 'open.sidebar': 'Abrir na barra lateral', diff --git a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx index 6d9c3fcbb5..8461e307ca 100644 --- a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx +++ b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx @@ -4,7 +4,7 @@ import type { ISessions, SessionReference, } from '@deepseek-ai/dsh-api-session-controller/client' import type { ResourceProvider } from '@deepseek-ai/dsh-client-resources/client' -import type { ConversationViewsProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { ConversationViewsProps, WorkspaceSelectedHandler } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { SidebarRightTabDefinition } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { PropsRenderFactories, PropsRenderSlots, PropsRuntime, TranslateNS, @@ -39,7 +39,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Session-scoped Conversation occurrence hosted by one Sidebar chat tab. */ - 'sidebar.chat.conversation': { kind: 'single'; scope: 'session' } + 'sidebar.chat.conversation': { kind: 'single'; scope: 'session'; inject: SidebarChatInjected } } } @@ -117,6 +117,12 @@ function subagentChatResourceProvider(sessions: ISessions): ResourceProvider<'su } } +/** Navigation injected into the child-Session Conversation host. */ +export interface SidebarChatInjected { + /** Open the Workspace's blank Session as the main Session. */ + readonly openWorkspace: WorkspaceSelectedHandler +} + /** Fixed Chat selection used by an embedded Conversation occurrence. */ export function FixedChatConversationView(props: ConversationViewsProps) { return <>{props.renderSlot('conversation.session', { view: 'chat' })} @@ -127,7 +133,7 @@ export type ConversationSlotPanelProps = PropsRuntime<'sidebar.chat.conversation /** Render the shared Conversation content for one explicitly provided child Session. */ export function ConversationSlotPanel({ - sessionId, useSession, useConversation, useSessions, renderFactorySlot, + sessionId, useSession, useConversation, useSessions, renderFactorySlot, openWorkspace, }: ConversationSlotPanelProps) { const session = useSession(value => value) const conversation = useConversation(value => value) @@ -139,7 +145,7 @@ export function ConversationSlotPanel({ const settling = (shellPhase === 'blank' && session.openState === 'loading' && summaryBlank !== true) const hero = shellPhase === 'blank' && (session.openState === 'open' || summaryBlank === true) const phase = settling ? 'settling' : hero ? 'hero' : 'active' - return renderFactorySlot('conversation.content', { variant: 'embedded', phase, hero }, { + return renderFactorySlot('conversation.content', { variant: 'embedded', phase, hero, onWorkspaceSelected: openWorkspace }, { slots: { views: FixedChatConversationView }, }) } @@ -188,10 +194,13 @@ export function registerSidebarChat(ctx: Context, t: TranslateNS): vo : ctx.sessions.list.getSnapshot().byId[child]?.projectionValues?.subagent?.label ?? child }, } satisfies SidebarRightTabDefinition), 'ui-subagent: Sidebar chat type') + const chatInjected: SidebarChatInjected = { + openWorkspace: (workspaceId, adopt) => ctx.uiWorkspace.openWorkspace(workspaceId, adopt), + } ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: SUBAGENT_CHAT_ID, - children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session' } }, + children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session', inject: chatInjected } }, }, SidebarChatTab)), 'ui-subagent: Sidebar chat body') ctx.effect(() => ctx.slots.inject('sidebar.chat.conversation', () => ctx.slots.register({ name: 'sidebar.chat.conversation', diff --git a/packages/client/ui-subagent/src/client/slots.ts b/packages/client/ui-subagent/src/client/slots.ts deleted file mode 100644 index a3e379e62f..0000000000 --- a/packages/client/ui-subagent/src/client/slots.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** Extension position below the root conversation's subagent catalog. */ - -declare module '@deepseek-ai/dsh-client-ui-slots' { - interface SlotMap { - /** Content below the root Session's subagent tree. */ - 'conversation.session.header.actions.subagent.footer': { - kind: 'list' - scope: 'session' - } - } -} - -export {} diff --git a/packages/client/ui-subagent/src/client/subagents-store.ts b/packages/client/ui-subagent/src/client/subagents-store.ts new file mode 100644 index 0000000000..c650efe170 --- /dev/null +++ b/packages/client/ui-subagent/src/client/subagents-store.ts @@ -0,0 +1,38 @@ +/** + * Whether the user unfolded the subagents list of the Session panel. The + * registration declares it as an exclusive store, so each Session keeps its + * own while its scope is retained, across hiding and showing the panel. + */ + +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' + +/** The fold of one Session's subagents list. */ +export interface SubagentsSectionState { + /** Whether the list shows every row instead of holding back the rows past its limit. */ + unfolded: boolean +} + +/** The subagents section store's write set. */ +type SubagentsSectionActions = { + unfoldedSet: (draft: SubagentsSectionState, unfolded: boolean) => void +} + +/** + * Declare the subagents section's store. + * @returns the store handle to declare on the registration. + */ +export function createSubagentsSectionStore(): EngineStoreHandle { + return defineStore({ + init: (): SubagentsSectionState => ({ unfolded: false }), + actions: { + /** + * Record the user's choice to show every row or fold the list again. + * @param d - draft state. + * @param unfolded - whether the list now shows every row. + */ + unfoldedSet: (d, unfolded: boolean) => { + d.unfolded = unfolded + }, + }, + }) +} diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts index 4dae089f5a..dc7ea06f05 100644 --- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts @@ -11,9 +11,10 @@ import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' -import { - SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected, -} from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from '../src/client/SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from '../src/client/SubagentCatalog.tsx' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' +import { en } from '../src/client/locales.ts' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from '../src/client/SubagentReadOnlyComposer.tsx' @@ -66,7 +67,9 @@ async function provideSlotFaces(ctx: Context): Promise { name: 'root', children: { 'conversation.session.header.lineage': { kind: 'single', scope: 'session' }, - 'conversation.session.header.actions': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + 'conversation.session.panel.indicator': { kind: 'list', scope: 'session' }, 'conversation.composer': { kind: 'chain', scope: 'session' }, }, } as never, () => null) @@ -114,14 +117,13 @@ describe('apply', () => { it('keeps the root catalog extension available when optional Sidebar services arrive', async () => { const { ctx } = await fullBench(FAMILY) onTestFinished(() => ctx.fiber.dispose()) - ctx.slots.register({ name: 'conversation.session.header.actions.subagent.footer', id: 'test-content' }, () => null) const registerResource = vi.fn(() => () => {}) const registerTab = vi.fn(() => () => {}) ctx.provide('resources', { register: registerResource } as never) ctx.provide('sidebarRightTabs', { register: registerTab } as never) await vi.waitFor(() => { expect(registerResource).toHaveBeenCalledOnce() }) expect(registerTab).toHaveBeenCalledOnce() - expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1) + expect(ctx.slots.entries('conversation.session.panel.section').map(entry => entry.options.id)).toEqual(['subagents']) }) it('reads direct child catalogs sequentially after reading the parent', async () => { @@ -183,26 +185,17 @@ describe('apply', () => { { method: 'refreshProjections', args: [sid('parent')] }, ]) - // The root-session catalog seat registers in the actions band with the - // same business face, between the preset label (-10) and background - // tasks (20). - const actionEntry = ctx.slots.entries('conversation.session.header.actions') - .find(entry => entry.options.id === 'subagent-catalog')! - expect(actionEntry.options.order).toBe(10) - const actionProps = (actionEntry.inject as (id: SessionId) => SubagentCatalogActionInjected)(sid('parent')) - const source = actionProps.hooks.footerAvailable - const changed = vi.fn() - const unsubscribe = source.subscribe(changed) - expect(source.getSnapshot()).toBe(false) - const remove = ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'test-footer', - }, () => null) - expect(source.getSnapshot()).toBe(true) - await vi.waitFor(() => { expect(changed).toHaveBeenCalledOnce() }) - remove() - expect(source.getSnapshot()).toBe(false) - await vi.waitFor(() => { expect(changed).toHaveBeenCalledTimes(2) }) - unsubscribe() + // The Session panel section registers with the same business face, + // after change requests (100) and before background jobs (300), together + // with its progress control beside the title. + const sectionEntry = ctx.slots.entries('conversation.session.panel.section') + .find(entry => entry.options.id === 'subagents')! + expect(sectionEntry.options.order).toBe(200) + expect(resolveSlotLabel(sectionEntry.options.label)).toBe(en['section.title']) + expect(ctx.slots.entries('conversation.session.panel.section.actions').map(entry => entry.options.key)).toEqual(['subagents']) + expect(ctx.slots.entries('conversation.session.panel.indicator')[0]).toMatchObject({ options: { id: 'subagents.running', order: 10 } }) + const sectionActions = (sectionEntry.inject as (id: SessionId) => SubagentCatalogInjected)(sid('parent')) + expect(Object.keys(sectionActions).sort()).toEqual(['openChild', 'openChildAside', 'prepareCatalog', 'refreshProjection']) const composerEntry = ctx.slots.entries('conversation.composer') .find(entry => entry.component === SubagentReadOnlyComposer)! diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 7ff86bb02c..a13821a1c8 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -2,20 +2,23 @@ import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { allowAllAccess, makeTranslate, RemoteError, sessionSnapshot } from '@deepseek-ai/dsh-client-test-runtime' +import { useState } from 'react' +import { allowAllAccess, bindSnapshotSelector, makeTranslate, RemoteError, sessionSnapshot } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionListState, SessionSummary, SessionSnapshot, } from '@deepseek-ai/dsh-api-session-controller/client' import type { SubagentAddress, SubagentCatalogEntry } from '@deepseek-ai/dsh-subagent/client' -import type { TeamProjection, TeamTaskId, TeamTaskView } from '@deepseek-ai/dsh-agent-team/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import { SubagentHeaderLineage, type SubagentHeaderLineageProps } from '../src/client/SubagentHeaderLineage.tsx' import { - SubagentCatalogAction, SubagentHeaderLineage, - type SubagentCatalogActionProps, type SubagentHeaderLineageProps, -} from '../src/client/SubagentHeaderLineage.tsx' + SubagentsProgress, SubagentsRunningIndicator, SubagentsSection, + type SubagentsProgressProps, type SubagentsRunningIndicatorProps, type SubagentsSectionProps, +} from '../src/client/SubagentsSection.tsx' import { SubagentReadOnlyComposer } from '../src/client/SubagentReadOnlyComposer.tsx' +import { createSubagentsSectionStore } from '../src/client/subagents-store.ts' import { en, zh } from '../src/client/locales.ts' +import type { PanelDetailsProps, PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' afterEach(() => { cleanup() @@ -29,26 +32,21 @@ const CHILD = 'child' as SessionId const GRANDCHILD = 'grandchild' as SessionId const t: SubagentHeaderLineageProps['t'] = makeTranslate(zh) -type HeaderCatalogProps = SubagentHeaderLineageProps - & Pick +/** One Session's section store, as the registration mints it. */ +type SectionStore = ReturnType['create']> + +type HeaderCatalogProps = SubagentHeaderLineageProps & { dismissOverlay?: () => void; store?: SectionStore | undefined } type CatalogFixtureEntry = Entry extends SubagentCatalogEntry ? Omit & { activity: 'running' | 'inactive' } : never type CatalogFixture = { - team?: TeamProjection entries: readonly CatalogFixtureEntry[] state: SessionListState['projectionsBySession'][SessionId]['state'] error: SessionListState['projectionsBySession'][SessionId]['error'] } -const sharedTask: TeamTaskView = { - id: 'shared-task' as TeamTaskId, revision: 1, subject: 'Plan shared work', description: 'Prepare the implementation', - status: 'pending', blockedBy: [], writeScopes: [], ready: true, writeScopeWarnings: [], -} -const sharedTeam: TeamProjection = { enabled: true, tasks: [sharedTask] } - function catalog(over: Partial = {}): CatalogFixture { return { entries: [ @@ -75,44 +73,30 @@ function props( ) { const catalogs = value === undefined ? nested : { [PARENT]: value, ...nested } const statuses: SessionStatusSnapshot = new Map() - const byId: Record = { - ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { - id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, projectionValues: { subagentCatalog: [] }, - }]))), - [CHILD]: { - id: CHILD, - title: '正在扫描项目文件', - displayTitle: 'worker', - running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), - retainedBy: {}, - blank: false, - updatedAt: Date.now(), - projectionValues: { subagentCatalog: [] }, - }, - ...summaries, - } const state = { ids: [CHILD], - byId, - phase: 'ready', - projectionsBySession: { - ...Object.fromEntries(Object.entries(byId).flatMap(([id, entry]) => entry.projectionValues === undefined ? [] : [[id, { - state: 'idle' as const, error: null, values: entry.projectionValues, - }]])), - ...Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { - state: catalog.state, error: catalog.error, - values: { - ...byId[id as SessionId]?.projectionValues, - ...catalog.team === undefined ? {} : { agentTeam: catalog.team }, - subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), - }, - }])), + byId: summaries ?? { + ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { + id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, + }]))), + [CHILD]: { + id: CHILD, + title: '正在扫描项目文件', + displayTitle: 'worker', + running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), + retainedBy: {}, + blank: false, + updatedAt: Date.now(), + }, }, + phase: 'ready', + projectionsBySession: Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { + state: catalog.state, error: catalog.error, + values: { + subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), + }, + }])) , } satisfies SessionListState - for (const [id, entry] of Object.entries(byId)) { - const projection = state.projectionsBySession[id] - if (projection !== undefined) byId[id as SessionId] = { ...entry, projectionValues: projection.values } - } function useSessions(select: (snapshot: SessionListState) => T): T { return select(state) } @@ -149,14 +133,12 @@ function props( ...standard, sessionId: PARENT, useSessions, - useFooterAvailable: (select: (available: boolean) => T): T => select(true), useSessionStatus: (select: (snapshot: SessionStatusSnapshot) => T): T => select(statuses), useSession: (select: (snapshot: SessionSnapshot) => T): T => select(snapshot), openChild: vi.fn(), openChildAside: vi.fn(), refreshProjection: vi.fn(), prepareCatalog: vi.fn<(id: SessionId) => Promise>().mockResolvedValue(), - renderSlot: vi.fn(() => null), lineageSessionId: PARENT, displayTitle: 'Parent title', t, @@ -197,126 +179,74 @@ function enableTooltips(): void { } /** - * Both header seats as the real header composes them: the breadcrumb switcher - * (child sessions, lineage slot) and the actions-band catalog entry (root - * sessions) — exactly one renders per form. The actions seat sees the same - * session the lineage renders. + * Rest the pointer on a Session panel row past the hover card's 500ms dwell and + * read the card's parts in order, then leave it. + * @param row - the row's treeitem. + * @returns the card's lines, or null while no card shows. */ -function HeaderCatalog(props: HeaderCatalogProps) { - const actionProps: SubagentCatalogActionProps = { - ...props, sessionId: props.lineageSessionId, - useProjection: ((_key: 'agentTeam', selector: (value: TeamProjection | undefined) => boolean) => - props.useSessions(state => selector(state.projectionsBySession[props.lineageSessionId]?.values.agentTeam))) as SubagentCatalogActionProps['useProjection'], - } +async function hoverDetailsOf(row: HTMLElement): Promise { + vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' }))) + const anchor = row.parentElement as HTMLElement + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + await act(async () => { await vi.advanceTimersByTimeAsync(500) }) + const card = document.querySelector('[data-session-panel-details]') + const lines = card === null ? null : [...card.children].map(child => child.textContent ?? '') + fireEvent.pointerLeave(anchor, { pointerType: 'mouse' }) + await act(async () => { await vi.advanceTimersByTimeAsync(400) }) + return lines +} + +/** + * The two surfaces as the real page composes them: the breadcrumb switcher + * (child sessions, lineage slot) and the Session panel section listing the + * Session's own subagents. The section sees the same Session the lineage renders. + */ +function HeaderCatalog({ store, ...props }: HeaderCatalogProps) { return ( <> - +
      ) } +/** + * The Session panel's Factories as these suites render them: the fold control as a button with its state, name, and + * label, and a row's details as one element per part in order. ui-session-panel's own suite owns their markup. + */ +function renderPanelFactory(name: string, input: object) { + if (name === 'conversation.session.panel.details') { + const { title, lines = [], status, facts = [] } = input as PanelDetailsProps + return ( +
      + {title !== undefined &&
      {title}
      } + {lines.map(line =>
      {line}
      )} + {status !== undefined &&
      {status.label}
      } + {facts.length > 0 &&
      {facts.map(fact => {fact.label})}
      } +
      + ) + } + const fold = input as PanelFoldProps + return +} + +/** The section with the panel owner values, its Session's store (a fresh one unless given), and the fold control. */ +function Section({ store, dismissOverlay, ...props }: Omit) { + const [own] = useState(() => store ?? createSubagentsSectionStore().create()) + const [useStore] = useState(() => bindSnapshotSelector(own)) + const sectionProps = { + ...props, presentation: 'docked', dismissOverlay: dismissOverlay ?? vi.fn(), useStore, actions: own.actions, renderFactorySlot: renderPanelFactory, + } as SubagentsSectionProps + return +} + describe('SubagentHeaderLineage', () => { - it.each([ - { dictionary: zh, total: '2 个子智能体', running: '1 个子智能体,正在运行' }, - { dictionary: en, total: '2 subagents', running: '1 subagent running' }, - ])('keeps the total accessible name separate from the running description: $total', ({ dictionary, total, running }) => { - const input = props(catalog()) - const view = render() - const trigger = screen.getByRole('button', { name: total }) - expect(trigger.textContent).toBe(total) - expect(document.getElementById(trigger.getAttribute('aria-describedby')!)?.textContent).toBe(running) - view.rerender() - expect(screen.getByRole('button', { name: total }).getAttribute('aria-describedby')).toBeNull() - }) - it('shows a non-collapsible heading with direct-member progress beside shared tasks', () => { - const finished = 'finished' as SessionId - const paused = 'paused' as SessionId - const external = 'external' as SessionId - const entries: CatalogFixture['entries'] = [ - { id: CHILD, mode: 'continuable', label: 'worker', activity: 'running' }, - { id: finished, mode: 'continuable', label: 'finished', activity: 'inactive' }, - { id: paused, mode: 'continuable', label: 'paused', activity: 'inactive' }, - { id: external, mode: 'external', label: 'external', activity: 'running' }, - ] - const summaries: Record = { - [CHILD]: { ...summary(CHILD, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [finished]: { ...summary(finished, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [paused]: { ...summary(paused, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: false } } }, - [external]: { - ...summary(external, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } }, - }, - } - const input = props(catalog({ entries, team: sharedTeam }), { - [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'nested', activity: 'running' }] }), - }, summaries) - const view = render() - fireEvent.click(screen.getByRole('button', { name: '4 个子智能体' })) - const header = view.container.ownerDocument.querySelector('[data-subagent-section-header]')! - expect(within(header).getByRole('heading', { name: '子智能体' })).toBeTruthy() - expect(within(header).queryByRole('button')).toBeNull() - expect(header.textContent).toBe('子智能体1 已完成\u2002·\u20021 进行中\u2002·\u20021 未运行\u2002·\u20021 外部任务') - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(header.textContent).toContain('1 进行中') - expect(header.textContent).not.toContain('2 进行中') - view.rerender() - expect(header.textContent).toBe('Subagents1 completed\u2002·\u20021 in progress\u2002·\u20021 not running\u2002·\u20021 external') - }) - - it('omits zero progress counts from a completed-only catalog header', () => { - const input = props(catalog({ - team: sharedTeam, entries: [{ id: CHILD, mode: 'continuable', label: 'finished', activity: 'inactive' }], - }), {}, { - [CHILD]: { ...summary(CHILD, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - }) - render() - fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' })) - const header = document.querySelector('[data-subagent-section-header]')! - expect(header.textContent).toBe('子智能体1 已完成') - }) - - it.each([ - { name: 'absent Team projection', team: undefined, footer: true }, - { name: 'disabled Team mode', team: { ...sharedTeam, enabled: false }, footer: true }, - { name: 'empty tasks', team: { enabled: true, tasks: [] }, footer: true }, - { name: 'deleted-only tasks', team: { enabled: true, tasks: [{ ...sharedTask, status: 'deleted' }] }, footer: true }, - { name: 'failure without tasks', team: { enabled: true, tasks: [], failure: 'Invalid task record' }, footer: true }, - { name: 'unavailable task footer', team: sharedTeam, footer: false }, - ] satisfies { name: string; team: TeamProjection | undefined; footer: boolean }[])( - 'omits section headings from a members-only catalog with $name', ({ team, footer }) => { - const input = props(catalog({ ...team === undefined ? {} : { team } })) - render( select(footer)} />) - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - expect(screen.getByRole('tree')).toBeTruthy() - expect(screen.queryByRole('heading')).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - }, - ) - - it('shows the description above the Session id and opens the row without a description toggle', () => { - const description = 'Check the construction and all bounds. '.repeat(20).trim() - const input = props(catalog({ - entries: [{ id: CHILD, mode: 'continuable', label: description, activity: 'running' }], - })) - render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) - const primary = within(row).getByText(description) - const id = within(row).getByText(CHILD) - expect(primary.compareDocumentPosition(id) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(row.getAttribute('aria-label')).toMatch(/^Check the construction/) - expect(primary.tagName).toBe('SPAN') - expect(primary.getAttribute('aria-expanded')).toBeNull() - expect(primary.querySelector('svg')).toBeNull() - expect(within(row).queryByRole('button', { name: /描述/ })).toBeNull() - fireEvent.click(primary) - expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - expect(screen.queryByRole('treeitem')).toBeNull() + it('omits section headings from a catalog of members', () => { + render() + expect(screen.getByRole('tree')).toBeTruthy() + expect(screen.queryByRole('heading')).toBeNull() + expect(document.querySelector('[data-subagent-section-header]')).toBeNull() }) it.each([undefined, ''])('keeps a single ID line when the creation description is %s', (label) => { @@ -324,13 +254,13 @@ describe('SubagentHeaderLineage', () => { entries: [{ id: CHILD, mode: 'one-shot', ...label === undefined ? {} : { label }, activity: 'running' }], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) expect(within(row).getAllByText(CHILD)).toHaveLength(1) expect(row.getAttribute('aria-label')).toMatch(new RegExp(`^${CHILD}`)) }) - it('shows agent names in place of Session ids while navigation keeps the Session id', () => { + it('shows agent names in place of Session ids while navigation keeps the Session id', async () => { + vi.useFakeTimers() const external = 'external-id' as SessionId const input = props(catalog({ entries: [ @@ -340,11 +270,11 @@ describe('SubagentHeaderLineage', () => { ], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const named = screen.getByRole('treeitem', { name: /^Review the diff reviewer/ }) - expect(within(named).getByText('Review the diff').compareDocumentPosition(within(named).getByText('reviewer')) - & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + // The panel row shows one line; its hover card names the agent as the owner. + expect(within(named).queryByText('reviewer')).toBeNull() expect(within(named).queryByText(CHILD)).toBeNull() + expect(await hoverDetailsOf(named)).toEqual(['Review the diff', '负责人:reviewer', '正在运行 · 可继续']) const undescribed = screen.getByRole('treeitem', { name: /^checker/ }) expect(within(undescribed).getAllByText('checker')).toHaveLength(1) expect(within(undescribed).queryByText(GRANDCHILD)).toBeNull() @@ -353,91 +283,9 @@ describe('SubagentHeaderLineage', () => { expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) }) - it('hides an empty Team entry but keeps shared tasks and errors reachable without children', () => { - const input = props(catalog({ entries: [] })) - const initial = input.useSessions(state => state) - const mode: { enabled: boolean; tasks: TeamTaskView[]; failure?: string } = { enabled: true, tasks: [] } - const values = { ...initial.projectionsBySession[PARENT]!.values, agentTeam: mode } - const current = { - ...input, - useSessions: (select: (snapshot: SessionListState) => T): T => select({ - ...initial, projectionsBySession: { [PARENT]: { state: 'ready', error: null, values } }, - }), - renderSlot: () => mode.tasks.some(task => task.status !== 'deleted') - ?
      Tasks
      - : mode.failure === undefined ? null :
      {mode.failure}
      , - } - const view = render() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ - id: 'task-1' as TeamTaskId, revision: 1, subject: 'Plan work', description: 'Prepare tasks before spawning workers', - status: 'pending', blockedBy: [], writeScopes: [], ready: true, writeScopeWarnings: [], - }] - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - const tree = screen.getByRole('tree') - const board = screen.getByRole('region', { name: 'Shared tasks' }) - expect(tree.compareDocumentPosition(board) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(screen.getByRole('heading', { name: zh['section.title'] })).toBeTruthy() - expect(screen.getByText(zh['section.empty'])).toBeTruthy() - expect(screen.getAllByRole('dialog')).toHaveLength(1) - mode.tasks = [] - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ ...sharedTask, status: 'deleted' }] - view.rerender() - expect(screen.queryByRole('button')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - mode.tasks = [] - mode.failure = 'Invalid task record' - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - expect(screen.getByRole('dialog')).toBeTruthy() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - view.rerender( select(false)} />) - expect(screen.queryByRole('button')).toBeNull() - mode.enabled = false - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - }) - - it.each([false, true])('keeps child navigation without reading or rendering a task board (listed: %s)', (listed) => { - const input = props(catalog({ team: sharedTeam }), {}, listed ? { - [CHILD]: { ...summary(CHILD, 1), origin: 'subagent', parentId: PARENT }, - } : {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - const readProjection = vi.fn((): never => { throw new Error('child task-board projection read') }) - const readFooter = vi.fn((): never => { throw new Error('child footer subscription') }) - const renderFooter = vi.fn(() =>
      Tasks
      ) - render(<> - - - ) - fireEvent.click(screen.getByRole('button', { name: /切换子智能体/u })) - expect(screen.getByRole('tree')).toBeTruthy() - expect(screen.queryByRole('region', { name: 'Shared tasks' })).toBeNull() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - expect(readProjection).not.toHaveBeenCalled() - expect(readFooter).not.toHaveBeenCalled() - expect(renderFooter).not.toHaveBeenCalled() - }) - - it('leaves task-board keys alone and dismisses the shared panel from outside focus', () => { + it('leaves Escape from outside focus alone', () => { const input = props(catalog()) - render(<>