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-24-single-harness-home-resolver.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.i18n.yaml index 170036d0fb..a01d2a4e23 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.i18n.yaml @@ -9,8 +9,8 @@ en: fa4d3622fb18dd58 zh: 2b98640594c8344b /agent-note-one-harness-home-resolver/decision: - en: 816e5109718bc4ae - zh: af3f08f07c3cb761 + en: a9d9f7bf051341e9 + zh: cc1fed8d2b606276 /agent-note-one-harness-home-resolver/alternatives-considered: en: b1c9535540171d47 zh: 7df816d42945db94 diff --git a/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.md b/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.md index a128d4fe40..7b42b88087 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.md +++ b/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.md @@ -21,9 +21,9 @@ One resolver owns the harness home, in `@deepseek-ai/dsh-home-paths`, single-roo explicit configured path > $DSH_HOME > ~/.dsh ``` -An empty or whitespace-only `$DSH_HOME` is treated as unset; otherwise `resolve('')` would silently place the home at the current working directory. The harness keeps all user data under one root; there is no XDG config/data/cache split. `dshHomePath(...segments)` joins deployment-owned children onto that root, and `dsh-app-boot` exposes it to Loader `!!js` config expressions before mounting entries, so shipped compositions derive `sessions` and `storages` without copying the resolver. `dshHomeDisplay()` names a resolved root symbolically for user-facing paths — `~/.dsh` for the default home, `$DSH_HOME` for any configured home — so the user-global `AGENTS.md` label never leaks an absolute machine path. It replaces agent-instructions's bespoke default-vs-`$DSH_HOME` check. Home is process policy rather than row configuration: `dsh-agent-instructions` accepts no home override, so a composition cannot point instruction loading at a root that sessions, skills, and storage would not read. `resolveAgentsHome()` and `agentsHomeDisplay()` apply the same precedence, tilde expansion, and symbolic labelling to the shared agent configuration root (`$DSH_AGENTS_HOME` or `~/.agents`), which stays outside the harness home because other agent tools share it ([shared agents root](2026-10-05-shared-agents-root-instructions.md)); `dsh-skill-filesystem` still accepts its own `dshHome` and `agentsHome` fields, which select its own skill roots and resolve through the shared resolver in the instruction-loading change. +An empty or whitespace-only `$DSH_HOME` is treated as unset; otherwise `resolve('')` would silently place the home at the current working directory. The harness keeps all user data under one root; there is no split into separate XDG roots. `dshHomePath(...segments)` joins deployment-owned children onto that root, and `dsh-app-boot` exposes it to Loader `!!js` config expressions before mounting entries, so shipped compositions derive `sessions` and `storages` without copying the resolver. `dshHomeDisplay()` names a resolved root symbolically for user-facing paths — `~/.dsh` for the default home, `$DSH_HOME` for any configured home — so the user-global `AGENTS.md` label never leaks an absolute machine path. It replaces agent-instructions's bespoke default-vs-`$DSH_HOME` check. Home is process policy rather than row configuration: `dsh-agent-instructions` accepts no home override, so a composition cannot point instruction loading at a root that sessions, skills, and storage would not read. `resolveAgentsHome()` and `agentsHomeDisplay()` apply the same precedence, tilde expansion, and symbolic labelling to the shared agent configuration root (`$DSH_AGENTS_HOME` or `~/.agents`), which stays outside the harness home because other agent tools share it ([shared agents root](2026-10-05-shared-agents-root-instructions.md)); `dsh-skill-filesystem` still accepts its own `dshHome` and `agentsHome` fields, which select its own skill roots and resolve through the shared resolver in the instruction-loading change. -`dshCachePath(...segments)` derives paths below the resolved home's `cache` directory. An initial `{ dshHome }` option preserves a provider's explicit home override. It resolves paths without creating directories; callers own directory creation. `attachment-local` uses this helper for regenerable request-image variants while retaining durable attachment objects in their versioned storage tree, so clearing the cache cannot remove Session attachments. Existing request-image cache entries are left in place and are not read or copied; a cache miss regenerates the variant from its durable attachment. +`dshPath(category, ...segments)` derives paths below a `config`, `data`, `state`, `cache`, or `backup` directory of that one root, and app-boot exposes it to Loader `!!js` expressions beside `dshHomePath`; the [home path categories proposal](../../proposed/architecture/2026-11-04-dsh-home-path-categories.md) owns the categories and which existing entries keep their top-level locations. `dshCachePath(...segments)` is `dshPath('cache', ...segments)`. An initial `{ dshHome }` option preserves a provider's explicit home override. It resolves paths without creating directories; callers own directory creation. `attachment-local` uses this helper for regenerable request-image variants while retaining durable attachment objects in their versioned storage tree, so clearing the cache cannot remove Session attachments. Existing request-image cache entries are left in place and are not read or copied; a cache miss regenerates the variant from its durable attachment. `@deepseek-ai/dsh-home` is deleted. Home-owning providers and boot packages import `resolveDshHome` from `dsh-home-paths`; composition bundles contain only the resolved configuration rows. diff --git a/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.zh.md b/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.zh.md index 3f02908f86..3bc6c4faef 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-24-single-harness-home-resolver.zh.md @@ -21,9 +21,9 @@ Status: implemented explicit configured path > $DSH_HOME > ~/.dsh ``` -空或仅含空白的 `$DSH_HOME` 被当作未设置处理;否则,`resolve('')` 会悄悄把 home 落在当前工作目录。harness 把所有用户数据都放在同一个根目录下;不存在 XDG 的 config/data/cache 拆分。`dshHomePath(...segments)` 将部署负责的子路径拼接到该根目录下,`dsh-app-boot` 在挂载条目前向 Loader `!!js` 配置表达式暴露它,因此出厂组合无需复制解析器即可派生 `sessions` 和 `storages`。`dshHomeDisplay()` 为面向用户的路径以符号形式命名已解析的根目录——默认 home 显示为 `~/.dsh`,任何已配置的 home 显示为 `$DSH_HOME`——这样用户全局的 `AGENTS.md` 标签就绝不会泄露机器上的绝对路径。它取代了 agent-instructions 中自定义的「默认值 vs `$DSH_HOME`」判断。home 属于进程策略而非配置行:`dsh-agent-instructions` 不接受 home 覆盖,因此组合无法把指令加载指向会话、skill 与存储不会读取的根目录。`resolveAgentsHome()` 与 `agentsHomeDisplay()` 对共享 agent 配置根目录(`$DSH_AGENTS_HOME` 或 `~/.agents`)采用相同的优先级、波浪号展开与符号化标签;该根目录位于 harness home 之外,因为其他 agent 工具会共享它([共享 agents 根目录](2026-10-05-shared-agents-root-instructions.zh.md));`dsh-skill-filesystem` 仍接受自己的 `dshHome` 与 `agentsHome` 字段,用于选择它自己的 skill 根目录,并在指令加载改动中改用共享解析器。 +空或仅含空白的 `$DSH_HOME` 被当作未设置处理;否则,`resolve('')` 会悄悄把 home 落在当前工作目录。harness 把所有用户数据都放在同一个根目录下;不拆分到各自独立的 XDG 根目录。`dshHomePath(...segments)` 将部署负责的子路径拼接到该根目录下,`dsh-app-boot` 在挂载条目前向 Loader `!!js` 配置表达式暴露它,因此出厂组合无需复制解析器即可派生 `sessions` 和 `storages`。`dshHomeDisplay()` 为面向用户的路径以符号形式命名已解析的根目录——默认 home 显示为 `~/.dsh`,任何已配置的 home 显示为 `$DSH_HOME`——这样用户全局的 `AGENTS.md` 标签就绝不会泄露机器上的绝对路径。它取代了 agent-instructions 中自定义的「默认值 vs `$DSH_HOME`」判断。home 属于进程策略而非配置行:`dsh-agent-instructions` 不接受 home 覆盖,因此组合无法把指令加载指向会话、skill 与存储不会读取的根目录。`resolveAgentsHome()` 与 `agentsHomeDisplay()` 对共享 agent 配置根目录(`$DSH_AGENTS_HOME` 或 `~/.agents`)采用相同的优先级、波浪号展开与符号化标签;该根目录位于 harness home 之外,因为其他 agent 工具会共享它([共享 agents 根目录](2026-10-05-shared-agents-root-instructions.zh.md));`dsh-skill-filesystem` 仍接受自己的 `dshHome` 与 `agentsHome` 字段,用于选择它自己的 skill 根目录,并在指令加载改动中改用共享解析器。 -`dshCachePath(...segments)` 在解析出的主目录下的 `cache` 目录中派生路径。首个 `{ dshHome }` 选项保留提供方显式配置的主目录覆盖值。它只解析路径,不创建目录;目录创建由调用方负责。`attachment-local` 将此函数用于可重新生成的请求图片版本,持久附件对象仍保留在其带版本的存储树中,因此清空缓存不会删除 Session 附件。已有请求图片缓存条目保留在原处,不再读取或复制;缓存未命中时从持久附件重新生成请求版本。 +`dshPath(category, ...segments)` 在该根目录下的 `config`、`data`、`state`、`cache` 或 `backup` 目录中派生路径,app-boot 将它与 `dshHomePath` 一并暴露给 Loader `!!js` 表达式;类别定义以及哪些现有条目保留顶层位置由 [home 路径类别提案](../../proposed/architecture/2026-11-04-dsh-home-path-categories.zh.md)负责。`dshCachePath(...segments)` 等同于 `dshPath('cache', ...segments)`。首个 `{ dshHome }` 选项保留提供方显式配置的主目录覆盖值。它只解析路径,不创建目录;目录创建由调用方负责。`attachment-local` 将此函数用于可重新生成的请求图片版本,持久附件对象仍保留在其带版本的存储树中,因此清空缓存不会删除 Session 附件。已有请求图片缓存条目保留在原处,不再读取或复制;缓存未命中时从持久附件重新生成请求版本。 `@deepseek-ai/dsh-home` 被删除。拥有 home 配置的提供方与 boot 包从 `dsh-home-paths` 导入 `resolveDshHome`;组合包只包含解析后的配置行。 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-08-desktop-welcome-window-material.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.i18n.yaml index 98414d1dd2..76517aa858 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.i18n.yaml @@ -9,8 +9,8 @@ en: 8578b584bda3abdc zh: 85dcf44aab2cfd51 /agent-note-desktop-welcome-window-material/decision: - en: 1affa7f1fccc945f - zh: e5aea959e7886a59 + en: 307d17b576022b26 + zh: 2992ab7d8abde284 /agent-note-desktop-welcome-window-material/alternatives-considered: en: cf42e200b1d0f00a zh: de96b5647f5ffb23 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.md index e285a57699..cf30999adb 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.md @@ -12,7 +12,7 @@ The desktop welcome design blurs the desktop behind its entire window. Chromium The [Electron welcome window](../../../../apps/desktop/src/welcome-window.ts) owns native material and window controls. Its independently bundled React renderer supplies the entry, account sign-in states and API-key form. It shares the `StateDot` loading component with the Web UI without booting the Web plugin graph. The Desktop build emits local JavaScript and CSS under `lib/welcome`, included in packaged applications; the document keeps its network-denying content security policy. A narrow preload supplies typed shell copy, a write-only key operation, and a skip operation; IPC rejects other windows and subframes. Each sandboxed preload is bundled independently because Electron’s restricted require cannot load sibling chunks. The Electron main process authenticates through the shared Web launch URL and resolves the official provider's reference through the existing settings and credential RPC methods. The [thin Web wrapper](2026-09-10-desktop-web-wrapper.md) owns the HTTP server; onboarding adds no Host endpoint or child IPC operation. Responses contain metadata or a safe outcome, never a key or private provider diagnostics. -Cold startup opens the entry when neither an account credential nor a model API key is configured. Saving enters the workspace after persistence succeeds; skipping enters without saving a draft or a credential-entry completion flag. The next process launch checks credentials again. The Desktop preload marker suppresses the automatic Web credential step and welcome notice; settings and explicit API-key editing remain available. The [Desktop onboarding reference](../../../../packages/client/ui-settings-account/README.md) owns the separate device-local introduction after account login. Other native shells can disable only the credential step through the Models Host plugin's `credentialOnboarding` page-injection value. The module graph carries package identities rather than arbitrary Host config, so a Host row alone does not configure its Client half. The [account provider](2026-09-14-deepseek-account-login.md) supplies login and sign-out state while preserving independently stored API keys. +Cold startup opens the entry when neither an account credential nor a model API key is configured. Saving enters the workspace after persistence succeeds; skipping enters without saving a draft or a credential-entry completion flag. The next process launch checks credentials again. The Desktop preload marker suppresses the automatic Web credential step and welcome notice; settings and explicit API-key editing remain available. The [Desktop onboarding reference](../../../../packages/client/ui-settings-account/README.md) owns the separate device-local introduction after account login. Other native shells can disable only the credential step through the Models plugin's synced `credentialOnboarding` Config field. The module graph carries package identities rather than arbitrary Host config, so a Host row alone does not configure its Client half. The [account provider](2026-09-14-deepseek-account-login.md) supplies login and sign-out state while preserving independently stored API keys. The generated project follows declared workspace dependencies because pnpm’s hoist index alone can omit configured plugins. diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.zh.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.zh.md index e708b53447..3693158338 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.zh.md @@ -12,7 +12,7 @@ Status: implemented [Electron 欢迎窗口](../../../../apps/desktop/src/welcome-window.ts)负责原生材质和窗口控件。独立打包的 React 渲染器提供入口、账号登录状态和 API Key 表单。它与 Web UI 共用 `StateDot` 加载组件,不启动 Web 插件图。Desktop 构建将本地 JavaScript 和 CSS 输出到 `lib/welcome`,并纳入应用安装包;文档继续使用禁止网络访问的内容安全策略。窄接口 preload 提供强类型桌面文案、仅写密钥操作和跳过操作;IPC 拒绝其他窗口和子 frame。每个沙箱 preload 都独立打包,因为 Electron 受限的 require 无法加载同目录中的拆分模块。Electron 主进程通过共享 Web 启动 URL 认证,并通过现有设置和凭证 RPC 方法解析官方提供方的引用。[Web 薄壳](2026-09-10-desktop-web-wrapper.zh.md)负责 HTTP 服务;引导不增加 Host 端点或子进程 IPC 操作。响应只包含元数据或安全结果,不包含密钥或提供方的私有诊断。 -冷启动在账号凭证与模型 API Key 均未配置时打开入口。保存会在持久化成功后进入工作区;跳过会直接进入,不保存草稿或凭证入口完成标记。下次进程启动时会重新检查凭证。Desktop preload 标记抑制自动 Web 凭证步骤和欢迎须知;设置与显式 API Key 编辑仍然可用。[Desktop 引导参考](../../../../packages/client/ui-settings-account/README.zh.md)负责账号登录后独立的设备本地介绍流程。其他原生壳可以通过 Models Host 插件注入页面的 `credentialOnboarding` 值仅禁用凭证步骤。模块图传递的是包标识,而不是任意 Host 配置,因此单独配置 Host 行不会配置其 Client 半部。[账号提供方](2026-09-14-deepseek-account-login.zh.md)提供登录与退出登录状态,同时保留独立存储的 API Key。 +冷启动在账号凭证与模型 API Key 均未配置时打开入口。保存会在持久化成功后进入工作区;跳过会直接进入,不保存草稿或凭证入口完成标记。下次进程启动时会重新检查凭证。Desktop preload 标记抑制自动 Web 凭证步骤和欢迎须知;设置与显式 API Key 编辑仍然可用。[Desktop 引导参考](../../../../packages/client/ui-settings-account/README.zh.md)负责账号登录后独立的设备本地介绍流程。其他原生壳可以通过 Models 插件同步到浏览器的 `credentialOnboarding` Config 字段仅禁用凭证步骤。模块图传递的是包标识,而不是任意 Host 配置,因此单独配置 Host 行不会配置其 Client 半部。[账号提供方](2026-09-14-deepseek-account-login.zh.md)提供登录与退出登录状态,同时保留独立存储的 API Key。 生成的开发项目沿已声明的 workspace 依赖建立链接,因为单独依赖 pnpm 的提升索引会漏掉配置插件。 diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml index 49a9f432ee..97db170db9 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml @@ -9,11 +9,11 @@ en: 31fba384d90ce7d2 zh: f8b814868f3280c3 /agent-note-session-working-directory/decision: - en: 9ccde1c5e635b9c0 - zh: 4dc76229703d3ef7 + en: 5ff0c24c29c916b9 + zh: bfbb082623c2a86c /agent-note-session-working-directory/alternatives-considered: en: f0995feb9b6bcce8 zh: 97417085fd17f70f /agent-note-session-working-directory/consequences: - en: 2dd3a4de72ee6d74 - zh: be5d8a80c8eaac6e + en: da8ef050c25c7a7b + zh: 8c9c1ca7467f986e diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md index 8151c0e85a..6b8a6c9507 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md @@ -10,17 +10,17 @@ A fixed Session creation directory cannot represent a task that changes checkout ## Decision -`dsh-working-directory` owns one logged effective directory per Session. Its projection initializes from the immutable original project and folds `working-directory/change`; consumers read that owner instead of deriving execution paths from the header or sandbox root. Directory changes validate through the filesystem provider, serialize within the Session, and publish only after the new directory is available. +`dsh-working-directory` owns one logged effective directory per Session. Its projection initializes from the immutable original project and folds `workspace-root/change` events; consumers read that owner instead of deriving execution paths from the header or sandbox root. Directory changes validate through the filesystem provider, serialize within the Session, and publish only after the new directory is available. -The `dsh-base` composition mounts `working_directory({ cd? })` globally. The tool reads or changes the Session directory, so every Agent preset can select or recover it, including presets without file-editing tools. The Web composition keeps action tools in preset scopes. +Only Host operations change the directory: worktree creation and exit, the forge panel, SDK requests, and child startup call the service. The [workspace-root note](2026-11-03-session-workspace-root.md) removed the model-facing `working_directory` tool, records each change as `workspace-root/change`, and ignores stored `working-directory/change` events. Required user-context snapshots carry the current value; each committed change attempts to queue a notice through the ordinary Agent inbox. Cancellation or disposal may discard unadmitted notices while the directory event survives for subsequent requests. The original project is the recovery destination when the selected directory disappears. Missing recovery destinations produce an error. Write permissions remain independent. -Subagents capture the parent's current directory or an explicit override and commit their selected directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. Project instructions, skills, and completion follow the effective directory without changing Session identity, grouping, or runtime composition. +Subagents start in the parent's current directory or a Host-chosen directory and commit that directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. The model's file and process tools, project instructions, skills, completion, and the sandbox boundary follow the effective directory, which is the [workspace root](2026-11-03-session-workspace-root.md), without changing Session identity, grouping, or runtime composition. -Live Session skill catalogs and file completion validate through the same directory owner. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directory. Cold skill catalogs read the recorded projection without activating an Agent. +Live Session skill catalogs and file completion validate through the same directory owner, then read the workspace root. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directories. Cold skill catalogs read the recorded root projection without activating an Agent. -Web sidebar terminal environment lookup reads the effective directory without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning; the process keeps that directory independently of later Session changes. +Web sidebar terminal environment lookup reads the workspace root without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning in the workspace root; the process keeps that directory independently of later Session changes. Playwright MCP and Chrome DevTools MCP validate the effective directory when acquiring a Session's MCP connection and use it to launch the server. Later directory changes do not restart the retained server or change its process directory. @@ -44,4 +44,4 @@ The runtime exposes one directory owner and preserves the original project. Cons `{{cwd}}` has no loop-provided value; custom personas that depend on that built-in fail strict interpolation. Deployments remove those references using the [system-prompt migration guidance](../../../../packages/core/system-prompt/README.md). When both the current directory and its recovery destination are unavailable, prompt assembly rejects model turns; the [directory service recovery guidance](../../../../packages/session/working-directory/README.md#known-limitations-and-deferred-work) requires restoring the directory or selecting an existing absolute directory through the SDK or host service. -Verification covers independent Sessions, relative changes, replay, cancellation, recovery, tool disposal, user-context rendering, provider inheritance, and real directory-based operations. +Verification covers independent Sessions, relative changes, replay, cancellation, recovery, user-context rendering, provider inheritance, and real directory-based operations. diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md index 46246a9d67..8d99661c89 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md @@ -10,17 +10,17 @@ Status: implemented ## Decision -`dsh-working-directory` 拥有每个 Session 的一个日志化有效目录。投影从不可变的原始项目初始化,并折叠 `working-directory/change`;消费者读取该服务,而不是从 header 或沙箱根目录派生执行路径。目录变更通过文件系统 provider 验证,在 Session 内串行执行,并只在新目录可用后发布。 +`dsh-working-directory` 拥有每个 Session 的一个日志化有效目录。投影从不可变的原始项目初始化,并折叠 `workspace-root/change` 事件;消费者读取该服务,而不是从 header 或沙箱根目录派生执行路径。目录变更通过文件系统 provider 验证,在 Session 内串行执行,并只在新目录可用后发布。 -`dsh-base` 组合在全局挂载 `working_directory({ cd? })`。该工具读取或改变 Session 目录,使每个 Agent preset 都能选择或恢复它,包括没有文件编辑工具的 preset。Web 组合把操作工具放在 preset 作用域中。 +只有 Host 操作改变目录:工作树的创建与退出、forge 面板、SDK 请求和子代理启动调用该服务。[工作区根记录](2026-11-03-session-workspace-root.zh.md)移除了面向模型的 `working_directory` 工具,把每次变更记录为 `workspace-root/change`,并忽略已存储的 `working-directory/change` 事件。 必需的用户上下文快照携带当前值;每次已提交变更都会尝试通过普通 Agent 收件箱排入通知。取消或销毁可能丢弃尚未进入请求的通知,但目录事件仍然保留,供后续请求使用。所选目录消失时恢复到原始项目。恢复目录也消失时返回错误。写权限保持独立。 -子代理捕获父代理当前目录或显式覆盖值,并在继承历史之后提交选定目录。已有进程、终端和持久 shell 保留进程局部目录。项目指令、技能和补全跟随有效目录,不改变 Session 身份、归属或运行时组合。 +子代理从父代理的当前目录或 Host 选定的目录启动,并在继承历史之后提交该目录。已有进程、终端和持久 shell 保留进程局部目录。模型的文件与进程工具、项目指令、技能、补全和沙箱边界都跟随有效目录,即[工作区根](2026-11-03-session-workspace-root.zh.md),不改变 Session 身份、归属或运行时组合。 -活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的投影,不激活 Agent。 +活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录,再读取工作区根。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的根投影,不激活 Agent。 -Web 侧栏终端的环境查询读取有效目录,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录;后续 Session 目录变更不会改变该进程的目录。 +Web 侧栏终端的环境查询读取工作区根,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录,并在工作区根中启动;后续 Session 目录变更不会改变该进程的目录。 Playwright MCP 和 Chrome DevTools MCP 在获取 Session 的 MCP 连接时验证有效目录,并在该目录启动服务器。后续目录变更不会重启保留的服务器,也不会改变其进程目录。 @@ -44,4 +44,4 @@ Playwright MCP 和 Chrome DevTools MCP 在获取 Session 的 MCP 连接时验证 `{{cwd}}` 没有循环提供的值;依赖该内置变量的自定义 persona 会触发严格插值错误。部署方按照[系统提示词迁移说明](../../../../packages/core/system-prompt/README.zh.md)移除这些引用。当前目录与恢复目标均不可用时,提示词组装会拒绝模型轮次;[目录服务恢复说明](../../../../packages/session/working-directory/README.zh.md#known-limitations-and-deferred-work)要求恢复目录,或通过 SDK 或 Host 服务选择现有的绝对目录。 -验证覆盖 Session 相互独立、相对路径变更、回放、取消、恢复、工具卸载、用户上下文渲染、provider 继承和真实目录操作。 +验证覆盖 Session 相互独立、相对路径变更、回放、取消、恢复、用户上下文渲染、provider 继承和真实目录操作。 diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml index 6826d6a497..ef4816a697 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml @@ -15,8 +15,8 @@ en: 9ff7f15985d06986 zh: fe27ef687594c124 /agent-note-client-session-references-reference-sources-and-ui-status/decision/addresses-bindings-and-references: - en: 3743abc8bca00348 - zh: d79e6a9311f0a2fe + en: 21659869e0d90071 + zh: 6a011076cf6676ca /agent-note-client-session-references-reference-sources-and-ui-status/decision/acquisition-failure-and-release: en: 84e9528d4f995460 zh: f79f197d3dfbe8e9 diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md index 6a7c15ad86..85e4c5401c 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md @@ -52,7 +52,9 @@ The [blank Session decision](2026-09-17-process-local-blank-sessions.md) owns cr | `sessions.sessionOf(ctx)` | Returns the matching live Session face or `undefined`; an ended Context cannot resolve to a same-id replacement | | `sessions.create(...)` / `sessions.fork(...)` | Existing Host operations returning a Session identity; retaining and displaying it remain explicit | -`SessionRetainOptions` contains required `source: SessionReferenceSource` and optional `signal: AbortSignal`. Both acquisition methods accept `target: SessionTarget` and these options. Source keys are consumer-defined and declaration-merge extensible; there is no runtime source-registration protocol or default main-view source. A source is a usage label, not another Session address or a permission to act on it. +`SessionRetainOptions` contains required `source: SessionReferenceSource`, optional `facets`, and optional `signal: AbortSignal`. Both acquisition methods accept `target: SessionTarget` and these options. Source keys are consumer-defined and declaration-merge extensible; there is no runtime source-registration protocol or default main-view source. A source is a usage label, not another Session address or a permission to act on it. + +[Session retain facets and recent views](2026-11-15-session-retain-facets-and-recent-views.md) owns `facets`, the independently counted parts a reference keeps beyond its history stream, and the `recentViews` source. ### Acquisition, failure, and release diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md index 167dbac7b9..fa38ddcef7 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md @@ -52,7 +52,9 @@ Client Session 对象、Agent 作用域的 Client Context、引用、使用方 | `sessions.sessionOf(ctx)` | 返回匹配的活跃 Session 接口或 `undefined`;已结束的 Context 不能解析为同 ID 替代代 | | `sessions.create(...)` / `sessions.fork(...)` | 既有 Host 操作,返回 Session 身份;持有与展示仍需显式执行 | -`SessionRetainOptions` 包含必填 `source: SessionReferenceSource` 与可选 `signal: AbortSignal`。两个获取方法均接受 `target: SessionTarget` 和这些 options。来源键由使用方定义,通过声明合并扩展;不提供运行时来源注册协议,也不默认使用主视图来源。来源是使用标签,不是另一种 Session 地址,也不授予操作权限。 +`SessionRetainOptions` 包含必填 `source: SessionReferenceSource`、可选 `facets` 与可选 `signal: AbortSignal`。两个获取方法均接受 `target: SessionTarget` 和这些 options。来源键由使用方定义,通过声明合并扩展;不提供运行时来源注册协议,也不默认使用主视图来源。来源是使用标签,不是另一种 Session 地址,也不授予操作权限。 + +[Session retain 子要素与最近访问会话](2026-11-15-session-retain-facets-and-recent-views.zh.md) 负责 `facets`,即引用在历史流之外独立计数保活的部分,以及 `recentViews` 来源。 ### 获取、失败与释放 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 b04f873a24..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,14 +24,14 @@ 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 /agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/consequences: - en: 53d72faa09e78410 - zh: a5224e4662a4846b + en: ed424571c81bcb91 + zh: 9b79bf03741c1c21 /agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/testing: en: 532918df1acd147d zh: e476c090d183d0a4 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 71509500e5..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 @@ -81,7 +81,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_ ## Consequences -The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override, and enabling any bundle skips no patch. The Plugins page and Settings → Built-in plugins list every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector. +The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override, and enabling any bundle skips no patch. The Plugins page lists every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector. Size (MiB, measured): the base image is 9.20 (12.79 with pack-time composition and eager chunks, −28%) including 11 optional bundles, plus 5 lazy tar archives totaling 4.45 (pdf 2.88, excel 1.39, terminal 0.13, frontmatter 0.05, Inspector bottom panel 0.00). The base image contains no lazily loaded chunk, and the page fetches an archive only when it requests the chunk. 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 5c9b5bf233..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 插件无需刷新页面即可挂载。 ## 考虑过的替代方案 @@ -81,7 +81,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错 ## 后果 -Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖;开任一 bundle 都没有被跳过的补丁。插件页和“设置 → 内置插件”列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。 +Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖;开任一 bundle 都没有被跳过的补丁。插件页列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。 体积(MiB,实测):基础镜像 9.20(打包期组合且 chunk 随启动下载时为 12.79,−28%),含 11 个 optional bundle;另有 5 个 lazy tar 共 4.45(pdf 2.88、excel 1.39、terminal 0.13、frontmatter 0.05、inspector 底部面板 0.00)。基础镜像不含懒加载 chunk,页面请求 chunk 时才拉取对应 archive。 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-28-upstream-skills-runtime-download.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.i18n.yaml new file mode 100644 index 0000000000..b21f9c6fb1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-28-upstream-skills-runtime-download.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-28-upstream-skills-runtime-download.md +/agent-note-runtime-download-of-upstream-skills: + en: aa22dd6b2e4a7dd5 + zh: 19e36747a2ae6310 +/agent-note-runtime-download-of-upstream-skills/problem: + en: 755fe8a192cfebe1 + zh: 855ad2920b33e364 +/agent-note-runtime-download-of-upstream-skills/decision: + en: e601879f83a17cba + zh: a5ab03a7804787fc +/agent-note-runtime-download-of-upstream-skills/alternatives-considered: + en: 3828cc141c037db6 + zh: 3a164d7a5886cbd2 +/agent-note-runtime-download-of-upstream-skills/consequences: + en: 124556ff88e9e014 + zh: d25070f79bb2c726 diff --git a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.md b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.md new file mode 100644 index 0000000000..8464038b57 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.md @@ -0,0 +1,31 @@ +# Agent Note: Runtime download of upstream skills + +Status: implemented + +English | [中文](2026-10-28-upstream-skills-runtime-download.zh.md) + +## Problem + +The WeCom and Tencent Meeting plugins index guides that their vendors publish only in their GitHub repositories: 180 files, about 1.75 MB, for WeCom and 11 for Tencent Meeting. A copy in this repository dominates each plugin's diff and every upstream update, and the plugins' npm packages would publish DeepSeek's copy of another company's content. DeepSeek does not publish such copies. + +## Decision + +Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the upstream files by repository, commit, kept directory, exclusions, license file, total size, and a digest of the kept files, and registers both with `ctx.upstreamSkills`, the Service of [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.md). The Service downloads the commit archive from GitHub when the plugin loads, keeps the directory and the license file, verifies them, publishes them in `$DSH_HOME/cache/`, and lists the entry skill with that directory as its base directory. The plugin shows the download state beside the account state. Its check reads only the account and restarts a failed download without waiting for it: the CLI account runtime runs one operation at a time, so a check that waited for a slow GitHub download would also hold sign-in. Each archive source has `skillsTimeoutMs` to deliver the whole archive, and reading stops once the kept files exceed the pinned size. A plugin's `skillsDir` points at prepared files for tests and offline installations, and the Service's `skillsUrls` replaces the archive host for every plugin. + +## Alternatives considered + +**A copy in this repository.** It was the earlier approach. Byte-identical copies dominate review and upstream updates, and the plugins' npm packages republish them. + +**A DSH-published package of the upstream files.** It moves the copy out of this repository, but it is still DeepSeek's own publication of another company's content. + +**The vendors' npm packages.** Neither `@wecom/cli` nor `@tencentcloud/tmeet` ships the skills. + +**jsDelivr or one request per file.** A CDN adds a third party between the vendor and the user. Per-file downloads need the file list in the pin and one request per file, while one archive per commit needs one request and lets the digest cover exactly what is kept. + +**A digest of the archive bytes.** The files of a commit archive are stable, but GitHub does not keep its compressed bytes stable, so the digest covers the kept files' paths and contents instead. + +**DingTalk's downloader.** DingTalk downloads checksummed release assets together with its executable. WeCom and Tencent Meeting publish no release assets and install their CLIs from npm, so only these two plugins register with this Service, and DingTalk keeps its own downloader. + +## Consequences + +The repository and the plugins' npm packages carry only the entry skills. The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the failure, which its next check retries. Tests, recorded Sessions, and Web end-to-end tests set `skillsDir` to fixture files and make no network requests. Published directories are never pruned. Updating a pin is a code change: `scripts/upstream-skills-digest.ts` prints the new pin, and the entry's guide index and a real-model run follow it. diff --git a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.zh.md b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.zh.md new file mode 100644 index 0000000000..5cf2467522 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.zh.md @@ -0,0 +1,31 @@ +# Agent Note:运行时下载上游技能 + +Status: implemented + +[English](2026-10-28-upstream-skills-runtime-download.md) | 中文 + +## 问题 + +企业微信和腾讯会议插件索引的子指南,厂商只在自己的 GitHub 仓库里发布:企业微信 180 个文件,约 1.75 MB;腾讯会议 11 个。把它们复制进本仓库,会让副本占据每个插件的 diff 和每次上游更新,插件的 npm 包也会发布 DeepSeek 复制的其他公司内容。DeepSeek 不发布这类副本。 + +## 决策 + +这些插件只保留 DSH 自己编写的入口 `SKILL.md`,按仓库、提交、保留的目录、排除项、许可证文件、总大小和保留文件的摘要固定上游文件,并把两者注册到 `ctx.upstreamSkills`,即 [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.zh.md) 的 Service。插件加载时,Service 从 GitHub 下载这个提交的归档,保留该目录和许可证文件,校验后发布到 `$DSH_HOME/cache/<插件>`,再列出入口技能,并把这个目录作为它的基础目录。插件在账号状态旁显示下载状态。它的检查只读取账号,并在不等待的情况下重新开始失败的下载:CLI 账号运行时一次只执行一个操作,检查若等待缓慢的 GitHub 下载,登录也会被占住。每个归档来源要在 `skillsTimeoutMs` 内送达完整归档,保留文件超过固定的大小时停止读取。插件的 `skillsDir` 为测试和离线安装指向准备好的文件,Service 的 `skillsUrls` 为所有插件替换归档主机。 + +## 考虑过的替代方案 + +**在本仓库中保留副本。** 这是之前的做法。逐字节相同的副本占据评审和上游更新,插件的 npm 包还会再次发布它们。 + +**由 DSH 发布上游文件的包。** 它把副本移出本仓库,但仍是 DeepSeek 自己发布其他公司的内容。 + +**厂商的 npm 包。** `@wecom/cli` 和 `@tencentcloud/tmeet` 都不包含这些技能。 + +**jsDelivr 或逐个文件请求。** CDN 在厂商和用户之间多了一个第三方。逐个文件下载需要在固定信息中列出文件,每个文件一次请求;每个提交一个归档只需一次请求,摘要也正好覆盖保留的文件。 + +**对归档字节做摘要。** 提交归档中的文件是稳定的,但 GitHub 不保证压缩后的字节稳定,因此摘要覆盖保留文件的路径和内容。 + +**钉钉的下载器。** 钉钉把带校验和的发布资产和可执行文件一起下载。企业微信和腾讯会议没有发布资产,CLI 从 npm 安装,因此只有这两个插件注册到这个 Service,钉钉保留自己的下载器。 + +## 影响 + +仓库和插件的 npm 包里只有入口技能。换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示失败,下一次检查会重试。测试、录制的 Session 和 Web 端到端测试都把 `skillsDir` 设为夹具文件,不发起网络请求。已发布的目录从不清理。更新固定提交需要改代码:`scripts/upstream-skills-digest.ts` 输出新的固定信息,随后更新入口的子指南索引,并用真实模型运行一次。 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-03-session-workspace-root.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml new file mode 100644 index 0000000000..772a8c6bcd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-03-session-workspace-root.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-03-session-workspace-root.md +/agent-note-session-workspace-root: + en: f746e6645bc11001 + zh: b7666200c98a96fc +/agent-note-session-workspace-root/problem: + en: 6938aa715106bb99 + zh: ea1497b337712f33 +/agent-note-session-workspace-root/decision: + en: 0b07db6326c2ecd6 + zh: 19ba9a1adf93af1f +/agent-note-session-workspace-root/alternatives-considered: + en: 8a4859a6f96ef49e + zh: fa7088d29ebe3dd6 +/agent-note-session-workspace-root/consequences: + en: a6bf8aa40464f524 + zh: 61997dc31615bdbb diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md new file mode 100644 index 0000000000..a37849a230 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md @@ -0,0 +1,49 @@ +# Agent Note: Session workspace root + +Status: implemented + +English | [中文](2026-11-03-session-workspace-root.zh.md) + +## Problem + +A Session that enters a Git worktree records only a changed current directory. The `working_directory` tool recorded the same event for a model's `cd` into a subdirectory or out of the project, so a consumer could not tell a model-moved cursor from a changed checkout: a file view, a change summary, or a write boundary either followed every `cd` or stayed on the original project. Usage did not justify the cursor: in 58 recorded Sessions of one developer that offered the tool, the model called it once in 6,229 tool calls and prefixed 61% of its shell commands with `cd`. + +## Decision + +A Session works in one directory, and only Host operations move it. The model-facing `working_directory` tool and the `cwd` parameter of the delegation tools are removed; the model reaches a subdirectory through paths and the shell's per-call `workdir`. `header.cwd` remains the immutable original project: Session identity, workspace grouping, and the recovery destination. `dsh-working-directory` owns the directory and has one read, `get`: relative paths resolve from the directory, and it is the workspace root that consumers bound writes, file views, and discovery by. Every change the service records, through `set` or the recovery of `ensure`, is a `workspace-root/change`. + +`workspace-root/change` is a new ordinary event type, recorded as a same-version persistence change in the [acknowledgement](../../../../docs/persistence-changes/2026-11-13-workspace-root-change.md). `working-directory/change` stays in the event vocabulary, deprecated and without a writer. Readers ignore a stored one: the same event recorded the model's `cd` and an entered worktree, and most stored ones are a `cd`, since few stored Sessions ran the worktree plugin. A Session that holds them resumes in its original project, or in the directory of its last `workspace-root/change`, and the next request's context reports the directory. An older build refuses a log that holds `workspace-root/change`; a Session that never moves its workspace holds none. + +Worktree creation enters the checkout through `set`. The model has one tool for entering a checkout, `enter_worktree`: a name selects a worktree inside the pool of the checkout the Session works in. An existing one is entered through `ctx.worktrees.enter`, and a new one is created through `ctx.worktrees.create` when none has that name. The name cannot leave that pool, so the model still cannot choose an arbitrary directory. `ctx.worktrees.exit`, exposed as `exit_worktree`, returns the Session from the recorded worktree that contains its directory to the checkout it created or entered that worktree from. A child subagent keeps the parent's original project in its header and starts, through `set`, in the parent's directory or a Host-chosen directory. + +Every consumer reads that directory. The model's file, search, and process tools resolve relative paths from it, and everything the user sees or that describes the project is bounded by it: the sandbox `workspace-write` boundary, the workspace file service and desktop file drag, the change recorder, the Files tree, deliverables, open-in-app actions and Session rows, new sidebar terminals, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace. + +The sandbox policy reads no Git layout: it bounds a Session by its directory and adds only the directories the deployment configured or a Host plugin registered for that Session through `registerWritableRoot`. A repository's Git directory lies outside a linked worktree, so after a move into a worktree a Git command that writes it, such as `git commit`, is denied under `workspace-write` until a grant covers that directory; the original project is not writable either. Granting the Git directory of the checkout a Session works in belongs to a separate plugin that reads the Git layout and registers the directory, which this decision defers. Host maintenance of a checkout the Session does not work in keeps the original boundary: removing a worktree on archive, restoring a removed one, and reading its branch in the source repository run under a policy the worktree service and the forge panel build themselves, the Session's mode and grants with the recorded source checkout as the root. The Session's own root may be the removed directory, and a process sandbox cannot bind a missing or vanishing root. + +## Alternatives considered + +**Keep the cursor and derive the root from registered anchors.** An optional `anchor` on the change, an anchor list, and a longest-containing-anchor rule separate a model's `cd` from a changed checkout, at the cost of three directories, a relocation operation, and an inheritance rule for children. Removing the only model-facing mover makes that separation unnecessary. + +**Derive the root from the worktree plugin's creation record.** That record is an ignorable experimental plugin record, which a format migration keeps only on a best-effort basis; a released package must not derive a write boundary from it. + +**Rewrite the header on relocation.** The header is identity metadata for storage, grouping, and permission roots; the [working-directory note](2026-09-13-session-working-directory.md) rejected rewriting it. + +**An optional `workspace` marker on `working-directory/change`.** Older readers ignore the property and keep reading every log. Every change the service records would then carry a constant, and a missing property would be the only sign of a stored change; a separate event names the workspace move and leaves the stored event unchanged. + +**Retire `working-directory/change` through a format migration.** The stored event carries no origin, so a migration would classify each one by its neighbouring events. Ignoring stored events needs no rewrite of the log. The [compatibility rules](../../../../docs/persistence-changes/README.md#compatibility-rules) reserve a version bump for changes that an existing discriminator cannot make safe. + +**Enter a worktree by path.** A model-supplied path would move the write boundary to any registered worktree, which removing the directory tool ruled out unless the user approves each move. A `tools/pre-execute` listener can ask for that approval through the approval service; this decision leaves the path form, and with it entry of a sibling from inside a worktree, to a later change. A name inside the pool keeps the boundary inside the checkout. + +**Separate tools for creation and entry.** `create_worktree` beside `enter_worktree` gave the model two tools for one action, entering a worktree, and made it choose by whether the worktree exists. One tool follows Claude Code's `EnterWorktree`, which creates a worktree or opens the one of that name. In the 79 recorded Sessions of one developer that offered `create_worktree`, the model called it once in 6,599 tool calls, so removing the name affects few stored Sessions. + +**Persist the shell's `cd` between calls.** That is an implicit cursor. In that developer's Sessions, 68% of `cd` prefixes named a directory outside the Session directory and 30% the Session directory itself, so a persisted directory confined to the workspace would apply to about 2%. + +**Two public reads.** `get` for relative paths beside `rootOf` for the workspace root kept every stored directory, and made each consumer choose between two values that are equal in every Session started from this version on. One read removes that choice. + +**Keep every stored directory.** Reading every stored `working-directory/change` as the directory would let a stored model `cd`, including one to a home directory, become the write boundary, because consumers follow the directory. + +**Keep stored directories inside the original project.** A Session that entered a worktree would resume there, but the rule cannot tell a worktree from a `cd`: a stored `cd` into a subdirectory would narrow the write boundary and the file views, and a worktree outside the directory a Session was opened in would be dropped. + +## Consequences + +Consumers read one directory through `get`. A stored Session resumes in its original project whatever directory its `working-directory/change` events recorded, and follows Host moves from there. One that worked in a worktree returns to it through `enter_worktree`; until then its relative paths resolve in the original project. The model enters a checkout only through `enter_worktree`: a new one, or a registered one in the pool. A checkout elsewhere needs a Host operation. The ACP, SDK, and Web producers record the original project by its canonical spelling, so a Host move back to it records no change. A Session that works in a linked worktree, whether it entered one or was opened in one, cannot run `git commit` under `workspace-write` without a grant for the repository's Git directory; on the previous boundary a Session that entered a worktree inside its project could. An SDK `setWorkingDirectory` call and a child started in a Host-chosen directory move the `workspace-write` boundary with the directory. The worktree snapshot fixture covers entering, leaving, and losing a worktree. diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md new file mode 100644 index 0000000000..c35b5a9f83 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md @@ -0,0 +1,49 @@ +# Agent Note: Session workspace root + +Status: implemented + +[English](2026-11-03-session-workspace-root.md) | 中文 + +## Problem + +进入 Git 工作树的 Session 只记录当前目录的变化。`working_directory` 工具在模型 `cd` 进子目录或离开项目时记录的是同一种事件,消费方因此无法区分模型移动的光标和已切换的检出:文件视图、变更汇总或写边界要么跟随每一次 `cd`,要么停留在原始项目。实际用法也不支持保留光标:在一位开发者的 58 个提供该工具的已记录 Session 中,模型在 6,229 次工具调用里只调用了它一次,61% 的 shell 命令自带 `cd` 前缀。 + +## Decision + +一个 Session 在一个目录中工作,只有 Host 操作移动它。面向模型的 `working_directory` 工具与委派工具的 `cwd` 参数被移除;模型通过路径和 shell 的单次调用参数 `workdir` 到达子目录。`header.cwd` 仍是不可变的原始项目:Session 身份、工作区归属和恢复目的地。`dsh-working-directory` 拥有该目录,只有一个读取接口 `get`:相对路径从该目录解析,消费方也以它作为工作区根来限定写入、文件视图和发现。服务通过 `set` 或 `ensure` 的恢复记录的每次变更都是 `workspace-root/change`。 + +`workspace-root/change` 是新增的普通事件类型,作为同版本持久化变更记录在[确认记录](../../../../docs/persistence-changes/2026-11-13-workspace-root-change.zh.md)中。`working-directory/change` 保留在事件词汇表中,已标为 deprecated,没有写入方。读者忽略已存储的这类事件:同一种事件既记录模型的 `cd`,也记录进入工作树,而已存储的 Session 很少启用工作树插件,其中大多数是 `cd`。含有这类事件的 Session 在原始项目中恢复,或在最近一条 `workspace-root/change` 的目录中恢复,下一次请求的上下文会报告该目录。旧版本拒绝含有 `workspace-root/change` 的日志;从未移动工作区的 Session 不含该事件。 + +工作树创建通过 `set` 进入检出目录。模型只有一个进入检出的工具 `enter_worktree`:名称在 Session 所在检出的池中选中一个工作树。已有的工作树通过 `ctx.worktrees.enter` 进入,没有同名工作树时通过 `ctx.worktrees.create` 新建。名称无法离开该池,因此模型仍然不能选择任意目录。`ctx.worktrees.exit` 以 `exit_worktree` 的形式提供,它找到包含 Session 目录的已记录工作树,把 Session 送回创建或进入该工作树时所在的检出。子代理的 header 保留父级的原始项目,并通过 `set` 从父级的目录或 Host 选定的目录启动。 + +每个消费方都读取这个目录。模型的文件、搜索与进程工具从它解析相对路径,用户看到的、以及描述项目的一切都以它为界:沙箱 `workspace-write` 边界、工作区文件服务与桌面文件拖拽、变更记录器、文件树、交付物、在应用中打开操作与 Session 行、新开的侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区。 + +沙箱策略不读取任何 Git 布局:它以 Session 的目录为界,只加入部署配置的目录,以及 Host 插件通过 `registerWritableRoot` 为该 Session 注册的目录。仓库的 Git 目录位于链接工作树之外,因此移入工作树之后,写入它的 Git 命令(例如 `git commit`)在 `workspace-write` 下会被拒绝,直到有授权覆盖该目录;原始项目也不再可写。为 Session 所在检出目录授权其 Git 目录,属于一个读取 Git 布局并注册该目录的独立插件,本决策将其延后。Host 对 Session 并不在其中工作的检出目录做维护时保留原来的边界:归档时移除 worktree、恢复被删除的 worktree、在源仓库中读取其分支,都在 worktree 服务与 forge 面板自己构造的策略下运行,即沿用 Session 的模式与授权、以记录中的源检出目录为根。Session 自身的根可能正是被删除的目录,而进程沙箱无法绑定缺失或正在消失的根。 + +## Alternatives considered + +**保留光标,从已登记的锚推导根。** 在变更上增加可选的 `anchor`、维护锚列表并取包含目录的最长锚,可以区分模型的 `cd` 与检出切换,代价是三个目录、一个重定位操作和一条子会话继承规则。移除唯一面向模型的移动入口之后,这种区分不再必要。 + +**从工作树插件的创建记录推导根。** 该记录是可忽略的实验性插件记录,格式迁移只尽力保留;已发布的包不能据此推导写边界。 + +**重定位时改写 header。** header 是存储、归属与权限根使用的身份元数据;[工作目录记录](2026-09-13-session-working-directory.zh.md)已否决改写它。 + +**在 `working-directory/change` 上增加可选的 `workspace` 标记。** 旧读者忽略该属性,仍能读取所有日志。但服务记录的每次变更都要带一个恒定值,缺少属性成为识别已存储变更的唯一依据;单独的事件为工作区移动命名,并让已存储的事件保持不变。 + +**通过格式迁移退役 `working-directory/change`。** 已存储的事件不带来源,迁移只能依据相邻事件逐条分类。忽略已存储的事件不需要改写日志。[兼容性规则](../../../../docs/persistence-changes/README.zh.md#compatibility-rules)只在现有判别符无法保证安全时才要求升版本。 + +**按路径进入工作树。** 模型提供的路径会把写边界移到任意已登记的工作树,除非用户逐次批准,否则这正是移除目录工具所排除的。`tools/pre-execute` 监听器可以通过审批服务请求这一批准;本决定把路径形式,以及随之而来的“从工作树内进入同级工作树”,留给之后的变更。池内的名称把边界留在检出之内。 + +**创建与进入各用一个工具。** `create_worktree` 与 `enter_worktree` 并存时,模型为“进入工作树”这一个动作面对两个工具,还要按工作树是否存在来选择。单一工具与 Claude Code 的 `EnterWorktree` 一致,后者创建工作树,或打开同名的已有工作树。在一位开发者提供过 `create_worktree` 的 79 个已记录 Session 中,模型在 6,599 次工具调用里只调用过它一次,因此移除这个名称影响的已存储 Session 很少。 + +**在调用之间保留 shell 的 `cd`。** 这是一个隐式的光标。在该开发者的 Session 中,68% 的 `cd` 前缀指向 Session 目录之外,30% 指向 Session 目录本身,限制在工作区内的保留只对约 2% 生效。 + +**两个公开读取接口。** 用 `get` 读相对路径的基准、用 `rootOf` 读工作区根,可以保留每个已存储的目录,但每个消费方都要在两个值之间做选择,而这两个值在从这个版本起启动的每个 Session 中都相等。只保留一个读取接口,就不需要这种选择。 + +**保留每个已存储的目录。** 把每条已存储的 `working-directory/change` 都读作目录,由于消费方跟随目录,已存储的模型 `cd`(包括进入用户主目录的)会成为写边界。 + +**保留原始项目之内的已存储目录。** 进入过工作树的 Session 会在工作树中恢复,但这条规则分不清工作树与 `cd`:已存储的进入子目录的 `cd` 会收窄写边界和文件视图,而位于 Session 打开目录之外的工作树会被丢弃。 + +## Consequences + +消费方通过 `get` 读取一个目录。无论 `working-directory/change` 事件记录了什么目录,已存储的 Session 都在原始项目中恢复,并从那里跟随 Host 移动。曾在工作树中工作的 Session 通过 `enter_worktree` 回到工作树;在此之前,它的相对路径在原始项目中解析。模型只能通过 `enter_worktree` 进入检出:新建的检出,或池中已登记的检出。其他位置的检出需要 Host 操作。ACP、SDK 与 Web 的生产方以规范拼写记录原始项目,因此 Host 移回原始项目时不记录变更。在链接工作树中工作的 Session,无论是进入的还是直接在其中打开的,在没有仓库 Git 目录授权时都不能在 `workspace-write` 下运行 `git commit`;在此前的边界下,进入项目内工作树的 Session 可以。SDK 的 `setWorkingDirectory` 调用以及在 Host 选定目录启动的子代理,会让 `workspace-write` 边界随目录一起移动。工作树快照夹具覆盖进入、离开和失去工作树。 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/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml new file mode 100644 index 0000000000..1eacb1f915 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for 2026-11-15-session-retain-facets-and-recent-views.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-session-retain-facets-and-recent-views.md +/agent-note-session-retain-facets-and-recently-viewed-sessions: + en: 903aecad7bc8a610 + zh: 17f8f0c420035cc1 +/agent-note-session-retain-facets-and-recently-viewed-sessions/problem: + en: 455344d0dc6aec78 + zh: cd0b86cc1cd2cbe7 +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision: + en: d1fa71821f857f8b + zh: 15308ccd85c6c25c +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/connection-and-facets: + en: 6c72ad036c9f9834 + zh: 0922647e1f58a811 +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/the-conversation-facet: + en: a6031fa553aae23b + zh: 77e534b656ae660e +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/the-draft-reference: + en: db1266225cc204e9 + zh: d786fe7fca2c783e +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/reference-sources-and-facets: + en: cb761521ca56fe93 + zh: 76f8797f4808407d +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/recently-viewed-sessions-recentviews: + en: 1af8b25948c049f2 + zh: 6444d8d9eacf6fc2 +/agent-note-session-retain-facets-and-recently-viewed-sessions/alternatives-considered: + en: 7a484119b745aee9 + zh: 3092d3dbda8397cd +/agent-note-session-retain-facets-and-recently-viewed-sessions/consequences: + en: 9ec4b80ad5f74041 + zh: f20bc50bf5e4dd2c +/agent-note-session-retain-facets-and-recently-viewed-sessions/testing: + en: 83e4d88dce18a4de + zh: 36bdf8f95c1fa373 diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md new file mode 100644 index 0000000000..ab543402e6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md @@ -0,0 +1,131 @@ +# Agent Note: Session retain facets and recently viewed Sessions + +Status: implemented + +English | [中文](2026-11-15-session-retain-facets-and-recent-views.zh.md) + +## Problem + +When the Web Client main view switched away from a Session, it released that Session's `mainView` reference. Once the reference count reached zero, the Client disposed the Session's binding, event window, and Conversation assembly state, so returning to it pulled history again. + +Keeping a Session alive is inexpensive: the event window only appends, the stream shares the one Gateway WebSocket, and Host-side subscriptions are passive. The cost lies in derived computation. [`BoundConversation`](../../../../packages/client/ui-conversation/src/client/conversation/assembly.ts) subscribed to the event window when constructed; afterwards every event, including every `assistant/live-chunk`, passed through Definition `match`/`update` folding and rAF-batched publication whether or not the Session was rendered. A retained background Session that keeps running would keep paying that cost. + +The retain interface could only express retaining or releasing the whole Session; it could not express receiving data without derived computation. + +## Decision + +This decision extends [Client Session references](2026-09-15-client-session-references.md) without superseding it: references and source counts are unchanged; `SessionRetainOptions` carries `connection` and facets, and a reference without the connection is ready once its binding exists. It replaces the draft-attachment ownership of [draft attachments across Session switches](../bug-fix/2026-11-13-draft-attachments-across-session-switches.md) with the `draft` reference. + +### Connection and facets + +A Session reference always keeps the Session object and its scope, which hold local state such as the composer draft and pending submission echoes. Two options decide what it keeps beyond that: + +```ts ignore-check +export interface SessionRetainOptions { + readonly source: SessionReferenceSource + /** Keeps the Session's own event connection and the event window it keeps current; defaults to `true`. */ + readonly connection?: boolean + /** Owner-declared facets this reference keeps computing over the Session's data; an absent key is not computed. */ + readonly facets?: Readonly>> + readonly signal?: AbortSignal | undefined +} + +export interface SessionRetainInfo { + // existing members unchanged + /** Positive counts of references retaining each facet; absent while no reference retains any facet. */ + readonly retainedFacets?: Readonly>> + /** Positive count of references keeping the event connection; absent while none does. */ + readonly connectionCount?: number +} +``` + +| Rule | Behavior | +|---|---| +| Connection | The connection is the Session's own follow stream plus the event window it keeps current, not the page transport. It opens when the first reference that keeps it is retained; when the last such reference is released while the scope remains, `Session.disconnect()` closes it, empties the window, and returns the Session to its cold state while keeping pending submission echoes; the next reference that keeps it connects as a first open | +| Facets | The owning package adds a facet to `SessionRetainFacetMap` through declaration merging; the Controller assigns no meaning to any facet. An absent key is not computed; a facet computes over the data the connection keeps, so without it there is nothing to compute | +| Buffered older pages | When the last facet is released while the connection remains, `Session.bufferOlder()` keeps only the last Turn-aligned page visible and hands the older entries to its `SessionEventStream`. The Session pages back exactly as before; the stream answers page reads from those buffered records, cut by the request's Turn window, without a request, and reads Host pages after they run out. A replaced window drops the buffer, and it leaves with the stream on resync, disconnect, or disposal. [`buffered-pages.ts`](../../../../packages/api/session-controller/src/client/sessions/buffered-pages.ts) owns the page cut | +| Counting | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) keeps one count per facet beside `connectionCount` and the per-source `retainedBy` counts in the generation's `SessionRetainInfo`; `retainInfo(id)` publishes every change, and owners derive their facet from that snapshot and the current binding, so `SessionBinding` is unchanged | +| Immutability | A reference's options are fixed at creation; changing them retains a new reference before releasing the old one | +| `using()` | Signature unchanged; borrowed references keep the connection by default and request no facet | +| `retainAgentScope` | Keeps neither the connection nor a facet | + +### The `conversation` facet + +`ui-conversation` declares `conversation`: Conversation assembly of the event window and materialization of its views. + +- `BoundConversation` remains one per binding, and its `snapshot`, `openTurn`, and `target(t)` sources keep stable identities. `UiConversation.binding()` registers the binding's disposal on the Session scope before the binding starts following, and a failed initial fold disposes the binding so the next resolution starts afresh. +- While the facet is retained, the binding folds the whole current window once, publishes it synchronously, and follows window changes; a fold that fails leaves the binding unfolded, so the next window change folds the whole window again. +- When the facet is released, the binding unsubscribes, cancels a pending rAF, drops its fold, and publishes the empty result once; registry changes while released are not applied until it is retained again. A feed dispatch already in progress checks whether the binding still follows, so a release during that dispatch stops folding immediately. +- Two computations follow the `conversation` facet: `BoundConversation` and the [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) quota listener, which neither publishes nor replays notices for failures received while the facet is not retained. + +### The `draft` reference + +The [input hub](../../../../packages/client/ui-conversation/src/client/input/hub.ts) holds a Session with `{ source: 'draft', connection: false }` while its composer draft has attachments and the Session is not removed. The scope, and with it the same composer shell and its browser-owned attachments, therefore survives every view releasing the Session; returning reconnects and refolds while the composer keeps its attachments, uploads, and failed-upload retries. Removing the last attachment, sending it, or removing the Session releases the hold, and scope teardown then releases every draft attachment. A page unload still marks the Sessions whose draft holds attachments, and the next page reports them as discarded. + +### Reference sources and facets + +| Source | Owning package | Options | +|---|---|---| +| `mainView` | declared by ui-session, retained by ui-workspace | `{ conversation: true }` | +| `sidebarView` | ui-sidebar-right | `{ conversation: true }` | +| `sidebarChat` | ui-subagent | `{ conversation: true }` | +| `recentViews` | ui-workspace | omitted: connection only | +| `draft` | ui-conversation | `{ connection: false }` | +| `using()` callers | their own packages | omitted | +| `gateway` | session-controller | internal entry without connection | +| Test fixture default | test-support/client-runtime | `{ source: 'testFixture', facets: { conversation: true } }` | + +### Recently viewed Sessions: `recentViews` + +ui-workspace [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) owns a [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts), which holds one `recentViews` reference for each recent view. + +Its state records only what the user did: the order in which Sessions left the main view and the Session the main view shows now. One idempotent `sync()` derives the Sessions to hold from that state and the current Session list, Workspace list, and Session UI status, retains the missing ones, then releases the rest. Navigation calls `show(sessionId)` after retaining the new `mainView` reference and before releasing the previous one; Session list, Workspace list, and status changes call `sync()`. Retaining publishes the Session list synchronously, so a re-entrant `sync()` only marks the state dirty and the running pass repeats until the selection is stable. + +| Rule | Behavior | +|---|---| +| Order | Both `mainView` references are held while `show()` syncs, so the previous Session moves to the recent views before its `mainView` reference is released and its reference count never reaches zero; the main-view Session is never a recent view, and reselecting it leaves the selection unchanged | +| Blank | A Session still blank when the main view leaves it does not enter | +| Failure | A failed retention is reported to the console once and the Session leaves the order, so it is released with its `mainView` reference; navigation continues | +| Exit | A removed, archived, or evicted Session leaves the order and returns only when the main view leaves it again | +| Attention | A Session that is running, awaits the user, or has an unread completion, as the unified Session UI status reports, is neither counted nor evicted; once it is read and idle it counts again | +| Limit | The ui-workspace `recentViewLimit` configuration, 10 by default, counted Sessions besides the main-view Session; a volatile Host `Config` field the browser receives through [synced plugin configuration](2026-11-15-client-config-sync.md), so a change applies without a reload and Sessions already evicted do not return | +| Eviction | Beyond the limit, the least recently left unpinned Session is evicted first, then the least recently left pinned one; the list is checked again whenever the Session list, Workspace list, or Session UI status changes | +| Disposal | Plugin disposal unsubscribes from both lists and the status, clears the order, and releases every reference | + +## Alternatives considered + +**Decide following by subscriber count.** `BoundConversation` would fold only while subscribed and catch up synchronously on cold reads. React renders before it subscribes, so following would depend on read-time catch-up to avoid a stale first frame, and whether computation runs would follow incidental subscription timing rather than the owner's intent. + +**Split reference sources into render and hold classes.** This expresses only one switch; an independently counted part such as a draft would need another classification. + +**Owner-declared facet defaults at runtime.** This requires a Controller runtime registry plus recounting across load order and HMR, while the rule that an omitted facet is not retained suffices. + +**Expose a facet observable on `SessionBinding`.** A new required `SessionBinding` member breaks every hand-built binding, including third-party test fakes, while facet counts are local reference counts that `retainInfo` already publishes beside the per-source counts. + +**Retention levels instead of facets.** A fixed `state`, `cache`, `live` enumeration cannot grow with later owner needs, while a default-on `connection` plus owner facets expresses the same three states. + +**Keep the last fold after the facet is released.** A stale result with no owner adds a hidden state; the window stays, and folding only its last page on return is cheap. + +**Root-level draft-attachment ownership.** Recording owners in the Conversation service and re-adopting them in a new composer duplicates Session lifetime tracking with a catalog watch; holding the scope keeps the composer itself. + +**Keep background Session DOM.** React 18 has no ``; K hidden subtrees pay layout, memory, and subscription costs and conflict with the single-Session `session-maybe` binding. + +**Keep folding while unretained and only defer publication.** The `match`/`update` cost of stream chunks remains. + +**Compute a bespoke difference between the folded inputs and the window.** One attempt can start, stream, and settle entirely while unretained, which makes such difference logic error-prone; returning folds the last page from scratch instead. + +## Consequences + +- A recent view switches back without a history request and folds only its last page; paging back through pages already loaded makes no request. +- A recent view keeps its whole loaded window in memory; it keeps no Conversation fold. +- A Session evicted from the recent views with draft attachments keeps its composer but not its window, so returning to it requests history again. +- The attention-protected recent views have no upper bound: an unread completion stays protected until the user reads it, so each Session that finishes unread while the user is elsewhere keeps its generation, loaded event window, and history follow stream until it is read, marked read, removed, or archived. +- A rendering owner that omits `conversation: true` sees an unretained stale or empty snapshot without an error. +- `SessionRetainOptions` and `SessionRetainInfo` gain optional fields only; a third-party Client plugin that renders a Session it retains under its own source must add `facets: { conversation: true }`, and a plugin that only needs local state may pass `connection: false`, which the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md) describes. + +## Testing + +- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) covers per-facet and connection counting, holding a Session without connecting it, disconnecting after the last connected reference, buffering older pages after the last facet, and counts ending with the generation and root disposal; [session.client.spec.ts](../../../../packages/api/session-controller/tests/session.client.spec.ts) covers buffered-page paging, Turn jumps, Host paging after buffered pages, buffering again after live growth, and disconnect then reconnect. +- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) covers dropping the fold on release, one synchronous fold on retention, equality with continuous following, activation and registry changes while not following, a release during an in-progress dispatch, a cancelled rAF publication, a failed fold, and a failed initial fold leaving no subscription; [draft-attachment-retention.client.spec.ts](../../../../packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts) covers the `draft` reference, its release, removed Sessions, and unload marks. +- [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) covers quota notices publishing only while the facet is retained. +- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) and [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) cover the attention and pin rules, synchronous re-entrancy during retention, the main-view Session staying out of the count, eviction without automatic return, configuration, list-driven reconciliation, and returning to a recent view through the same generation without reopening history. diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md new file mode 100644 index 0000000000..a79310566f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md @@ -0,0 +1,131 @@ +# Agent Note: Session retain 子要素与最近访问会话 + +Status: implemented + +[English](2026-11-15-session-retain-facets-and-recent-views.md) | 中文 + +## 问题 + +Web Client 的主视图切走一个 Session 时,会释放该 Session 的 `mainView` 引用。引用计数归零后,Client 销毁该 Session 的 binding、事件窗口和 Conversation 折叠状态,切回时只能重新拉取历史。 + +保住 Session 本身代价不高:事件窗口只追加,数据流复用同一条 Gateway WebSocket,Host 侧订阅是被动的。真正的开销在派生计算。[`BoundConversation`](../../../../packages/client/ui-conversation/src/client/conversation/assembly.ts) 在构造时就订阅事件窗口,此后不论 Session 是否被渲染,每个事件(包括每个 `assistant/live-chunk`)都要经过 Definition 的 `match`/`update` 折叠,并按 rAF 合批发布。被保住的后台 Session 只要仍在运行,就会一直付出这笔计算。 + +retain 接口只能表达保住或释放整个 Session,无法表达「只收数据,不做派生计算」。 + +## 决策 + +本决策扩展 [Client Session 引用](2026-09-15-client-session-references.zh.md),但不取代它:引用与来源计数不变;`SessionRetainOptions` 携带 `connection` 与子要素,不保留连接的引用在 binding 建好时即就绪。它以 `draft` 引用取代 [跨会话切换保留草稿附件](../bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md) 中的草稿附件归属机制。 + +### 连接与子要素 + +Session 引用始终保活 Session 对象及其作用域,作用域上保存草稿、发送回显等本地状态。两个选项决定在此之外还保留什么: + +```ts ignore-check +export interface SessionRetainOptions { + readonly source: SessionReferenceSource + /** Keeps the Session's own event connection and the event window it keeps current; defaults to `true`. */ + readonly connection?: boolean + /** Owner-declared facets this reference keeps computing over the Session's data; an absent key is not computed. */ + readonly facets?: Readonly>> + readonly signal?: AbortSignal | undefined +} + +export interface SessionRetainInfo { + // existing members unchanged + /** Positive counts of references retaining each facet; absent while no reference retains any facet. */ + readonly retainedFacets?: Readonly>> + /** Positive count of references keeping the event connection; absent while none does. */ + readonly connectionCount?: number +} +``` + +| 规则 | 行为 | +|---|---| +| 连接 | 连接指 Session 自己的 follow 流及其维持最新的事件窗口,不是页面传输连接。第一个保留连接的引用出现时建立;作用域仍在而最后一个保留连接的引用被释放时,`Session.disconnect()` 关闭连接、清空窗口,并让 Session 回到 cold 状态,发送回显保留;下一个保留连接的引用按首次打开的流程重新连接 | +| 子要素 | owner 包通过声明合并把子要素加入 `SessionRetainFacetMap`;Controller 不赋予任何子要素含义。未写的键不计算;子要素基于连接保有的数据计算,没有数据就无从计算 | +| 缓冲的更早页 | 连接仍在而最后一个子要素被释放时,`Session.bufferOlder()` 只让按 Turn 对齐的最后一页可见,并把更早的条目交给它的 `SessionEventStream`。Session 的翻页逻辑不变;stream 读页时先按请求的 Turn 窗口从这些缓冲记录中切一页返回,不发请求,用完后再读 Host 分页。窗口被整体替换时丢弃缓冲,resync、断开或销毁时随 stream 一起丢弃。[`buffered-pages.ts`](../../../../packages/api/session-controller/src/client/sessions/buffered-pages.ts) 负责分页切点 | +| 计数 | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) 在 generation 的 `SessionRetainInfo` 中为每个子要素记一个计数,与 `connectionCount` 和按来源的 `retainedBy` 并列;`retainInfo(id)` 发布每次变化,owner 根据该快照与当前 binding 推导自己的子要素,因此 `SessionBinding` 不变 | +| 不可变 | 一条引用的选项在创建时固定;更改时先 retain 新引用,再 release 旧引用 | +| `using()` | 签名不变;借出的引用默认保留连接,不请求子要素 | +| `retainAgentScope` | 既不保留连接,也不保留子要素 | + +### `conversation` 子要素 + +`ui-conversation` 声明 `conversation`:对事件窗口做 Conversation 折叠并物化其视图。 + +- `BoundConversation` 仍然每个 binding 一个,其 `snapshot`、`openTurn` 和 `target(t)` 数据源保持对象标识稳定。`UiConversation.binding()` 先在 Session 作用域上登记该绑定的清理,再让绑定开始跟随;首次折叠失败时清理该绑定,下次解析重新开始。 +- 子要素被保留期间,绑定对当前整个窗口折叠一次、同步发布,并跟随窗口变化;折叠失败时绑定保持未折叠,下一次窗口变化重新整窗折叠。 +- 子要素被释放时,绑定退订、取消待发的 rAF、丢弃折叠结果,并发布一次空结果;释放期间的注册表变化要等再次保留时才生效。正在进行的事件分发会检查绑定是否仍在跟随,因此分发中途的释放会立即停止折叠。 +- 跟随 `conversation` 子要素的计算有两项:`BoundConversation` 与 [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) 的 quota 监听;后者对子要素未被保留期间收到的失败既不发布也不补发提示。 + +### `draft` 引用 + +[输入 hub](../../../../packages/client/ui-conversation/src/client/input/hub.ts) 在某个 Session 的输入框草稿有附件且该 Session 未被移除时,以 `{ source: 'draft', connection: false }` 持有它。因此所有视图都释放该 Session 后,作用域以及同一个输入框 shell 和其中的浏览器侧附件仍然保留;切回时重新连接并重新折叠,输入框保留附件、上传进度和失败上传的重试。移除最后一个附件、发送它或移除 Session 会释放这条引用,随后作用域销毁时释放全部草稿附件。页面卸载时仍为草稿有附件的 Session 写标记,下一个页面提示这些附件已失效。 + +### 引用来源与子要素 + +| 来源 | 所属包 | 选项 | +|---|---|---| +| `mainView` | ui-session 声明,ui-workspace 调用 | `{ conversation: true }` | +| `sidebarView` | ui-sidebar-right | `{ conversation: true }` | +| `sidebarChat` | ui-subagent | `{ conversation: true }` | +| `recentViews` | ui-workspace | 不写:只保连接 | +| `draft` | ui-conversation | `{ connection: false }` | +| `using()` 调用方 | 各自的包 | 不写 | +| `gateway` | session-controller | 不保留连接的内部入口 | +| 测试替身默认值 | test-support/client-runtime | `{ source: 'testFixture', facets: { conversation: true } }` | + +### 最近访问会话 `recentViews` + +ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) 持有一个 [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts),为每个最近访问会话持有一条 `recentViews` 引用。 + +它的状态只记录用户做过什么:Session 离开主视图的顺序,以及主视图当前显示的 Session。一个幂等的 `sync()` 根据这些状态和当前的 Session 列表、Workspace 列表与 Session UI 状态算出应持有的 Session,先 retain 缺少的,再释放其余的。导航在 retain 新的 `mainView` 引用之后、释放上一个之前调用 `show(sessionId)`;Session 列表、Workspace 列表和状态变化时调用 `sync()`。retain 会同步发布 Session 列表,因此重入的 `sync()` 只标记状态已变化,正在执行的一轮会重复,直到选择稳定。 + +| 规则 | 行为 | +|---|---| +| 顺序 | `show()` 同步时两个 `mainView` 引用都还在,因此上一个 Session 先成为最近访问会话、再释放其 `mainView` 引用,引用计数不会归零;主视图 Session 永远不是最近访问会话,重复选中它时选择保持不变 | +| 空白 | 离开时仍是空白的 Session 不入队 | +| 失败 | retain 失败时报告到控制台一次,该 Session 离开顺序列表,随其 `mainView` 引用一起释放;导航继续 | +| 出队 | 被移除、归档或淘汰的 Session 离开顺序列表,只有主视图再次离开它时才会回来 | +| 关注 | 统一 Session UI 状态显示为运行中、等待用户或完成未读的 Session 既不计数也不淘汰;读过且空闲后重新计数 | +| 上限 | 由 ui-workspace 配置 `recentViewLimit` 决定,默认 10,计数的 Session 不含主视图 Session;它是 Host `Config` 的 volatile 字段,浏览器经[前端插件配置同步](2026-11-15-client-config-sync.zh.md)接收,修改后无需刷新即生效,已淘汰的 Session 不会回来 | +| 淘汰 | 超出上限时先淘汰最早离开的未置顶 Session,再淘汰最早离开的置顶 Session;Session 列表、Workspace 列表或 Session UI 状态变化时都会重新检查 | +| 卸载 | 插件卸载时退订两个列表与状态,清空顺序列表,并释放全部引用 | + +## 备选方案 + +**按订阅数决定是否跟随。** `BoundConversation` 只在有订阅时折叠,冷态读取时同步补齐。React 先渲染后订阅,跟随要靠读取时补齐来避免首帧陈旧,而且是否计算取决于偶然的订阅时序,而不是持有方的意图。 + +**把引用来源分成 render 与 hold 两类。** 这只能表达一个开关;草稿这类独立计数的部分还需要另一种分类。 + +**由子要素 owner 在运行时声明默认值。** 这需要 Controller 维护运行时注册表,并在加载顺序与 HMR 下重新计数;而「未写即不保留」的规则已经足够。 + +**在 `SessionBinding` 上暴露子要素 observable。** `SessionBinding` 新增必需成员会让所有手写 binding(包括第三方测试替身)失效,而子要素计数本就是本地引用计数,`retainInfo` 已在按来源计数旁发布它们。 + +**用固定级别代替子要素。** 固定的 `state`、`cache`、`live` 枚举无法随后续 owner 诉求扩展,而默认开启的 `connection` 加上 owner 子要素就能表达这三种状态。 + +**释放子要素后保留最后一次折叠结果。** 无主的陈旧结果会多出一个隐含状态;窗口仍在,切回时只折叠最后一页的代价很小。 + +**在根级维护草稿附件归属。** 在 Conversation 服务中记录归属并在新输入框中重新接回,等于用会话目录监听重复跟踪 Session 生命周期;保住作用域就能保住输入框本身。 + +**保留后台 Session 的 DOM。** React 18 没有 ``;K 个隐藏子树要付出布局、内存和订阅成本,还与 `session-maybe` 只绑定一个 Session 的设计冲突。 + +**未被保留时继续折叠,只推迟发布。** 流式块的 `match`/`update` 成本仍然存在。 + +**自行计算已折叠输入与窗口之间的差集。** 未被保留期间,一次 attempt 可能从开始、流式到 settle 全部完成,这类差集逻辑容易出错;切回时改为从头折叠最后一页。 + +## 后果 + +- 最近访问会话切回时无需历史请求,只折叠最后一页;往上翻阅已加载的页不发请求。 +- 最近访问会话在内存中保留其完整的已加载窗口,但不保留 Conversation 折叠结果。 +- 带草稿附件被淘汰出最近访问会话的 Session 保留输入框,但不保留窗口,切回时要重新请求历史。 +- 受关注保护的最近访问会话没有总量上限:完成未读会一直受保护直到用户读过,因此用户不在时每个以未读状态完成的 Session 都会保留其 generation、已加载的事件窗口和历史跟随流,直到被读过、标为已读、被移除或归档。 +- 漏写 `conversation: true` 的渲染方会看到未被保留的陈旧或空快照,不会报错。 +- `SessionRetainOptions` 与 `SessionRetainInfo` 只新增可选字段;以自己的来源 retain 并渲染 Session 的第三方 Client 插件需加上 `facets: { conversation: true }`,只需本地状态的插件可写 `connection: false`,见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md)。 + +## 测试 + +- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) 覆盖按子要素与连接计数、不建立连接地持有 Session、最后一个保留连接的引用释放后断开、最后一个子要素释放后缓冲更早页,以及计数随 generation 退役与根释放结束;[session.client.spec.ts](../../../../packages/api/session-controller/tests/session.client.spec.ts) 覆盖缓冲页翻页、Turn 跳转、缓冲页用完后的 Host 分页、实时增长后再次缓冲,以及断开后重新连接。 +- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) 覆盖释放时丢弃折叠、保留时同步折叠一次、与持续跟随结果一致、未跟随期间的激活与注册表变化、分发中途的释放、被取消的 rAF 发布、折叠失败,以及首次折叠失败不残留订阅;[draft-attachment-retention.client.spec.ts](../../../../packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts) 覆盖 `draft` 引用、其释放、被移除的 Session 与卸载标记。 +- [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) 覆盖 quota 提示只在子要素被保留时发布。 +- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) 与 [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) 覆盖关注与置顶规则、retain 期间的同步重入、主视图 Session 不计数、淘汰后不自动回来、配置、由列表变化驱动的对账,以及经由同一 generation 切回最近访问会话且不重新打开历史。 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..bf3ab5ad3d --- /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: 3b2603721398054c + zh: 7d2e5f3be236f1d3 +/agent-note-draft-attachments-across-session-switches/alternatives-considered: + en: 01a406120acfc8b9 + zh: 17a3fd9be7a303fb +/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..3c45613f1d --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -0,0 +1,27 @@ +# 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 + +**A draft with attachments holds its Session's scope.** While a composer draft has attachments and its Session is not removed, the input hub holds the Session with a `draft` reference that keeps no event connection, as [Session retain facets and recently viewed Sessions](../architecture/2026-11-15-session-retain-facets-and-recent-views.md) defines. Switching away and evicting the Session from the recent views therefore keep the same composer shell and its attachments: an active upload keeps running, a failed upload keeps its in-place retry, and a pasted image keeps its bytes in memory. Removing the last attachment, sending it, or removing the Session releases the hold; scope teardown then releases every attachment the draft still holds. + +**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session whose draft holds attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark 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. + +**Recording draft-attachment owners in the Conversation service and re-adopting them in the next composer.** It keeps attachments without holding the scope, but it tracks Session lifetime a second time through a catalog watch and splits submission release across composer phases; holding the scope keeps the composer itself. + +**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..e6a29cd8fe --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -0,0 +1,27 @@ +# Agent Note:草稿附件跨会话切换 + +Status: implemented + +[English](2026-11-13-draft-attachments-across-session-switches.md) | 中文 + +## 问题 + +切到另一个会话再切回时,输入框的附件栏被清空,文字却还在(issue #5070)。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。 + +## 决策 + +**带附件的草稿持有其会话的作用域。** 输入框草稿有附件且其会话未被删除时,输入 hub 以不保留事件连接的 `draft` 引用持有该会话,见 [Session retain 子要素与最近访问会话](../architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md)。因此切走以及从最近访问会话中被淘汰时,同一个输入框 shell 和其中的附件都会保留:进行中的上传继续进行,失败的上传保留原位重试,粘贴的图片把字节保留在内存中。移除最后一个附件、发送它或删除会话会释放这条引用;随后作用域销毁时释放草稿仍持有的全部附件。 + +**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个草稿持有附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记的输入框会显示「请重新添加」提示。 + +## 考虑过的替代方案 + +**刷新后通过浏览器 durable 引用与 Host `restore` Remote 恢复附件。** 它能在页面刷新后找回已上传的文件和图片,但需要新增一个 Host Remote 及其 Liveshare 与目录分类、一种浏览器持久化格式、恢复期间的发送拦截和图片字节载荷。主要用户所在的桌面端收益很小:桌面端 Host 每次启动都绑定新端口,存储 origin 连同所有已存引用都无法跨应用重启保留。 + +**在 Conversation 服务中记录草稿附件归属,并在下一个输入框中接回。** 它不持有作用域也能保留附件,但要通过会话目录监听再跟踪一遍 Session 生命周期,并按输入框阶段拆分已提交附件的释放;持有作用域就能保住输入框本身。 + +**切换时释放已结算附件,切回时由 Host 恢复。** 它能在会话不显示期间省下粘贴图片的内存,但每次切回都需要一次 Host 往返,弱网下会失败,并且之后还要再分配同样的字节。 + +## 影响 + +切换会话从不访问 Host,因此弱网不会让草稿附件在切换中丢失。刷新或崩溃仍会丢弃附件;崩溃时不会写标记,因此没有提示。 diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml index 5736f23e73..5d4953709e 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml @@ -18,8 +18,8 @@ en: 16c4ee08b65ead23 zh: df80d6e49982615b /agent-note-parallel-tool-call-execution-by-per-call-safety/configuration-and-declarations: - en: 082e5a02b092b656 - zh: ca674a08323d8cc1 + en: 5ef62a9b07a857eb + zh: 931f648655a0cb34 /agent-note-parallel-tool-call-execution-by-per-call-safety/verification: en: 20d0e1724ebc1247 zh: baa89694cea135c8 diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md index 03e35dba6b..dd5a0669c6 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md @@ -62,7 +62,7 @@ Any shared state touched during execution must be concurrency-safe. This include The shipped declarations are conservative. Web search, web fetch, filesystem read, glob, grep, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Read-only queries also opt in: the background job list, the subagent tree and model listings, scheduled task and Team task reads, Cordis Inspect queries, and MCP resource reads. Filesystem writes and edits, bash tools, `job_output` because it consumes a read cursor, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive. Read-only `lsp` stays exclusive because its language-server pool already serializes queries per workspace, so overlap would gain nothing, and the goal tools stay exclusive under the [goal tools Agent Note](2026-07-19-model-facing-goal-tools.md). -Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `working-directory/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session. +Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `workspace-root/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session. ## Verification diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md index 38db00b5ff..ace1167802 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md @@ -62,7 +62,7 @@ Status: implemented 当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、glob、grep、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。只读查询也选择并行:后台任务列表、subagent 树与模型列表、定时任务与 Team 任务读取、Cordis Inspect 查询以及 MCP 资源读取。文件系统写入与编辑、bash 工具、`job_output`(因为它会消费读取游标)、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。只读的 `lsp` 仍按独占方式执行,因为其语言服务器池已按工作区串行化查询,重叠执行不会带来收益;goal 工具依照 [goal 工具 Agent Note](2026-07-19-model-facing-goal-tools.zh.md) 仍按独占方式执行。 -文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `working-directory/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。 +文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `workspace-root/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。 ## 验证 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-09-13-explicit-worktree-creation.i18n.yaml b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml index 201593ebbe..6a8511eee5 100644 --- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml @@ -9,8 +9,8 @@ en: 12ab239ab0c58e31 zh: c32874442ce66041 /agent-note-explicit-worktree-creation/decision: - en: 571a2d4c5352170b - zh: aeb12b849c5f8d31 + en: 98289c9b859516cd + zh: ac45d0997966840b /agent-note-explicit-worktree-creation/alternatives-considered: en: 72d42e892a37b94c zh: 92a14a51c6a89c53 diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md index 9facc68061..6fe421dab8 100644 --- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md +++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md @@ -10,7 +10,7 @@ A Session that needs an isolated checkout otherwise has to coordinate Git comman ## Decision -The experimental [worktree runtime](../../../../packages/experimental/worktree/README.md) creates a new named branch and checkout from a pinned local commit, then enters its canonical directory through the shared working-directory service. The [tool](../../../../packages/experimental/tool-worktree/README.md) exposes `create_worktree({ name?, from? })`. These packages use ordinary explicit composition, with no additional runtime feature flag. +The experimental [worktree runtime](../../../../packages/experimental/worktree/README.md) creates a new named branch and checkout from a pinned local commit, then enters its canonical directory through the shared working-directory service. The [tool](../../../../packages/experimental/tool-worktree/README.md) exposes it as `enter_worktree({ name?, from? })`, which also enters an existing worktree of that name. These packages use ordinary explicit composition, with no additional runtime feature flag. The source repository comes from the calling Session's current directory. Creation does not fetch or copy uncommitted files. The default pool is `.agents/worktrees` under the current checkout’s top-level directory, including when the caller is in a linked checkout. The process that creates a pool writes its self-ignoring `.gitignore`; existing directories and ignore files are preserved. Names must be new branches and unused checkout paths. diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md index bc9fc0670c..2baafd7af8 100644 --- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md +++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md @@ -10,7 +10,7 @@ Status: implemented ## Decision -实验性[工作树运行时](../../../../packages/experimental/worktree/README.zh.md)从固定的本地提交创建新的具名分支与检出目录,然后通过共享工作目录服务进入其规范路径。[工具](../../../../packages/experimental/tool-worktree/README.zh.md)公开 `create_worktree({ name?, from? })`。这些包使用普通的显式组合,不添加额外运行时功能开关。 +实验性[工作树运行时](../../../../packages/experimental/worktree/README.zh.md)从固定的本地提交创建新的具名分支与检出目录,然后通过共享工作目录服务进入其规范路径。[工具](../../../../packages/experimental/tool-worktree/README.zh.md)以 `enter_worktree({ name?, from? })` 公开它,同名工作树已存在时进入该工作树。这些包使用普通的显式组合,不添加额外运行时功能开关。 源仓库由调用 Session 的当前目录决定。创建操作不会获取远端提交或复制未提交文件。默认父目录是当前检出目录顶层路径下的 `.agents/worktrees`,调用方位于链接检出目录中时也一样。创建该目录的进程写入忽略自身的 `.gitignore`;已有目录与忽略文件保持不变。名称必须对应新分支与尚未使用的检出路径。 diff --git a/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.i18n.yaml b/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.i18n.yaml new file mode 100644 index 0000000000..864ca254c9 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-08-mcp-on-demand-tool-loading.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.md +/agent-note-on-demand-mcp-tool-loading: + en: f3ae8820249277c7 + zh: e93dfdb03fbf1788 +/agent-note-on-demand-mcp-tool-loading/problem: + en: 8b6051ee3006e42d + zh: b54399f1a65c6751 +/agent-note-on-demand-mcp-tool-loading/decision: + en: d6ad94daf6a36798 + zh: c243547d88d752be +/agent-note-on-demand-mcp-tool-loading/alternatives-considered: + en: eb073fc5dfd6692d + zh: 51e842eae3fe7c61 +/agent-note-on-demand-mcp-tool-loading/testing: + en: 22966b6f3a05d7bd + zh: 1bf76080026d447f +/agent-note-on-demand-mcp-tool-loading/consequences: + en: 2a4e348e3e43fe78 + zh: c7fdb56494f2bef3 diff --git a/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.md b/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.md new file mode 100644 index 0000000000..5042da4e05 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.md @@ -0,0 +1,53 @@ +# Agent Note: On-demand MCP tool loading + +Status: implemented + +English | [中文](2026-10-08-mcp-on-demand-tool-loading.zh.md) + +## Problem + +A connected MCP server sends every tool definition with every request. Notion's hosted server advertises 46 tools whose definitions total about 214,500 characters; one tool's input schema alone is about 83,000 characters. A Notion plugin that only registers the server therefore costs that context on every request, before the model uses a single Notion tool. + +The existing `ToolSchema.deferLoading` marker does not solve this. Only routes that declare `toolUpdate` honor it, and the default `deepseek-flash` entry is the only catalog route that does. The marker keeps a prefix reusable; it does not reduce context. + +## Decision + +An mcp-client entry with `toolLoading: on-demand` keeps the server's tools out of the tool registry. The behavior lives in mcp-client; no session event, message type, or other package changes, and mcp-manager only passes the field to its instances. + +**One loader per server.** The server registers `mcp____load_tools` where an eager server registers its tools, and withdraws it where an eager server removes them, so outages and reconnects follow the eager lifecycle. A server tool named `load_tools` is left out of the catalog with a logged warning. + +**The catalog is a system prompt section.** The `mcp::tools` section lists each tool's raw name with the first line of its description, capped by `catalogDescriptionMaxLength`, and renders only for an agent that sees the loader. The session log already records the system prompt, so the catalog needs no new message type, and it changes only when the server's tool list does. + +**Loading registers in the agent's own scope.** The loader validates every requested raw name before registering any, then registers the definitions in a scope the plugin creates for that agent. The plugin releases the scope on `agent/disposed`, and plugin unload disposes it. The next request header carries the definitions, and the agent loop records the addition. Subagents, forks, and resumed sessions start with no loaded tools. + +**Each published generation carries loaded tools forward.** A tool definition calls the client of the generation that built it, so a reconnect must replace loaded definitions. Each published generation re-registers every agent's loaded names that it still offers and drops the rest. A failed re-registration drops only that agent's tool and logs the failure. + +**The loader decides access.** Tool restrictions filter only inherited tools, so seeing the loader permits loading any listed tool, as seeing `skill` permits loading any listed skill. Execution guards and permissions still apply. + +## Alternatives considered + +**A shared `load_mcp_tools` tool in mcp-resources with a session catalog message.** Rejected after implementation: it needed a cross-package catalog interface, a Host-wide-only restriction, an `agent/pre-step` listener that scanned session history on every step of every agent, and a persisted message type. + +**The catalog in the loader's tool description.** Rejected: OpenAI and Azure OpenAI Chat Completions reject tool descriptions longer than 1024 characters, pi-ai routes pass descriptions through unchanged, and a catalog of a dozen tools exceeds that limit. + +**A static `includeTools` list per entry.** Rejected: each plugin must choose its tools ahead of time, and the model cannot use the other tools during a session. + +**A proxy tool `call_mcp_tool(server, tool, args)`.** Rejected: the tool list never changes, but the model loses each tool's argument schema, and permissions, presentation, and guards that match tool names would need forwarding. + +**Mark MCP tools with `deferLoading`.** Rejected: it saves no context and works only on routes that declare `toolUpdate`. + +**Global registration hidden per agent with `tools.restrict({ deny })`.** Rejected: every agent needs a restriction scope, and every tool change rescans the registry and copies every schema. + +**Restore loaded tools on resume.** Rejected: it needs a durable record of loaded names, which is a session format change. The agent loop already records which tools a resumed session lost. + +## Testing + +mcp-client specs cover the loader-only registration and the prompt catalog, catalog omission for agents that cannot see the loader, loading into one agent's scope, invalid loads, carrying loaded tools across generations, withdrawal and restoration, agent release, a contained re-registration failure, the excluded `load_tools` server tool, a loader-name conflict, and the plugin path from load through call to unload. A manager spec mounts an on-demand entry. The `mcp-tool-loading` session snapshot pins the catalog section, the loader schema, the tool-addition record, and a call after loading. + +## Consequences + +- An on-demand server costs the loader definition and one catalog line per tool until an agent loads tools. +- Each load changes the next request's tool list. Routes declaring tool updates keep the earlier prefix; other routes start a new request series once per load. +- The model needs one extra tool call before using a server's tools. +- Agent tool restrictions do not filter loaded tools; `tools.guard` denies a loadable tool by name. +- A PTC program sees a tool loaded inside `run_code` only from the next program. diff --git a/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.zh.md b/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.zh.md new file mode 100644 index 0000000000..35f1451c26 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-08-mcp-on-demand-tool-loading.zh.md @@ -0,0 +1,53 @@ +# Agent Note: On-demand MCP tool loading + +Status: implemented + +[English](2026-10-08-mcp-on-demand-tool-loading.md) | 中文 + +## Problem + +已连接的 MCP 服务器会在每次请求中发送全部工具定义。Notion 托管服务器提供 46 个工具,定义合计约 214,500 字符;其中一个工具的输入 schema 就约有 83,000 字符。因此,只注册服务器的 Notion 插件在模型使用任何 Notion 工具之前,就会让每次请求都承担这部分上下文。 + +现有的 `ToolSchema.deferLoading` 标记解决不了这个问题。只有声明了 `toolUpdate` 的路由才会遵循它,而目录中只有默认的 `deepseek-flash` 条目声明了。该标记能保留可复用的前缀,但不会减少上下文。 + +## Decision + +配置 `toolLoading: on-demand` 的 mcp-client 条目不把服务器的工具注册到工具注册表。该行为位于 mcp-client 内部;不改动会话事件、消息类型或其他包,mcp-manager 只把该字段传给它的实例。 + +**每个服务器一个加载器。** 服务器在 eager 服务器注册工具的位置注册 `mcp____load_tools`,并在 eager 服务器移除工具的位置撤下它,因此断线与重连遵循 eager 的生命周期。服务器自己名为 `load_tools` 的工具不列入目录,并记录一条警告。 + +**目录是一个系统提示词段落。** `mcp::tools` 段落列出每个工具的原始名称及其描述的第一行,长度以 `catalogDescriptionMaxLength` 为上限,并且只对能看到加载器的 agent 渲染。会话日志本来就记录系统提示词,所以目录不需要新的消息类型;只有服务器的工具列表变化时目录才会变化。 + +**加载注册到 agent 自己的作用域。** 加载器先校验所有请求的原始名称,再注册任何工具;随后把这些定义注册到插件为该 agent 创建的作用域中。插件在 `agent/disposed` 时释放该作用域,插件卸载时也会释放它。下一次请求头带上这些定义,agent loop 记录这次添加。子 agent、fork 和恢复的会话开始时都没有已加载的工具。 + +**每个发布的注册代都会延续已加载的工具。** 工具定义调用的是构建它的那一代连接的 client,因此重连后必须替换已加载的定义。每次发布注册代时,会为每个 agent 重新注册该代仍提供的已加载名称,并丢弃其余名称。重新注册失败只丢弃该 agent 的这个工具,并记录失败。 + +**加载器决定访问权限。** 工具限制只过滤继承的工具,因此能看到加载器就能加载目录中的任何工具,就像能看到 `skill` 就能加载目录中的任何 skill。执行 guard 与权限检查照常生效。 + +## Alternatives considered + +**在 mcp-resources 中放一个共享的 `load_mcp_tools` 工具,并发布会话目录消息。** 实现后否决:它需要跨包的目录接口、只支持 Host 级服务器的限制、在每个 agent 的每一步都扫描会话历史的 `agent/pre-step` 监听器,以及一种持久化消息类型。 + +**把目录放进加载器的工具描述。** 否决:OpenAI 与 Azure OpenAI 的 Chat Completions 会拒绝超过 1024 字符的工具描述,pi-ai 路由原样传递描述,而十几个工具的目录就会超过这个上限。 + +**每个条目一个静态 `includeTools` 列表。** 否决:每个插件都必须预先选定工具,会话中模型无法使用其他工具。 + +**代理工具 `call_mcp_tool(server, tool, args)`。** 否决:工具列表从不变化,但模型失去每个工具的参数 schema,按工具名匹配的权限、展示与 guard 都需要转发。 + +**给 MCP 工具加 `deferLoading` 标记。** 否决:它不节省上下文,且只在声明 `toolUpdate` 的路由上生效。 + +**全局注册,再用 `tools.restrict({ deny })` 按 agent 隐藏。** 否决:每个 agent 都需要一个限制作用域,每次工具变化都会重新扫描注册表并复制每个 schema。 + +**恢复会话时恢复已加载的工具。** 否决:这需要持久记录已加载的名称,也就是改动会话格式。agent loop 已经会记录恢复的会话失去了哪些工具。 + +## Testing + +mcp-client 规格覆盖:只注册加载器与提示词目录、看不到加载器的 agent 不渲染目录、加载到单个 agent 的作用域、无效加载、跨注册代延续已加载工具、撤下与恢复、释放 agent、限定在单个 agent 的重新注册失败、被排除的 `load_tools` 服务器工具、加载器名称冲突,以及从加载、调用到卸载的插件路径。一个 manager 规格挂载按需条目。`mcp-tool-loading` 会话快照固定目录段落、加载器 schema、工具添加记录,以及加载后的一次调用。 + +## Consequences + +- 在 agent 加载工具之前,按需服务器的开销是加载器定义加每个工具一行目录。 +- 每次加载都会改变下一次请求的工具列表。声明了工具更新的路由保留之前的前缀;其他路由每次加载开始一个新的请求序列。 +- 模型在使用服务器的工具之前需要多一次工具调用。 +- agent 的工具限制不过滤已加载的工具;用 `tools.guard` 可按名称禁止可加载的工具。 +- PTC 程序要到下一个程序才能看到在 `run_code` 内加载的工具。 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 83daa37ac0..c07882cc9d 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: 5d2dc730467e4bf3 + zh: 4aca28691504cd7b /agent-note-change-request-panel-and-worktree-sessions/deferred: en: 32ef8af85f4d2f66 zh: b82b67f94346399e 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 32b6fb4edc..a21fbba569 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -10,11 +10,11 @@ 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. -The Remote inspects the checkout through the Session's subprocess provider under its [resolved permissions and query restrictions](../bug-fix/2026-10-28-forge-git-session-permissions.md), so it reads what the Session's commands see. Inspection reads the top-level, Git, and common Git directories, the branch or the abbreviated HEAD commit, the upstream, the remotes, and the size of the branch's changes against its fork point. It runs when a Session is followed, after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and on refresh, one at a time with one trailing rerun. +The Remote inspects the checkout through the Session's subprocess provider under its [resolved permissions and query restrictions](../bug-fix/2026-10-28-forge-git-session-permissions.md), so it reads what the Session's commands see. Inspection reads the top-level, Git, and common Git directories, the branch or the abbreviated HEAD commit, the upstream, the remotes, and the size of the branch's changes against its fork point. It runs when a Session is followed, after each `workspace-root/change`, `tool/result`, and `sandbox/mode` event, and on refresh, one at a time with one trailing rerun. Status polling follows panel subscriptions: a Session's bindings are watched only while one of its surfaces is mounted, and the registry stops polling change requests nobody watches. Each card keeps the last snapshot a poll returned, so a transient failure keeps the title and number visible. A Session's only open change request starts expanded, and with several every card starts collapsed; the user's first toggle replaces this default. 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 6e8438080c..770db01822 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,11 +10,11 @@ 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 服务作为插件页中默认禁用的一个条目发布。 评审与工作树控件服务于同一个代码修改流程。统一插件入口让用户可以一次启用这些能力,无需根据底层包的拆分判断应该开启哪张卡片。包与两套工作树服务仍保持独立,分别负责会话开始前和对话中创建工作树的流程。 -Remote 通过 Session 的子进程提供方,按其[解析出的权限与查询限制](../bug-fix/2026-10-28-forge-git-session-permissions.zh.md)检查检出,因此它读到的与 Session 命令看到的相同。检查读取顶层目录、Git 目录与公共 Git 目录、分支或缩写的 HEAD 提交、上游与远端,以及分支相对于其分叉点的变更规模。它在 Session 被关注时、每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后以及刷新时运行,一次只运行一个,最多再追加一次。 +Remote 通过 Session 的子进程提供方,按其[解析出的权限与查询限制](../bug-fix/2026-10-28-forge-git-session-permissions.zh.md)检查检出,因此它读到的与 Session 命令看到的相同。检查读取顶层目录、Git 目录与公共 Git 目录、分支或缩写的 HEAD 提交、上游与远端,以及分支相对于其分叉点的变更规模。它在 Session 被关注时、每个 `workspace-root/change`、`tool/result` 与 `sandbox/mode` 事件之后以及刷新时运行,一次只运行一个,最多再追加一次。 状态轮询跟随面板订阅:只有该 Session 的某个界面挂载时才监听其绑定,注册表停止轮询无人监听的变更请求。每张卡片保留最近一次轮询得到的快照,因此短暂的失败不会让标题与编号消失。Session 只有一个打开的变更请求时,它的卡片默认展开;有多个时全部折叠;用户第一次展开或收起卡片后,以用户的选择为准。 diff --git a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml index ef48218d09..166fc3aab2 100644 --- a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.i18n.yaml @@ -15,5 +15,5 @@ en: 1e2239783738cec2 zh: 5f248eee47de376e /agent-note-session-change-request-bindings/consequences: - en: a2960e50ec52c9b6 - zh: fd23f4fe1137787d + en: 2786b1dffa995c14 + zh: c124420915da5aae diff --git a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md index cec7b0e81b..a7177b9acf 100644 --- a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md +++ b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.md @@ -30,4 +30,4 @@ After each push result, and when a caller such as the forge panel reports the br ## Consequences -Bindings appear without model cooperation for the common `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` flows and add no model tokens. Commands run through scripts, aliases, or other command-line tools are not recognized, and a change request opened elsewhere for a branch appears only after another push, another report of that branch, or a `track`. Another provider adds its own access and URL forms behind the same provider contract without changing the binding rules or the polling. The host needs `gh` signed in for each GitHub host. +Bindings appear without model cooperation for the common `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` flows and add no model tokens. Commands run through scripts, aliases, or other command-line tools are not recognized, and a change request opened elsewhere for a branch appears only after another push, another report of that branch, or a `track`. Another provider adds its own access and URL forms behind the same provider contract and registers its CLI's commands as a [command rule](2026-11-11-forge-provider-command-rules.md), without changing the polling. The host needs `gh` signed in for each GitHub host. diff --git a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md index e422428a20..e170f35117 100644 --- a/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-session-change-request-bindings.zh.md @@ -30,4 +30,4 @@ Status: implemented ## Consequences -在常见的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` 流程中,绑定无需模型配合即可出现,且不增加模型 token。通过脚本、别名或其他命令行工具运行的命令无法识别;在别处为某个分支打开的变更请求,要等到下一次推送、再次报告该分支或 `track` 之后才会出现。新的提供方在同一提供方契约之后加入自己的访问方式与 URL 形式,无需改变绑定规则或轮询。宿主需要为每个 GitHub 主机登录 `gh`。 +在常见的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` 流程中,绑定无需模型配合即可出现,且不增加模型 token。通过脚本、别名或其他命令行工具运行的命令无法识别;在别处为某个分支打开的变更请求,要等到下一次推送、再次报告该分支或 `track` 之后才会出现。新的提供方在同一提供方契约之后加入自己的访问方式与 URL 形式,并把其 CLI 的命令注册为[命令规则](2026-11-11-forge-provider-command-rules.zh.md),无需改变轮询。宿主需要为每个 GitHub 主机登录 `gh`。 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-10-20-forge-session-list.i18n.yaml b/.agents/notes/implemented/feature/2026-10-20-forge-session-list.i18n.yaml index 2f6f65eb10..0b5d2bda65 100644 --- a/.agents/notes/implemented/feature/2026-10-20-forge-session-list.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-20-forge-session-list.i18n.yaml @@ -9,8 +9,8 @@ en: 07ba0c3bf73a2446 zh: 2413783a6697133e /agent-note-forge-state-in-the-session-list/decision: - en: e1d03cf4e1afd5aa - zh: b2386cb7c17c58dd + en: 51fc671a0c3e682e + zh: cec607f46e7dc4b8 /agent-note-forge-state-in-the-session-list/alternatives-considered: en: 3b08440ee2bf7809 zh: a90e3fcb89cf3f74 diff --git a/.agents/notes/implemented/feature/2026-10-20-forge-session-list.md b/.agents/notes/implemented/feature/2026-10-20-forge-session-list.md index cec6faa265..5ec1f73924 100644 --- a/.agents/notes/implemented/feature/2026-10-20-forge-session-list.md +++ b/.agents/notes/implemented/feature/2026-10-20-forge-session-list.md @@ -12,7 +12,7 @@ The [forge panel](2026-10-09-forge-panel.md) named a Session's branch in a chip The chip beside the Session title is gone, and the tab's first row names the branch. A Session row shows, after its time, a branch glyph while the Session works in the worktree the panel created for it, and the glyph of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. An open change request's glyph keeps the row's subdued color with a dot for its checks; merged and closed ones keep their state colors. The row's hover card section names the worktree branch and what it started from, then up to three change requests with their state and checks, and how many more there are. -Log facts reach the list as projection client views, which the Session summary carries. The `forgeWorktree` projection also records the Session's directory from its header and each `working-directory/change`, and its view is the created worktree while that directory is the worktree or lies below it, else null. The `forgeChangeRequests` view lists the bindings without status, as the [binding decision](2026-10-09-session-change-request-bindings.md) intended. The projection cache keeps both for Sessions that are not loaded. +Log facts reach the list as projection client views, which the Session summary carries. The `forgeWorktree` projection also records the Session's directory from its header and each `workspace-root/change` or `working-directory/change`, and its view is the created worktree while that directory is the worktree or lies below it, else null. The `forgeChangeRequests` view lists the bindings without status, as the [binding decision](2026-10-09-session-change-request-bindings.md) intended. The projection cache keeps both for Sessions that are not loaded. Polled states reach the list through the `forgePanel.changeRequestStates` stream. One Host run serves every stream and stops with the last one. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of loaded Sessions from `ctx.forgeSession` and those of other Sessions from their cached summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through the shared `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. Every changed state is stored in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL, so a restart shows the last known states before the next poll, and unbound stored states are dropped only when every listed Session has known bindings. A stream sends a `baseline` of the states its caller may read, then `changed` frames, filtered through Remote access. diff --git a/.agents/notes/implemented/feature/2026-10-20-forge-session-list.zh.md b/.agents/notes/implemented/feature/2026-10-20-forge-session-list.zh.md index 73bfee90a7..6726d3c990 100644 --- a/.agents/notes/implemented/feature/2026-10-20-forge-session-list.zh.md +++ b/.agents/notes/implemented/feature/2026-10-20-forge-session-list.zh.md @@ -12,7 +12,7 @@ Status: implemented Session 标题旁的标签已移除,由标签页顶部一行写出分支。Session 在面板为它创建的 worktree 中工作时,会话行在时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,并用圆点标出检查;已合并与已关闭的保留各自的状态颜色。会话行悬浮卡片中的部分写出 worktree 分支及其起点,再列出最多三个变更请求的状态与检查,并说明还有多少个。 -日志事实经投影的客户端视图进入列表,由 Session 摘要携带。`forgeWorktree` 投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;该目录就是所创建的 worktree 或位于其下时,视图为该 worktree,否则为 null。`forgeChangeRequests` 视图列出绑定但不含状态,与[绑定决策](2026-10-09-session-change-request-bindings.zh.md)的设想一致。投影缓存为未加载的 Session 保留这两项。 +日志事实经投影的客户端视图进入列表,由 Session 摘要携带。`forgeWorktree` 投影还从 Session 头部与每个 `workspace-root/change` 或 `working-directory/change` 记录 Session 的目录;该目录就是所创建的 worktree 或位于其下时,视图为该 worktree,否则为 null。`forgeChangeRequests` 视图列出绑定但不含状态,与[绑定决策](2026-10-09-session-change-request-bindings.zh.md)的设想一致。投影缓存为未加载的 Session 保留这两项。 轮询到的状态经 `forgePanel.changeRequestStates` 流进入列表。宿主用一次运行服务所有流,最后一条流结束时运行停止。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的摘要;它跟随已加载 Session 的绑定变化,并经共享的 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,因此重启后在下次轮询之前就能显示最近已知的状态;仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态。每条流先发送调用方可读状态的 `baseline`,之后发送 `changed` 帧,均经 Remote 访问控制过滤。 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-deepseek-chat-export-import.i18n.yaml b/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.i18n.yaml new file mode 100644 index 0000000000..cbca1ec7a4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.i18n.yaml @@ -0,0 +1,61 @@ +# Bilingual-pair consistency record for 2026-11-11-deepseek-chat-export-import.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-11-deepseek-chat-export-import.md +/agent-note-import-deepseek-website-chat-exports: + en: 28f67da94fa101de + zh: e532503740e4516e +/agent-note-import-deepseek-website-chat-exports/problem: + en: bb08ceef4dc54b8b + zh: ff1a4235fadd19ee +/agent-note-import-deepseek-website-chat-exports/decision: + en: d80db86d5c5fb6c0 + zh: 786606a16d47635c +/agent-note-import-deepseek-website-chat-exports/decision/user-flow: + en: 3bb8080e42c2da26 + zh: eb67425c1715df6f +/agent-note-import-deepseek-website-chat-exports/decision/package-layout: + en: 08f6a8305084e5b3 + zh: 779f957ba5193525 +/agent-note-import-deepseek-website-chat-exports/decision/host-route-and-remote: + en: ff13a60cd73612a1 + zh: a0e625b6d7e05041 +/agent-note-import-deepseek-website-chat-exports/decision/reading-the-export: + en: 5069430168c5ae98 + zh: dc086ec1f236be9a +/agent-note-import-deepseek-website-chat-exports/decision/selecting-the-conversations: + en: 4628cc1e25d90a26 + zh: 8649b3e0b0210510 +/agent-note-import-deepseek-website-chat-exports/decision/linearizing-the-message-tree-selectbranch: + en: 4ee78fb3a40ded8e + zh: 3fda20e2db2cd37d +/agent-note-import-deepseek-website-chat-exports/decision/message-chain-to-session-events-convertconversation: + en: 542149b99f8d3ea5 + zh: c0fa9f8c545d54a2 +/agent-note-import-deepseek-website-chat-exports/decision/fragment-mapping: + en: 98282c93efe3d169 + zh: 3b79663b9020ad7e +/agent-note-import-deepseek-website-chat-exports/decision/reply-status-mapping: + en: a2ce8fc69fb38cd3 + zh: b65234fce7922b96 +/agent-note-import-deepseek-website-chat-exports/decision/session-writes: + en: b4d436e605cb2a24 + zh: e48735e9db5099ca +/agent-note-import-deepseek-website-chat-exports/decision/client: + en: 382e0c201bcde038 + zh: 710f67a5b0d89dc4 +/agent-note-import-deepseek-website-chat-exports/decision/realization: + en: 8803b6ec2edc20e3 + zh: 43dfee5ffcfff4a2 +/agent-note-import-deepseek-website-chat-exports/decision/images: + en: 3c185fa06a8c0af3 + zh: d51787e832337107 +/agent-note-import-deepseek-website-chat-exports/decision/testing: + en: 7644a5531582a3d4 + zh: a8153a60ca46815d +/agent-note-import-deepseek-website-chat-exports/alternatives-considered: + en: 94b324f44acde29b + zh: 549bdc73ae18a23a +/agent-note-import-deepseek-website-chat-exports/consequences: + en: ecbbfb4a245d89c9 + zh: 400f4469bf352ea0 diff --git a/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.md b/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.md new file mode 100644 index 0000000000..de51543863 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.md @@ -0,0 +1,266 @@ +# Agent Note: Import DeepSeek website chat exports + +Status: implemented + +English | [中文](2026-11-11-deepseek-chat-export-import.zh.md) + +## Problem + +The "export all chats" action on the DeepSeek website (chat.deepseek.com) produces a `deepseek_data-*.zip`. Users want to bring these conversations into DSH and keep using them: browse the original questions, reasoning, and answers in the Web GUI, and continue any conversation with the model seeing its original context. Without an import, DSH can only start from a blank Session. + +The export format (`export_format_version: 3`) differs from a DSH Session in four structural ways that the import must handle: + +- Each conversation's `messages` form a tree linked by `parent_id` (regenerating a reply or editing a question creates a branch); a DSH Session is a linear append-only log. +- Message `id` values increase only within one conversation and cannot be compared across conversations; `inserted_at` is not monotonic even within one conversation (an assistant reply is often a few milliseconds earlier than its user message). +- The `fragments` of one assistant message interleave reasoning, web search, opened pages, and answer text; DSH expresses the same process with `assistant/message` plus `tool/call` / `tool/result` inside steps. +- The export also contains template replies, failure states, encrypted link bodies, and notices that must **not** enter the model context. + +One export can contain thousands of conversations and hundreds of megabytes of images; users need only the most recent conversations, in a Workspace they choose, and the Host must stay responsive while it imports them. + +## Decision + +The experimental package [`@deepseek-ai/dsh-deepseek-chat-import`](../../../../packages/experimental/deepseek-chat-import/README.md) has a Host face and a Client face: + +- Host face: a `TypertRemoteService` that registers the exact upload route `POST /api/deepseek-chat-import/archive?workspaceId=…` on `ctx.connection.fetch` and the `@Remote limits()` method. The route buffers the uploaded ZIP in memory, imports the most recent conversations one at a time as stored DSH Sessions in the chosen Workspace, and streams progress. +- Client face: an import button right of "New session" in the sidebar. It opens a dialog with an export file field (the browser-native file input, `accept=.zip`) and a Workspace field that renders the `workspace.picker` Factory from ui-workspace; the browser uploads the file and shows upload and import progress and the result. + +The button position comes from the ui-sidebar HOC slot `sidebar.session.action`; the plugin wraps the New-session row content there and returns it followed by its button, so decorating the row adds no wrapper element. ui-sidebar does not hard-code the button, because the sidebar shell would then call the import plugin's Remote namespace and carry business logic. The Workspace field reuses the New-session Workspace menu as the `workspace.picker` Factory: existing Workspaces plus "Add workspace…", which runs the composed directory picker through the `workspace.picker.directoryFlow` hole. + +The capability ships as an Official experimental optional bundle: the package declares `dsh.bundle.patch` with its own `deepseek-chat-import` row, is listed in `OPTIONAL_BUNDLES`, and is switched off until the user enables it on the Plugins page. The default Web composition does not mount it. + +### User flow + +1. The user enables "DeepSeek chat import" on the Plugins page, then clicks the import button right of "New session" (an icon button below the "New session" icon in the narrow sidebar). Only the owner sees the button. +2. The dialog takes the ZIP file exported from the DeepSeek website (`deepseek_data-*.zip`) and the Workspace that receives the Sessions. The Workspace field preselects the current Session's Workspace; "Add workspace…" adds a new directory through the directory picker. +3. On import, the browser first calls `limits()`; a file larger than `maxUploadBytes` is rejected before upload. A served page then shows the upload percentage, an indeterminate phase while the Host reads the archive, and "Importing n/K" while Sessions are written. A page whose Host runs in another execution context carries the archive over `__DSH_TRANSPORT__.fetch`, which reports no byte progress, so the dialog starts at the reading phase. Closing the dialog aborts the request. +4. On success the dialog shows how many Sessions were imported into which Workspace, how many conversations exceeded the limit, and how many could not be imported, in singular or plural form. +5. On failure the dialog shows the localized explanation of the failure reason, or the message of an unexpected error. +6. However the attempt ends, the browser refreshes the Session list, so Sessions written before a failure or cancellation appear. + +The user then opens any imported Session and sees the original questions, reasoning, search cards, and answers; a new message continues with the default model and the imported history as context. + +### Package layout + +| File | Responsibility | +|---|---| +| `src/types.ts` | Browser-safe wire types only: results, failure reasons, limits, the NDJSON answer lines, and the `deepseekChatImport/owner-only` Remote error code | +| `src/protocol.ts` | `UPLOAD_PATH` and its document-relative form `UPLOAD_ROUTE` | +| `src/format.ts` | zod validation of `manifest.json`, `chat_sessions/{id}.json`, and the fragment types the package maps; unknown fragment types stay for the converter to ignore | +| `src/archive.ts` | `openExportArchive(bytes, maxEntryBytes, signal)`: the ZIP central directory, streaming passes over the archive bytes that inflate only the entries they are asked for, and a by-name read | +| `src/conversation.ts` | Pure functions `selectBranch(file)` and `convertConversation(file, options)` from a message tree to seed events | +| `src/importer.ts` | `importDeepseekChatExport(deps, request, signal)`: index selection, the image pass, the conversation pass, writes, and Workspace attachment | +| `src/upload.ts` | `createUploadRoute(handler)`: request validation, bounded buffering, the streamed answer, and cancellation | +| `src/index.ts` | `DeepseekChatImportService`, `Config`, the single import slot, and `@Remote limits()` | +| `src/client/*` | Button, dialog, browser upload over the page carrier or XHR, locale dictionaries, slot registration | +| `cordis.patch.yml` | The optional bundle row `deepseek-chat-import` | + +`src/conversation.ts` reads no files, uses no services, and reads no clock; the caller injects every id, so it is deterministic under unit tests. `src/importer.ts` uses persistence, the projection cache, attachments, and the Workspace registry through an explicit dependency object, so its tests can use real JSONL persistence. + +### Host route and Remote + +```ts +/** Deployment limits of the importer. */ +interface Config { + /** Most Sessions one import writes, choosing the conversations the export index lists as most recently updated; default 1000. */ + maxSessions: number + /** Largest export archive, in bytes, one upload may carry; default 512 MiB. */ + maxUploadBytes: number + /** Largest declared uncompressed size, in bytes, of one archive entry; default 256 MiB. */ + maxEntryBytes: number + /** Largest UTF-8 size, in bytes, of an imported title; default 80. */ + maxTitleBytes: number +} +``` + +`POST /api/deepseek-chat-import/archive?workspaceId=…` is an exact route on the shared API channel, so only owner Peers reach it. `limits()` refuses every caller that is not the owner with `deepseekChatImport/owner-only`, so a non-owner principal such as a shared-Session guest never imports. The route requires `content-type: application/octet-stream` (otherwise 415) and a non-empty `workspaceId` (otherwise 400); the shared handler answers other methods before the route runs. + +The service owns one import slot. A request takes the slot or answers `busy`, resolves the Workspace (`workspace-not-found`), and reads the streaming body into one buffer sized from a valid `content-length`, growing it only when the body is longer than declared, until the body ends or exceeds `maxUploadBytes` (`too-large`). The upload is never written to disk. Each request owns an AbortController joined with the request signal and with cancellation of the response body. Unloading the plugin aborts the running import, including a body still uploading, and completes only after the import stops writing. + +The answer is `application/x-ndjson` with `cache-control: no-store, no-transform`: progress lines `{ type: 'progress', done, total }`, then exactly one line `{ type: 'outcome', outcome }`, where `outcome` is `{ ok: true, value: DeepseekChatImportResult }` or `{ ok: false, error: { reason, message } }`. The Web server writes the body chunk by chunk, and the browser reads complete lines as they arrive, which also works when a proxy delivers the whole body at once. The browser validates every decoded line: it must be an object of a known `type` with the fields that type carries, so a `null`, a line missing `done`, or an outcome whose `ok` is not boolean fails the answer as invalid instead of throwing inside an `onload`/`onprogress` callback. `reason` is one of `too-large | unreadable-archive | missing-manifest | missing-index | unsupported-version | no-conversations | workspace-not-found | busy`. An unexpected failure is logged on the Host and ends the body without an outcome line, which the browser reports as an upload failure. + +`attachments` and `sessionProjectionCache` are optional services read through `ctx.get()`: without the attachment service, images become synthetic file cards; without the projection cache, the list row of a cold Session cannot show its original title and activity time before it is first opened. + +### Reading the export + +- `openExportArchive` reads the central directory with fflate's asynchronous `unzip` and a filter that accepts nothing, so opening inflates no entry. Bytes that are not a readable ZIP fail with `unreadable-archive`. Entry names must be unique: a by-name read selects by name, so a duplicate name would inflate every match and bypass the per-entry limit; a duplicated name fails with `unreadable-archive`. Duplicate detection covers the central directory only: a second local file header renamed to an existing entry name is not detected, so the pass can deliver more conversations than the index lists, and the import does not guard the write count. +- `manifest.json` and `chat_session_index.json` are read by name before the pass. A missing or damaged manifest fails with `missing-manifest` or `unreadable-archive`; a missing, damaged, or unparsable index fails with `missing-index`; an entry over `maxEntryBytes` fails with `too-large`; an `export_format_version` other than 3 fails with `unsupported-version`. +- One streaming pass then inflates only the chosen conversation entries, in archive order, yielding to the event loop between 64 KiB chunks of archive bytes. Inflation is synchronous (`UnzipInflate`), so one chunk's output is produced before the pass yields; an entry that declares a small size but inflates past `maxEntryBytes` keeps inflating until it ends, and the limit then stops the bytes being kept, not the work. The central directory supplies each entry's declared sizes before inflation: an entry over `maxEntryBytes` is rejected without being inflated, and a stored entry whose declared size differs from the bytes it holds is rejected as damaged. An accepted entry is accumulated and delivered whole; more bytes than it declares or than `maxEntryBytes` rejects it. +- The images of every chosen conversation are stored by a separate streaming pass before any conversation is parsed. That pass inflates only `chat_sessions/{id}_files/…` entries whose id the index selected, one at a time, and records the stored reference or the failure reason for each. Because it runs first, archive entry order does not matter and the conversation pass never reads an image by name. +- A by-name read serves the manifest, the index, and a replacement conversation. Each call re-parses the whole central directory, so a replacement costs one directory scan for its conversation file; its images are collected by one further image pass, not one read per image. The read returns at most the bytes the entry declares, truncating an entry that inflates to more; the pass reports that same condition as a size failure. +- Conversations are the `*.json` entries directly under `chat_sessions/` (not the `*_files/` subdirectories). An entry whose id the index does not select is skipped without being inflated. A chosen conversation is parsed and converted as it arrives; a conversation that is oversized, damaged, not JSON, or fails zod validation or conversion goes into `skipped`. + +### Selecting the conversations + +1. `chat_session_index.json` ranks the conversations the export carries: descending `updated_at`, then descending `inserted_at`, then ascending id. The import writes the newest `total = min(maxSessions, index rows)` of them, in archive order. +2. Session persistence and Workspace membership order by Session time rather than by write order, so the archive order the pass writes in does not change the Session list. +3. A conversation the archive does not carry, or one that fails conversion or storage, is reported in `skipped`; the next older conversation the index lists takes its place, fetched by name. `omittedByLimit` counts the conversations the index lists that no attempt reached. +4. `sessionIds` lists the imported Sessions newest first by the index order, whatever order they were written in. + +### Linearizing the message tree (`selectBranch`) + +- The selected message is the one named by `current_message_id`. The chain is traced from it along `parent_id` to the root with `parent_id === null`, then reversed. Other branches are dropped; each conversation yields one Session. +- When `current_message_id` is absent, null, or names no message, the message with the largest `id` is selected instead. Ids increase within a conversation and a child's id is always greater than its parent's, so that fallback is always a leaf. +- An empty `messages` list, duplicate message ids, a `parent_id` naming a missing message, or a cycle makes the conversation invalid and puts it into `skipped`. + +### Message chain to Session events (`convertConversation`) + +Messages on the chain are grouped as one turn per USER message: a USER message and the ASSISTANT message right after it form a turn. An ASSISTANT message without a preceding USER message (only possible in malformed data) is dropped. A USER message whose reply has status `CONTENT_FILTER` is dropped together with that reply: neither node produces an event, nothing is displayed, and later turns are numbered without a gap. A chain ending with USER yields a last turn with only the question. User and assistant need not alternate strictly: an excluded reply produces no `assistant/message`, so the next question follows the previous one directly, matching the history of a DSH turn that received several steered messages. A conversation without any remaining turn fails conversion and goes into `skipped`. + +Events of one turn: + +| Order | Event | Notes | +|---|---|---| +| 1 | `turn/start {turn: n}` | Time of the USER message | +| 2 | `step/start {turn: n, step: 1}` | In the first turn, followed by an empty `system/message` (`surfaceOp: 'append'`) as surface node 0 | +| 3 | `user/message` (`surfaceOp: 'append'`) | `source: { kind: 'user' }`, content below | +| 4 | Per step: `assistant/message` (`stream: []`), one `tool/call` / `tool/result` pair per tool call, `step/end`; the next step starts with `step/start` | Only for normally finished replies | +| 5 | `step/end` (last step) | | +| 6 | `turn/end` | `{ kind: 'completed' }` for a normal reply; `{ kind: 'error', error: { code, message } }` for an excluded or missing reply | + +The empty system head derives no model message and renders no prompt card. The stored format accepts a `system/message` only as surface node 0 or after such a head, and every read of a stored log checks this; with the head in place, a resumed Agent replaces it with the real system prompt instead of appending a system message after the imported history. + +A user message whose text is empty or whitespace and that has no attachment carries one text block with the empty string: the Turn and its row exist, and DeepSeek request serialization skips the empty user message, so that Turn's question is absent from the model context and a first Turn without text starts the request with its assistant message. + +After the first turn, the conversation title appends `session/title { title, messageSeqs: [], source: { kind: 'user' } }`. The title is normalized with session-title's `normalizeSessionTitle`: whitespace collapses to single spaces and the text is truncated to `maxTitleBytes` UTF-8 bytes. A missing title, or one that normalizes to empty, writes no title event. The `user` source pins the title, so no title generation runs after import. + +The assistant message `source` is `{ kind: 'model', provider: 'deepseek-chat-export', model: 'deepseek-chat-export' }` without `replayState`. The DeepSeek adapter sends such foreign reasoning as unsigned thinking, the existing cross-model history path. No `usage`, `request/header`, `request/context`, or `model/selection` is written: the first request after resume records an `initial` header with the deployment's default model and shows no model-switch notice. + +`stream` is an empty array. The export has no per-token stream record, and a fabricated stream cannot satisfy the check that the stream reconstructs the content exactly; the empty array passes the existing checks, and the Web assistant row renders from `message.content`. + +**Event times.** Each event's `time` is the `inserted_at` milliseconds of its export message, clamped to be non-decreasing in order of appearance (which absorbs the assistant reply that is a few milliseconds earlier than its question). Within one reply, each THINK with `elapsed_secs` advances the time cursor by that many milliseconds, and later steps use the advanced time, so step intervals reflect the original reasoning duration. The Session header's `createdAt` is the time of the first event. + +### Fragment mapping + +| Fragment | Message | Mapping | Enters model context | +|---|---|---|---| +| `REQUEST` | USER | Text of `user/message` | Yes | +| `FILE` (image) | USER | `{ type: 'image', attachment }` when the `export_path` entry exists and the attachment service stored it; otherwise a synthetic file card, `{ type: 'file', attachment }` with a reference naming no stored object | The stored image on image-capable routes; otherwise the file handle text, whose named path holds no bytes | +| `FILE` (not an image) | USER | Synthetic file card: `{ type: 'file', attachment }` whose reference is `attachmentId = sha256('deepseek-chat-export:' + file.id)`, `name = file_name`, `bytes = file_size` (0 when absent); the file body is not in the export, so no object exists for it and the handle's path holds nothing | Yes, as file handle text | +| `THINK` | ASSISTANT | `{ type: 'reasoning', text }` in the current step; empty text is ignored | Yes (per adapter rules) | +| `RESPONSE` | ASSISTANT | `{ type: 'text', text }` in the current step; empty text is ignored | Yes | +| `TOOL_SEARCH` | ASSISTANT | `web_search` call with arguments `{"queries": [...]}`; the result body comes from `formatSearchOutput` of `dsh-tool-web`; `meta` is `{ sources: [{ url, title, snippet, publishedAt }], truncated: false }`, rendered as the standard search card. `WIP` is skipped as incomplete; `FAILED` yields `isError: true` with the fixed text `Error: the export records this search as failed.`; a missing `status` behaves as `FINISHED`. Ignored when every query is empty or blank | Yes | +| `TOOL_OPEN` (with url) | ASSISTANT | `web_fetch` call with arguments `{"url": ...}`; the result body holds the title, URL, and a note that the page body is not in the export; with `status: FINISHED`, `meta` is `{ url, statusCode: 200, truncated: false }`, rendered as the standard fetch card; `FAILED` yields `isError: true`; `WIP` is ignored | Yes | +| `TOOL_OPEN` (url null or empty) | ASSISTANT | Nothing: the exporter writes one all-null record with `stage_id` and `group_id` beside the real opens of a stage, which names no page | No | +| `TOOL_FIND` | ASSISTANT | Nothing: the website shows the find as its own row, which has no counterpart message block | No | +| `TOOL_IMAGE_SEARCH` | ASSISTANT | Nothing: the website shows no row for an image search, and the reply's reasoning already states what the model took from its results; the searched image is not in the export | No | +| `READ_LINK` | ASSISTANT | One Markdown link line per result: `[title](url)`, the URL as its own text when the title is missing, the title alone when the URL is missing, and nothing for a result with neither; the body stays a signature that cannot be decrypted without the key | Yes (text) | +| `TIP` | ASSISTANT | Nothing: a website notice rather than model output, shown by the website as a banner | No | +| `CONTENT_RISK` | ASSISTANT | Ignored: a fixed disclaimer with no information | No | +| `PARTIAL_FILE_READ` | ASSISTANT | Nothing: the website shows the partial read as its own row | No | +| `TEMPLATE_RESPONSE` | ASSISTANT | Excludes the whole reply; `turn/end` carries the template text as the error message | No | +| Unknown type | Any | Ignored | No | + +**Step boundaries.** A fragment that carries a `stage_id` shares the open step while the value stays the same. A different value starts a new step only when the open step already holds a tool call; otherwise the open step adopts the new stage. A call-less step that is not the last would put two assistant messages in a row in the resumed history, which the live loop never produces, so a text-only step stays merged with the next call. A step opened by a fragment without a stage adopts the next stage it sees. Fragments without `stage_id` keep the older rule: THINK or RESPONSE after a tool call ends the current step and starts the next, and the records that do not carry a stage behave as text there. A `WIP` record is skipped and does not split a step. Consecutive tool fragments with one `stage_id` fall into one step, like one parallel call. Ignored fragments do not split steps, so "THINK, three TOOL_OPEN with null url, THINK" keeps one step holding both reasoning blocks. + +For the website's search-while-thinking replies, `THINK, TOOL_SEARCH (stage 1), THINK, TOOL_OPEN×4 (stage 2), THINK, RESPONSE` maps to three steps: (1) reasoning + `web_search`; (2) reasoning + four `web_fetch`; (3) reasoning + answer. A directly consecutive `TOOL_SEARCH (stage 1)` then `TOOL_OPEN (stage 2)` without reasoning between them splits into two steps because the first step already holds the search call. + +**Block order within a step.** One step's `assistant/message` carries its text blocks (reasoning, answers, link lines) before its tool-call blocks, each group in the order recorded. Text that the export records after a tool call in the same step is therefore stored before that call, while the step sequence and every cross-step order stay as exported. Interleaving text after a tool call inside one assistant message would not match any step the live loop produces. + +**Ids.** Message ids and tool-call ids come from the caller-injected `createId()` (`randomUUID` in production); the `tool-call` block id, `tool/call.callId`, and the `source.callId` and `toolCallId` of the `tool/result` message are the same. + +### Reply status mapping + +The export documentation requires that messages other than `FINISHED` and template replies stay out of the model context. A reply withdrawn by content filtering (`CONTENT_FILTER`, shown as withdrawn on the website) is dropped with its question, as described above. Every other excluded reply writes no `assistant/message` and no `assistant/attempt` (the Web does not show attempts, and "user message + attempt + retryable error code" would make the GUI offer to continue generating). The user sees the turn's closing error row with its reason and code: + +| Original reply | `turn/end.reason.error.code` | `message` (English, written to the log) | +|---|---|---| +| `FAILED` / `TIMEOUT` / `CONTEXT_LENGTH_EXCEEDED` / `INCOMPLETE` / `WIP` | `DEEPSEEK_EXPORT_FAILED` / `DEEPSEEK_EXPORT_TIMEOUT` / `DEEPSEEK_EXPORT_CONTEXT_LENGTH_EXCEEDED` / `DEEPSEEK_EXPORT_INCOMPLETE` / `DEEPSEEK_EXPORT_WIP` | The original reply ended with status "{STATUS}" and is excluded from the model context. | +| Any other status | `DEEPSEEK_EXPORT_UNFINISHED_REPLY` | The same message with the status quoted | +| Contains `TEMPLATE_RESPONSE` | `DEEPSEEK_EXPORT_TEMPLATE_RESPONSE` | The template text itself | +| `FINISHED` without importable content | `DEEPSEEK_EXPORT_EMPTY_REPLY` | The original reply has no importable content. | +| Chain ends with USER (no reply) | `DEEPSEEK_EXPORT_NO_REPLY` | The export contains no reply to this message. | + +Error codes are fixed strings; text from the export appears only inside the message. These codes are outside the session-controller's continuable code set, so no "continue generating" appears. The question itself stays in context. + +### Session writes + +The import creates no live Agent and writes the persistence layer directly. Failures detected before the pass (an unreadable archive, a missing, oversized, or unsupported manifest or index, no importable conversation, an oversized upload) write nothing; an archive whose structure breaks during the pass fails as `unreadable-archive` after the Sessions delivered before the break were written. Each conversation is fully converted and seed-validated with `Session.create` before it is written; a conversation that fails is skipped and does not stop the others. Each chosen conversation is converted and written as its archive entry arrives, and a conversation a failure pulls in afterwards is read by name. For each conversation: + +1. The import checks that the target Workspace is still registered and that its directory exists; otherwise it stops with `workspace-not-found`, and the Sessions written before remain. +2. The conversation is converted with the image references the image pass already stored. An image whose conversation later fails conversion or seed validation is already stored and keeps no referencing event. +3. `Session.create(id, seed, header)` runs the same seed validation as a live append (JSON serializable, consecutive seq, valid surface transitions, valid message fields); the detached validation instance is discarded. +4. `ctx.sessionPersistence.create(header)` → `handle.append(events)` → `handle.flush()` → `handle.close()` (closed on failure too). The header is `{ version: SESSION_FORMAT_VERSION, id, createdAt, cwd, isSeeded: false }`, and `cwd` is the Workspace's canonical path. The stored events have no `session/end-seed`; the ordinary resume path appends that marker on first open. +5. When the projection cache is available, `coldSnapshot(header, SessionLogOffset(0), events)` refreshes the cached row the sidebar reads (title, last question time, non-blank). +6. `workspace.attachSession(id)`. When it fails, the conversation goes into `skipped` with the reason "stored as Session {id} but not added to the workspace"; `SessionPersistence` offers no removal, so that Session stays stored outside the Workspace. + +The converted events are released before the next conversation, and the import yields to the event loop between conversations and checks cancellation at each step. A written Session appears in `session/list` like any other cold Session and opens through the ordinary resume path. The import adds no Session event type, does not change `SESSION_FORMAT_VERSION`, and needs no persistence-type acknowledgement. + +### Client + +- ui-sidebar declares the HOC slot `sidebar.session.action` (`scope: 'root'`, owner `{ wide: boolean }`) around the New-session row content, so an occupant receives that content as `children` and returns it, possibly wrapped, plus its own controls. The trigger renders right of "New session" (on the same row in the wide sidebar, where "New session" takes the remaining width; stacked below the "New session" icon in the narrow sidebar). +- The plugin's Client face `$mount`s its own `/remote` contribution (the self-mounting form of `dsh-api-remote-access`, outside the `dsh-api-remotes` aggregate) and registers `ImportSessionsAction` as the `sidebar.session.action` layer. It renders the row content first, then its trigger, then the dialog; a Peer that may not import gets the row content unchanged, so the New-session button keeps rendering. The button shows only when `useRemoteAccess('deepseekChatImport/limits')` is true; the dialog is local state of the layer rendered through the `Modal` portal. +- The upload uses `XMLHttpRequest` on a served page because Fetch exposes no upload progress. A page whose Host runs in another execution context (the static Cloudflare Pages preview) supplies `__DSH_TRANSPORT__.fetch`: the archive goes through that carrier with no byte progress, straight to the reading and importing phases. The URL is `UPLOAD_ROUTE` resolved against `document.baseURI`, so a path-prefixing proxy keeps working. A non-200 answer, an answer without an outcome line, a line that is not a valid protocol value, or a connection failure becomes the `upload-failed` outcome; a thrown error is shown with the unknown-failure copy. +- The carrier selection does not reuse `@deepseek-ai/dsh-client-file-upload`. That package's service buffers the whole response, which would lose the streamed NDJSON progress, and its `post` method is not part of its public surface; keeping the selection here preserves both the progress lines and the package edge. +- Copy goes through locale dictionaries in eight languages, with sentence case in English; summary lines have `.one` / `.other` forms chosen by `count === 1`. + +### Realization + +`sidebar.session.action` is an HOC layer rather than a list because the occupant decorates the row's content instead of rendering beside it: it receives that content as `children`, returns it, possibly wrapped, and adds its own controls without introducing a wrapper element. A list entry would render as a sibling of the row content, and the rail-in fade targets the slot outlet's children because the `display: contents` outlet anchor cannot carry an animation itself. + +The obligation is contract-only. An occupant that adds nothing, or may not act, must return `children` unchanged, because the renderer only rescues a layer that throws. A layer may legitimately omit `children`, which removes the New-session button, so no runtime check replaces the obligation. + +### Images + +- The image pass walks every image entry of a chosen conversation in archive order, without parsing the conversation. It inflates only `chat_sessions/{id}_files/…` entries whose id the index selected, calls `ctx.attachments.saveImage({ data, mediaType, name })` with the entry's extension and file name, and records the reference or the failure reason under the entry name. An extension other than png / jpg / jpeg / webp / gif is recorded as unsupported without inflating the entry. +- `convertConversation` emits an `image` block (before the text) for each `FILE` entry whose `export_path` the pass stored and a synthetic file card otherwise. +- A missing, unsupported, oversized, damaged, or rejected image becomes a synthetic file card with one Host warning; the conversation still imports. A missing entry reports `not in the export`; a size, corruption, unsupported-type, or storage failure reports its own reason. Attachment storage deduplicates by content. +- The pass stores every image entry of a chosen conversation before the branch is selected and before conversion. An image of a withdrawn round, of a dropped branch, or of a conversation whose conversion or `Session.create` seed validation later fails therefore stays stored without a referencing event. Neither `SessionPersistence` nor the attachment store offers a removal. + +### Testing + +| Layer | File | Coverage | +|---|---|---| +| Conversion | `tests/conversation.host.spec.ts` | `current_message_id` selection with the largest-id fallback; linearization by id; REQUEST / THINK / RESPONSE; `stage_id` step boundaries and search/open-page step boundaries; failed, unfinished, and status-less searches; dropped image searches, address-less opens, page finds, partial reads, and tips; Markdown link lines; turn errors and fixed codes for excluded replies; dropped content-filtered rounds; an empty text block in the first and later turns; title normalization; synthetic file cards; invalid trees. Output passes `Session.create`, and `deriveMessages` asserts the model history | +| Archive | `tests/archive.host.spec.ts` | Entry listing, one-entry reads truncating to the declared size, the streaming pass, the declared-size limit with a highly compressible entry, misdeclared sizes, duplicate entry names, stored-entry size mismatches, damaged entries, cancellation | +| Orchestration | `tests/importer.host.spec.ts` | Latest K oldest first with progress; a synthetic 2026-11-12 archive carrying every new field; oversized, damaged, and invalid conversation files; filling the limit after failures; a replacement chain that survives an invalid candidate; attach failures; Workspace removal; archive-level failures; cancellation; images stored by the image pass in any archive order, the synthetic file cards of unstored ones, and the absence of by-name image reads on the main path | +| Route | `tests/upload.host.spec.ts` | Request validation; `too-large`; buffer sizing from the declared length; one import at a time; NDJSON lines; cancellation by the answer, the request, and unloading | +| Resume | `tests/resume.host.spec.ts` | The production agent loop continues an imported Session; the model request holds the imported history without the withdrawn round | +| Composition | `tests/composition.host.spec.ts` | Host booted through the Loader; owner-only `limits()`; an upload stores the Session in the Workspace; unloading during a paused import cancels it and completes only after it stops, with nothing written | +| Client | `tests/import-sessions.client.spec.tsx`, `tests/mount.client.spec.ts`, `tests/upload.client.spec.ts` | Button visibility, Workspace preselection, progress bar and texts, plural summaries, failure and thrown-error copy, refresh after every attempt, NDJSON line reading and validation | +| Bundle | `scripts/optional-bundles.spec.ts` | The bundle composes over the Web profile and resolves its title, description, and icon | +| Snapshot | `apps/web/tests/deepseek-chat-import.e2e.ts`, `snapshots/web/deepseek-chat-import/` | A synthetic 2026-11-12 export with a branch, reasoning, a search and fetch pair, a read-link record, a content-filtered round, and an incomplete reply is uploaded through the route; one imported Session continues with one recorded model turn, and the persisted log replays keyless | + +## Alternatives considered + +**Type a host path to the export.** The first design read a ZIP or an extracted directory from an absolute Host path and created a `_workspace` directory next to it. Users must not type Host paths, a browser does not know them, and a remote Host has no access to the user's local download; the browser upload works the same for local and remote Hosts. + +**List export files inside a chosen Workspace.** The user would place the ZIP in a Workspace directory and pick it from a Host-side listing. The user rejected this in favor of uploading the file directly from the browser. + +**Stage uploads on disk.** Writing the upload to a temporary file would lift the memory bound but adds cleanup, crash residue, and a second copy of private data on the Host. The archive stays in memory, bounded by `maxUploadBytes`, and the service runs one import at a time. + +**Decompress and validate all conversations before writing any.** This made "a rejected export writes nothing" true for conversion failures, but held every conversation file and converted log in memory at once and blocked the event loop for the whole import. Two streaming passes follow `chat_session_index.json`: one stores the images of the chosen conversations without decompressing any conversation, and one converts and writes each chosen conversation as it arrives. + +**Report progress through a separate streaming Remote.** The route answer already streams through the Web server, so NDJSON lines on the same request need no second channel, keep progress and outcome ordered, and end with the request. + +**Import the newest leaf only.** It is always a leaf and needs no extra field, but it silently imports a different branch than the one the user was viewing whenever the export was taken after switching back. `current_message_id` is the export's own linearization key, and the largest-id fallback keeps archives without it importable. + +**Select by the selected message's `inserted_at`.** It is the time of the last imported event, but it needs every conversation's messages, so selection would decompress the whole archive before writing anything. `chat_session_index.json` carries the website's own update order and lets selection skip the conversations it does not choose; the cost is that the order follows renames and pins rather than the last imported event. + +**Create live Agents through `ctx.agents.create({ seed })`.** It is the existing supported entry, but `createdAt` can only be the current time, so every imported Session would crowd the top of the sidebar, and importing thousands of conversations would create thousands of live Agents. Writing persistence directly keeps the original times and uses no runtime resources. + +**One Session per branch, or branches inside DSH.** A DSH Session is a linear log; a Session per branch turns one website conversation into several hard-to-tell-apart Sessions. The requirement is the newest chain only. + +**Keep the question of a content-filtered reply with an error row.** The website shows such rounds as withdrawn, and the user decided that neither node is imported; the remaining turns read as the user saw them. + +**Write non-FINISHED or template replies as `assistant/attempt` or as `interrupted` `assistant/message`.** Attempts are invisible in the Web and, with retryable error codes, trigger "continue generating"; the content of an `interrupted` message enters the model context, which the export documentation forbids. + +**Hard-code the import button in ui-sidebar.** The sidebar shell would depend on the import plugin's Remote namespace and carry a business branch; the slot costs one declaration and a small layout change. + +**Add Session event types for TIP / CONTENT_RISK or the import origin.** That extends `SessionEventMap`, the persistence catalog, and the Web renderers beyond a small import; the notices do not change the answers. + +**Mount the importer in the default Web composition.** The capability is experimental, and release packages must not depend on experimental packages. The optional bundle keeps the default product unchanged and offers the import to users who enable it. + +## Consequences + +The import brings website history into DSH with original titles, times, reasoning, and search cards, and the imported Sessions continue through the ordinary resume path. Host memory is bounded by the archive (`maxUploadBytes`) plus one entry (`maxEntryBytes`), one converted conversation, and the references of the stored images, and the event loop stays responsive between conversations. The price is that only conversations already written survive a cancellation or a mid-import failure, and a conversation a failure pulls in is read by name and gets one further image pass. + +- **Cold writes are a production writer outside the agent loop.** The import uses fresh Session ids and closes each handle after writing, so it does not compete for ownership with live Sessions; if the persistence layer later assumes that every write goes through the agent loop (for example by registering derived state at creation), the import path must change with it. +- **A Session stored but not attached stays stored.** `SessionPersistence` offers no removal; the import reports such a Session in `skipped` with its id. +- **Historical tool calls have no tool records.** The imported `web_search` / `web_fetch` calls have no matching `request/header.tools` record. If a deployment does not register these tools, or a provider rejects history that references undeclared tools, the first request after resume fails; text-only mapping is the fallback. +- **The fetch card's status code is inferred.** The export records only that the page opened, not an HTTP status; `statusCode: 200` makes the card show a successful fetch. +- **Foreign reasoning is sent to the model again.** Imported reasoning is sent as unsigned thinking, which raises the input tokens of the first request after resume; the KV cache starts with that request. +- **Re-import duplicates.** Importing the same export again writes new Sessions; the import does not record which conversations it already imported. +- **The viewed branch decides the import.** `current_message_id` selects the chain, so an export taken after the user switched back to an older branch imports that branch; only an absent or unknown id falls back to the newest leaf. +- **One export structure.** The importer targets the 2026-11-12 structure. Older v3 archives still import because the added fields are optional, but their `READ_LINK` no URL or title, so its link lines carry less (an older `TOOL_FIND` pattern is no longer read at all). +- **`maxTitleBytes` is a separate setting.** The session-title service does not expose its limit, so a composition that changes session-title's `maxTitleBytes` sets the importer's field to the same value. +- **Content given up.** Other branches, content-filtered rounds, `CONTENT_RISK` disclaimers, `TIP`, `TOOL_FIND`, and `PARTIAL_FILE_READ` records, encrypted `READ_LINK` bodies, search-result `snippet` and `site_name`, the `pinned` flag, non-image file bodies, per-token reasoning times, and `accumulated_token_usage` are not imported; token accounting after import uses estimates. The explanations of excluded replies and of a failed search are fixed English text. diff --git a/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.zh.md b/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.zh.md new file mode 100644 index 0000000000..71bbf6a46f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.zh.md @@ -0,0 +1,266 @@ +# Agent Note: 导入 DeepSeek 官网会话导出 + +Status: implemented + +[English](2026-11-11-deepseek-chat-export-import.md) | 中文 + +## Problem + +DeepSeek 官网(chat.deepseek.com)的“导出全部会话”产物是一个 `deepseek_data-*.zip`。用户希望把这些历史会话带进 DSH 继续使用:在 Web GUI 里浏览原有的提问、思考与回答,并在任意一条会话上接着对话,模型能看到原有的上下文。没有导入功能时,DSH 只能从空白会话开始。 + +导出格式(`export_format_version: 3`)与 DSH Session 有四点结构差异,导入必须逐一处理: + +- 每个官网会话的 `messages` 是一棵靠 `parent_id` 连接的消息树(重新生成、编辑提问都会产生分叉);DSH Session 是线性的追加日志。 +- 消息 `id` 只在会话内自增,跨会话不可比较;`inserted_at` 在同一会话内也不单调(assistant 常比配对的 user 早几毫秒)。 +- 一条 assistant 消息的 `fragments` 交错记录思考、联网搜索、打开网页、正文等块;DSH 用 step 内的 `assistant/message` 加 `tool/call` / `tool/result` 表达同样的过程。 +- 产物还包含模板回答、失败状态、加密的链接正文、提示条等**不能**进入模型上下文的内容。 + +一个导出可能包含上千个会话和数百兆字节的图片;用户只需要最近的会话,并放进自己选择的工作区,而且 Host 在导入期间必须保持响应。 + +## Decision + +实验性包 [`@deepseek-ai/dsh-deepseek-chat-import`](../../../../packages/experimental/deepseek-chat-import/README.zh.md) 同时提供 Host 与 Client 两个编译面: + +- Host 面:一个 `TypertRemoteService`,在 `ctx.connection.fetch` 上注册精确上传路由 `POST /api/deepseek-chat-import/archive?workspaceId=…`,并提供 `@Remote limits()` 方法。路由把上传的 ZIP 缓存在内存中,把最近的会话逐个写成所选工作区中的持久化 DSH Session,并以流式方式报告进度。 +- Client 面:在侧栏“新建会话”右侧放一个导入按钮。点击后弹出对话框,包含导出文件字段(浏览器原生文件输入,`accept=.zip`)和工作区字段(渲染 ui-workspace 的 `workspace.picker` Factory);浏览器上传文件,显示上传与导入进度以及结果。 + +按钮位置通过 ui-sidebar 的 HOC slot `sidebar.session.action` 提供:插件在那里包裹新建会话行的内容,原样返回后追加自己的按钮,因此装饰该行不新增包裹元素。不在 ui-sidebar 里写死按钮,因为那样侧栏外壳要直接调用导入插件的 Remote 命名空间,把业务逻辑放进了外壳。工作区字段复用新建会话的工作区菜单,即 `workspace.picker` Factory:列出已有工作区,并提供“添加工作区…”,通过 `workspace.picker.directoryFlow` 洞运行已组合的目录选择器。 + +该能力作为 Official 实验性可选 bundle 发布:包本身声明 `dsh.bundle.patch` 并插入自己的 `deepseek-chat-import` 行,列入 `OPTIONAL_BUNDLES`,在用户于插件页启用之前保持关闭。默认 Web 组合不挂载它。 + +### 用户流程 + +1. 用户在插件页启用“DeepSeek 会话导入”,然后点击“新建会话”右侧的导入按钮(窄栏模式下是一个图标按钮,位于“新建会话”图标下方)。只有 owner 看得到这个按钮。 +2. 对话框需要 DeepSeek 官网导出的 ZIP 文件(`deepseek_data-*.zip`)以及接收会话的工作区。工作区字段预选当前会话所在的工作区;“添加工作区…”通过目录选择器添加新目录。 +3. 导入时,浏览器先调用 `limits()`;大于 `maxUploadBytes` 的文件在上传前就被拒绝。服务页面随后显示上传百分比、Host 读取压缩包时的不确定进度,以及写入会话时的“正在导入 n/K”。Host 跑在页面之外执行上下文中的页面经 `__DSH_TRANSPORT__.fetch` 携带压缩包,该载体不报告字节进度,因此对话框从读取阶段开始。关闭对话框会中止请求。 +4. 成功后对话框以单数或复数形式显示导入了多少个会话、导入到哪个工作区、多少个会话超出上限、多少个会话无法导入。 +5. 失败时对话框显示该失败原因的本地化说明,或意外错误的信息。 +6. 无论导入以何种方式结束,浏览器都会刷新会话列表,使失败或取消之前已写入的会话出现在列表中。 + +用户随后打开任一导入的会话,看到原始的提问、思考、搜索卡片和回答;发送新消息时,Agent 以默认模型和导入的历史为上下文继续。 + +### 包结构 + +| 文件 | 职责 | +|---|---| +| `src/types.ts` | 只放浏览器安全的线上类型:结果、失败原因、上限、NDJSON 应答行,以及 `deepseekChatImport/owner-only` Remote 错误码 | +| `src/protocol.ts` | `UPLOAD_PATH` 及其相对文档的形式 `UPLOAD_ROUTE` | +| `src/format.ts` | 用 zod 校验 `manifest.json`、`chat_sessions/{id}.json` 和本包映射的 fragment 类型;未知 fragment 类型原样保留给转换器忽略 | +| `src/archive.ts` | `openExportArchive(bytes, maxEntryBytes, signal)`:ZIP 中央目录、只解压调用方所需条目的流式扫描,以及按名读取单个条目 | +| `src/conversation.ts` | 纯函数 `selectBranch(file)` 与 `convertConversation(file, options)`:消息树到种子事件 | +| `src/importer.ts` | `importDeepseekChatExport(deps, request, signal)`:索引选择、图片扫描、会话扫描、写入与附加工作区 | +| `src/upload.ts` | `createUploadRoute(handler)`:请求校验、有界缓存、流式应答与取消 | +| `src/index.ts` | `DeepseekChatImportService`、`Config`、单一导入槽位与 `@Remote limits()` | +| `src/client/*` | 按钮、对话框、经页面载体或 XHR 的浏览器上传、locale 字典、slot 注册 | +| `cordis.patch.yml` | 可选 bundle 的 `deepseek-chat-import` 行 | + +`src/conversation.ts` 不读文件、不访问服务、不取当前时间,所有 id 由调用方注入,可以确定性地单测。`src/importer.ts` 通过一个显式的依赖对象使用持久化、投影缓存、附件服务与工作区注册表,单测可以接真实的 JSONL 持久化。 + +### Host 路由与 Remote + +```ts +/** Deployment limits of the importer. */ +interface Config { + /** Most Sessions one import writes, choosing the conversations the export index lists as most recently updated; default 1000. */ + maxSessions: number + /** Largest export archive, in bytes, one upload may carry; default 512 MiB. */ + maxUploadBytes: number + /** Largest declared uncompressed size, in bytes, of one archive entry; default 256 MiB. */ + maxEntryBytes: number + /** Largest UTF-8 size, in bytes, of an imported title; default 80. */ + maxTitleBytes: number +} +``` + +`POST /api/deepseek-chat-import/archive?workspaceId=…` 是共享 API 通道上的精确路由,只有 owner Peer 能访问。`limits()` 以 `deepseekChatImport/owner-only` 拒绝所有非 owner 调用方,因此共享会话的访客等非 owner principal 永远不能导入。路由要求 `content-type: application/octet-stream`(否则 415)和非空的 `workspaceId`(否则 400);其他方法在路由运行前就由共享处理器应答。 + +服务拥有一个导入槽位。请求先占用槽位,否则应答 `busy`;随后解析工作区(`workspace-not-found`),把流式请求体读入一个按有效 `content-length` 分配的缓冲区,只有请求体比声明的更长时才扩容,直到读完或超过 `maxUploadBytes`(`too-large`)。上传内容从不写入磁盘。每个请求拥有一个 AbortController,与请求信号以及应答体的取消合并。卸载插件会中止正在运行的导入(包括仍在上传的请求体),并且只有在导入停止写入后才完成卸载。 + +应答为 `application/x-ndjson`,带 `cache-control: no-store, no-transform`:先是进度行 `{ type: 'progress', done, total }`,然后恰好一行 `{ type: 'outcome', outcome }`,其中 `outcome` 为 `{ ok: true, value: DeepseekChatImportResult }` 或 `{ ok: false, error: { reason, message } }`。Web server 逐块写出应答体,浏览器在完整的行到达时读取,代理一次性交付整个应答体时同样可用。浏览器校验每一条解码后的行:必须是已知 `type` 的对象,并携带该类型对应的字段,因此 `null`、缺少 `done` 的行,或 `ok` 不是布尔值的 outcome 都会让应答以无效失败,而不是在 `onload`/`onprogress` 回调里抛错。`reason` 取 `too-large | unreadable-archive | missing-manifest | missing-index | unsupported-version | no-conversations | workspace-not-found | busy` 之一。意外失败会记入 Host 日志,并在没有 outcome 行的情况下结束应答体,浏览器将其报告为上传失败。 + +`attachments` 与 `sessionProjectionCache` 是通过 `ctx.get()` 读取的可选服务:缺少附件服务时图片变成伪造的文件卡片;缺少投影缓存时,冷会话的列表行在会话首次打开前不显示原标题与活动时间。 + +### 读取导出产物 + +- `openExportArchive` 用 fflate 的异步 `unzip` 和一个不接受任何条目的 filter 读取中央目录,打开阶段不解压任何条目。不是可读 ZIP 的字节报 `unreadable-archive`。条目名必须唯一:按名读取按名字选择,重名会让所有同名条目一起解压,绕过逐条上限;重名同样报 `unreadable-archive`。重复检测只覆盖中央目录:第二个本地文件头改成已有条目名时不会被发现,因此扫描可以交付比索引列出的更多的会话,写入数量也没有额外限制。 +- `manifest.json` 与 `chat_session_index.json` 在扫描前按名读取。`manifest.json` 缺失或损坏分别报 `missing-manifest` 或 `unreadable-archive`;索引缺失、损坏或无法解析报 `missing-index`;条目超过 `maxEntryBytes` 报 `too-large`;`export_format_version` 不是 3 报 `unsupported-version`。 +- 随后一次流式扫描按压缩包顺序只解压被选中的会话条目,并在每 64 KiB 压缩包字节之间让出事件循环。解压是同步的(`UnzipInflate`),因此一个分块的输出在扫描让出之前就已产生;声明很小、实际解压超过 `maxEntryBytes` 的条目会一直解压到条目结束,上限此时只阻止字节被保留,而不阻止这部分工作。中央目录在解压前给出每个条目声明的大小:超过 `maxEntryBytes` 的条目不会被解压;未压缩(stored)条目声明的大小与实际字节不一致时按损坏拒绝。接受的条目整块累积后交付;产出超过条目声明大小或 `maxEntryBytes` 时拒绝。 +- 每个选中会话的图片由单独一次流式扫描在任何会话被解析之前保存。该扫描只解压 `chat_sessions/{id}_files/…` 中 id 属于索引所选会话的条目,一次一个,并记录每条目的已保存引用或失败原因。由于它先运行,压缩包条目顺序不影响结果,会话扫描也不再按名读取任何图片。 +- 按名读取用于 manifest、索引与补位会话。每次调用都会重新解析整个中央目录,因此一个补位会话会为其会话文件多出一次目录扫描;它的图片由再一次图片扫描收集,而不是每张图片读取一次。它最多返回条目声明的大小,解压结果更大时截断;扫描把同一情况报告为大小失败。 +- 会话来源是 `chat_sessions/` 下直接的 `*.json` 条目(不进入 `*_files/` 子目录)。索引未选中的条目不会被解压。选中的会话在到达时解析并转换;超过上限、已损坏、不是 JSON,或未通过 zod 校验与转换的会话记入 `skipped`。 + +### 选择会话 + +1. `chat_session_index.json` 为导出携带的会话排序:`updated_at` 降序,其次 `inserted_at` 降序,最后 id 升序。导入写入其中最新的 `total = min(maxSessions, 索引行数)` 个,按压缩包顺序。 +2. Session 持久化与工作区成员关系按会话时间而非写入顺序排序,因此扫描按压缩包顺序写入不会改变会话列表。 +3. 压缩包中没有的会话,或转换、存储失败的会话记入 `skipped`;由索引中下一个更旧的会话按名补位。`omittedByLimit` 统计索引列出但任何尝试都未触及的会话。 +4. `sessionIds` 按索引顺序从新到旧列出已导入的会话,与写入顺序无关。 + +### 分叉树线性化(`selectBranch`) + +- 选中的消息是 `current_message_id` 指定的那条。从它沿 `parent_id` 回溯到 `parent_id === null` 的根,再反转,得到一条链。其他分支丢弃,每个会话只生成一个 Session。 +- `current_message_id` 缺失、为 `null` 或指向不存在的消息时,改选 `id` 最大的消息。消息 id 在会话内自增,子消息的 id 总大于父消息,所以这个兜底一定是叶子。 +- `messages` 为空、消息 id 重复、`parent_id` 指向不存在的消息或回溯出现环时,该会话无效并记入 `skipped`。 + +### 消息链到 Session 事件(`convertConversation`) + +链上的消息按“每个 USER 消息开一个 turn”分组:USER 消息与紧随其后的 ASSISTANT 消息组成一个 turn。没有前置 USER 的 ASSISTANT 消息(只可能来自异常数据)被丢弃。回答状态为 `CONTENT_FILTER` 的 USER 消息与该回答一起丢弃:两个节点都不产生事件,界面上什么都不显示,后续 turn 的编号不留空缺。链以 USER 结尾时最后一个 turn 只有提问。不要求 user / assistant 严格交替:被排除的回答不会产生 `assistant/message`,下一个提问直接跟在上一个提问之后,这与 DSH 中一个 turn 收到多条 steer 消息的历史形态一致。没有剩余 turn 的会话转换失败并记入 `skipped`。 + +一个 turn 的事件序列: + +| 顺序 | 事件 | 说明 | +|---|---|---| +| 1 | `turn/start {turn: n}` | 时间为 USER 消息时间 | +| 2 | `step/start {turn: n, step: 1}` | 第一个 turn 中其后紧跟一个空的 `system/message`(`surfaceOp: 'append'`),作为 surface 节点 0 | +| 3 | `user/message`(`surfaceOp: 'append'`) | `source: { kind: 'user' }`,内容见下 | +| 4 | 每个 step 一组:`assistant/message`(`stream: []`)、每个工具调用一对 `tool/call` / `tool/result`、`step/end`;下一 step 以 `step/start` 开始 | 只用于正常完成的回答 | +| 5 | `step/end`(最后一个 step) | | +| 6 | `turn/end` | 正常回答为 `{ kind: 'completed' }`;被排除或缺失的回答为 `{ kind: 'error', error: { code, message } }` | + +空的 system 头不产生模型消息,也不渲染提示卡片。存储格式只接受作为 surface 节点 0 或位于这样的头之后的 `system/message`,每次读取存储的日志都会检查这一点;有了这个头,恢复的 Agent 会用真实的系统提示替换它,而不是在导入的历史之后追加一条系统消息。 + +文本为空或只有空白、且没有附件的用户消息写入一个内容为空字符串的文本块:Turn 与它的行都存在,而 DeepSeek 请求序列化会跳过这条空用户消息,因此该轮提问不在模型上下文里;首轮没有文本时,请求会直接从它的 assistant 消息开始。 + +第 1 个 turn 结束后,会话标题追加 `session/title { title, messageSeqs: [], source: { kind: 'user' } }`。标题经 session-title 的 `normalizeSessionTitle` 规范化:空白折叠为单个空格,文本截断到 `maxTitleBytes` 个 UTF-8 字节。没有标题,或标题规范化后为空时,不写标题事件。`user` 来源会固定标题,导入后不会再触发标题生成。 + +Assistant 消息的 `source` 为 `{ kind: 'model', provider: 'deepseek-chat-export', model: 'deepseek-chat-export' }`,没有 `replayState`。DeepSeek adapter 把这类外来历史的 reasoning 按无签名 thinking 发送,这是已有的跨模型历史路径。不写 `usage`、`request/header`、`request/context`、`model/selection`:恢复后的首个请求记 `initial` header,使用部署的默认模型,不出现“模型已切换”提示。 + +`stream` 写空数组。导出不包含逐 token 的流记录,伪造的流无法满足“流精确重建内容”的校验;空数组能通过现有校验,Web 的 assistant 行从 `message.content` 渲染。 + +**事件时间。** 每个事件的 `time` 取对应导出消息的 `inserted_at` 毫秒值,并按出现顺序钳制为单调不减(吸收 assistant 比提问早几毫秒的情况)。在一个回答内部,每遇到一个带 `elapsed_secs` 的 THINK,时间游标前进对应的毫秒数,后续 step 使用前进后的时间,使 step 时间间隔反映原始思考耗时。Session header 的 `createdAt` 取第一个事件的时间。 + +### Fragment 映射 + +| Fragment | 所在消息 | 映射 | 进入模型上下文 | +|---|---|---|---| +| `REQUEST` | USER | `user/message` 的文本 | 是 | +| `FILE`(图片) | USER | `export_path` 指向的条目存在且附件服务已保存时写 `{ type: 'image', attachment }`;否则写伪造的文件卡片 `{ type: 'file', attachment }`,引用不指向任何已保存对象 | 图片能力路由上是已保存图片;否则是文件句柄文本,其中给出的路径没有任何字节 | +| `FILE`(非图片) | USER | 伪造的文件卡片:`{ type: 'file', attachment }`,引用为 `attachmentId = sha256('deepseek-chat-export:' + file.id)`、`name = file_name`、`bytes = file_size`(缺失时 0);本体不在导出里,因此不存在对应对象,句柄里的路径读不到内容 | 是,为文件句柄文本 | +| `THINK` | ASSISTANT | 当前 step 的 `{ type: 'reasoning', text }`;空文本忽略 | 是(按 adapter 规则) | +| `RESPONSE` | ASSISTANT | 当前 step 的 `{ type: 'text', text }`;空文本忽略 | 是 | +| `TOOL_SEARCH` | ASSISTANT | `web_search` 调用:参数 `{"queries": [...]}`;结果正文由 `dsh-tool-web` 的 `formatSearchOutput` 生成;`meta` 为 `{ sources: [{ url, title, snippet, publishedAt }], truncated: false }`,渲染为标准搜索卡片。`WIP` 视为未完成并略去;`FAILED` 生成 `isError: true` 的结果,文本固定为 `Error: the export records this search as failed.`;缺少 `status` 时按 `FINISHED` 处理。查询全为空或空白时忽略 | 是 | +| `TOOL_OPEN`(有 url) | ASSISTANT | `web_fetch` 调用:参数 `{"url": ...}`;结果正文为标题、URL 与“页面正文未包含在导出中”的说明;`status: FINISHED` 时 `meta` 为 `{ url, statusCode: 200, truncated: false }`,渲染为标准抓取卡片;`FAILED` 时结果为 `isError: true`;`WIP` 忽略 | 是 | +| `TOOL_OPEN`(url 为 null 或空串) | ASSISTANT | 不生成任何内容:导出端会在一个 stage 的真实打开记录旁写一条全 null、只带 `stage_id` 和 `group_id` 的记录,它不指向任何页面 | 否 | +| `TOOL_FIND` | ASSISTANT | 不生成任何内容:官网把它显示成单独一行,消息里没有对应的块 | 否 | +| `TOOL_IMAGE_SEARCH` | ASSISTANT | 不生成任何内容:官网不为图搜显示任何一行,回复的思考里已经写明模型从结果中得到了什么;被搜索的图片本身不在导出里 | 否 | +| `READ_LINK` | ASSISTANT | 每个结果一行 Markdown 链接:`[title](url)`;没有 title 时用 url 本身作文字,没有 url 时只写 title,两者都没有则跳过;正文仍是没有密钥无法解密的签名 | 是(文本) | +| `TIP` | ASSISTANT | 不生成任何内容:这是官网界面的提示横幅,不是模型输出 | 否 | +| `CONTENT_RISK` | ASSISTANT | 忽略:固定免责声明,没有信息量 | 否 | +| `PARTIAL_FILE_READ` | ASSISTANT | 不生成任何内容:官网把它显示成单独一行 | 否 | +| `TEMPLATE_RESPONSE` | ASSISTANT | 整个回答被排除,`turn/end` 以模板文本作为错误信息 | 否 | +| 未知类型 | 任意 | 忽略 | 否 | + +**Step 切分。** 带 `stage_id` 的 fragment 在取值不变时同属当前 step;只有工具 fragment 会开启或改变 stage,因此 stage 变化总是开新 step,带 stage 的 step 一定含工具调用。不是最后一个的 step 如果没有工具调用,续聊历史里就会出现两条相邻的 assistant 消息,而实时 agent loop 从不产生这种结构,因此只含文本的 step 会与下一次调用合并。不带 `stage_id` 的 fragment 沿用旧规则:工具调用之后再出现 THINK 或 RESPONSE 时结束当前 step 并开下一个,本身不带 stage 的记录按文本处理。`WIP` 记录被略过,不切分 step。连续多个 `stage_id` 相同的工具 fragment 落在同一个 step,相当于一次并行调用。被忽略的 fragment 不切分 step,因此“THINK、三个 url 为 null 的 TOOL_OPEN、THINK”仍是一个 step,只包含两个 reasoning 块。 + +以官网的“边想边搜”为例,`THINK, TOOL_SEARCH(stage 1), THINK, TOOL_OPEN×4(stage 2), THINK, RESPONSE` 映射为三个 step:①思考 + `web_search`;②思考 + 4 个 `web_fetch`;③思考 + 正文。中间没有思考时,紧邻的 `TOOL_SEARCH(stage 1)` 与 `TOOL_OPEN(stage 2)` 会拆成两个 step,因为第一个 step 已经持有搜索调用。 + +**Step 内的块顺序。** 一个 step 的 `assistant/message` 先放该 step 的文本块(思考、正文、链接行),再放工具调用块,两组各自保持记录顺序。因此导出中排在同一 step 工具调用之后的文本会存到该调用之前,而 step 顺序与所有跨 step 顺序仍与导出一致。把文本交叠到工具调用之后的同一条 assistant 消息里,不符合实时 loop 产生的任何 step。 + +**ID。** 消息 id、工具调用 id 都由调用方注入的 `createId()` 生成(生产用 `randomUUID`),`tool-call` 块 id、`tool/call.callId`、`tool/result` 消息的 `source.callId` 与 `toolCallId` 相同。 + +### 回答状态映射 + +导出文档要求非 `FINISHED` 的消息和模板回答不能进入模型上下文。被内容过滤撤回的回答(`CONTENT_FILTER`,官网显示为已撤回)按上文与其提问一起丢弃。其他被排除的回答都不写 `assistant/message`,也不写 `assistant/attempt`(Web 不展示 attempt,而且“用户消息 + attempt + 可重试错误码”会让 GUI 提示继续生成)。用户看到的是 turn 末尾的错误行,显示原因和代码: + +| 原回答 | `turn/end.reason.error.code` | `message`(英文,写入日志) | +|---|---|---| +| `FAILED` / `TIMEOUT` / `CONTEXT_LENGTH_EXCEEDED` / `INCOMPLETE` / `WIP` | `DEEPSEEK_EXPORT_FAILED` / `DEEPSEEK_EXPORT_TIMEOUT` / `DEEPSEEK_EXPORT_CONTEXT_LENGTH_EXCEEDED` / `DEEPSEEK_EXPORT_INCOMPLETE` / `DEEPSEEK_EXPORT_WIP` | The original reply ended with status "{STATUS}" and is excluded from the model context. | +| 其他任何状态 | `DEEPSEEK_EXPORT_UNFINISHED_REPLY` | 同样的说明,状态带引号 | +| 含 `TEMPLATE_RESPONSE` | `DEEPSEEK_EXPORT_TEMPLATE_RESPONSE` | 模板文本本身 | +| `FINISHED` 但没有任何可导入内容 | `DEEPSEEK_EXPORT_EMPTY_REPLY` | The original reply has no importable content. | +| 链以 USER 结尾(没有回答) | `DEEPSEEK_EXPORT_NO_REPLY` | The export contains no reply to this message. | + +错误码是固定字符串;来自导出的文本只出现在说明里。这些代码不在 session-controller 的可继续生成代码集合内,不会出现“继续生成”。提问本身保留在上下文里。 + +### Session 写入 + +导入不创建 live Agent,直接写持久化层。在扫描之前检测到的失败(压缩包不可读、manifest 缺失、超限或版本不支持、没有可导入的会话、上传超限)不写入任何内容;压缩包结构在扫描中途损坏时,会以 `unreadable-archive` 失败,而在那之前交付的会话已经写入。每个会话在写入前都完成转换,并经 `Session.create` 校验种子;失败的会话被跳过,不影响其他会话。每个选中的会话在压缩包条目到达时转换并写入;失败后补位的会话则按名读取。对每个会话: + +1. 检查目标工作区仍已登记且目录存在;否则以 `workspace-not-found` 停止,之前写入的会话保留。 +2. 用图片扫描已保存的引用转换会话。转换或种子校验后来失败的会话,其图片已经保存,并且没有任何事件引用它们。 +3. `Session.create(id, seed, header)` 做与 live append 相同的种子校验(JSON 可序列化、seq 连续、surface 转换合法、消息字段合法),校验用的分离实例随即丢弃。 +4. `ctx.sessionPersistence.create(header)` → `handle.append(events)` → `handle.flush()` → `handle.close()`(失败时也关闭)。header 为 `{ version: SESSION_FORMAT_VERSION, id, createdAt, cwd, isSeeded: false }`,`cwd` 是工作区的规范路径。存储的事件不含 `session/end-seed`;首次打开时普通恢复路径追加该标记。 +5. 若投影缓存可用,`coldSnapshot(header, SessionLogOffset(0), events)` 刷新侧栏读取的缓存行(标题、最后提问时间、非空白)。 +6. `workspace.attachSession(id)`。失败时该会话以“stored as Session {id} but not added to the workspace”为原因记入 `skipped`;`SessionPersistence` 不提供删除,所以这个会话留在存储中、不属于该工作区。 + +转换得到的事件在处理下一个会话前释放;导入在会话之间让出事件循环,并在每一步检查取消。写入后的 Session 与其他冷 Session 一样出现在 `session/list` 中,打开时走普通的恢复路径。导入不新增 Session 事件类型,不改变 `SESSION_FORMAT_VERSION`,也不需要持久化类型确认。 + +### Client + +- ui-sidebar 声明 HOC slot `sidebar.session.action`(`scope: 'root'`,owner `{ wide: boolean }`),包裹新建会话行的内容,占用方以 `children` 收到该内容,返回它(可再包裹)并附上自己的控件。导入按钮在“新建会话”按钮右侧渲染(宽栏同一行,“新建会话”按钮占剩余宽度;窄栏纵向排列在“新建会话”图标下方)。 +- 插件的 client 面 `$mount` 自己的 `/remote` 贡献(与 `dsh-api-remote-access` 相同的自挂载方式,不进入 `dsh-api-remotes` 聚合),作为 `sidebar.session.action` 层注册 `ImportSessionsAction`。它先渲染行内容,再渲染触发按钮,最后渲染对话框;不能导入的 Peer 会原样得到行内容,因此新建会话按钮继续渲染。按钮仅在 `useRemoteAccess('deepseekChatImport/limits')` 为真时显示;对话框是该层的本地状态,通过 `Modal` portal 渲染。 +- 服务页面上的上传使用 `XMLHttpRequest`,因为 Fetch 不提供上传进度。Host 跑在页面之外执行上下文中的页面(静态 Cloudflare Pages 预览)提供 `__DSH_TRANSPORT__.fetch`:压缩包经该载体传输,没有字节进度,直接进入读取与导入阶段。URL 是相对 `document.baseURI` 解析的 `UPLOAD_ROUTE`,因此加路径前缀的代理仍然可用。非 200 应答、没有 outcome 行的应答、不是合法协议值的行或连接失败归为 `upload-failed` 结果;抛出的错误以未知失败文案显示。 +- 载体选择没有复用 `@deepseek-ai/dsh-client-file-upload`。该包的服务会缓冲整个应答,流式 NDJSON 进度会丢失,而且它的 `post` 方法不在公开接口上;把选择留在本包内同时保住了进度行与包依赖边界。 +- 文案走 8 种语言的 locale 字典,英文用 sentence case;摘要行有 `.one` / `.other` 两种形式,按 `count === 1` 选择。 + +### Realization + +`sidebar.session.action` 是 HOC 层而不是 list,因为占用方装饰的是行的内容,而不是渲染在旁边:它把该内容作为 `children` 接收、原样返回(可再包裹)并追加自己的控件,不新增包裹元素。list 条目会渲染为行内容的兄弟节点,而 rail-in 淡入作用于 slot outlet 的子节点,因为 `display: contents` 的 outlet 锚点本身无法承载动画。 + +这项义务只是契约。没有追加内容或无权操作的占用方必须原样返回 `children`,因为渲染器只兜住抛错的层。层也可以合法地不渲染 `children`,那会移除新建会话按钮,因此没有运行时检查能替代这项义务。 + +### 图片 + +- 图片扫描按压缩包顺序遍历选中会话的每个图片条目,不解析会话。它只解压 `chat_sessions/{id}_files/…` 中 id 属于索引所选会话的条目,以条目的扩展名与文件名调用 `ctx.attachments.saveImage({ data, mediaType, name })`,并按条目名记录引用或失败原因。扩展名不是 png / jpg / jpeg / webp / gif 时记为类型不支持,且不解压该条目。 +- `convertConversation` 为 `export_path` 已被扫描保存的每个 `FILE` 条目写一个 `image` 块(在文本之前),否则写伪造的文件卡片。 +- 单张图片缺失、类型不支持、超过上限、损坏或被拒绝时只把该图片写成伪造的文件卡片并记一条 Host 警告,会话照常导入。条目缺失报告 `not in the export`;大小、损坏、类型不支持或存储失败报告自身原因。附件存储按内容去重。 +- 图片扫描在选中分支与转换之前保存选中会话的每个图片条目。被撤回轮次的图片、导入丢弃的分支的图片,以及转换或 `Session.create` 种子校验后来失败的会话的图片,因此都会存成没有任何事件引用的附件。`SessionPersistence` 与附件存储都不提供删除。 + +### 测试 + +| 层 | 文件 | 覆盖 | +|---|---|---| +| 纯转换 | `tests/conversation.host.spec.ts` | `current_message_id` 选择与 id 最大兜底;按 id 线性化;REQUEST / THINK / RESPONSE;`stage_id` 与搜索/打开网页的 step 切分;失败、未完成与缺少状态的搜索;图搜与无地址的打开网页丢弃;页内查找、部分读取、提示均丢弃;Markdown 链接行;被排除回答的 turn-error 与固定错误码;丢弃被内容过滤的轮次;首个与后续 turn 的空文本块;标题规范化;伪造文件卡片;无效树。输出经 `Session.create` 校验,并用 `deriveMessages` 断言模型历史 | +| 压缩包 | `tests/archive.host.spec.ts` | 列出条目、单条目读取按声明大小截断、流式扫描、用高压缩比条目验证声明大小上限、声明大小不实、重复条目名、stored 条目大小不一致、损坏条目、取消 | +| 编排 | `tests/importer.host.spec.ts` | 带进度地从旧到新导入最近 K 个;携带全部新字段的 2026-11-12 合成归档;超限、损坏与无效的会话文件;失败后补足上限;补位链在某候选无效后继续;附加失败;工作区被移除;压缩包级失败;取消;图片由图片扫描保存(与压缩包顺序无关)或写成伪造文件卡片,主路径不按名读取图片 | +| 路由 | `tests/upload.host.spec.ts` | 请求校验;`too-large`;按声明长度分配缓冲区;一次一个导入;NDJSON 行;由应答、请求与卸载触发的取消 | +| 恢复 | `tests/resume.host.spec.ts` | 生产 agent loop 继续导入的会话;模型请求包含导入的历史,不含被撤回的轮次 | +| 组合 | `tests/composition.host.spec.ts` | 经 Loader 启动 Host;`limits()` 只允许 owner;上传后会话存入工作区;导入暂停时卸载会取消导入,并且只有在导入停止后才完成,不写入任何内容 | +| Client | `tests/import-sessions.client.spec.tsx`、`tests/mount.client.spec.ts`、`tests/upload.client.spec.ts` | 按钮出现条件、工作区预选、进度条与文案、单复数摘要、失败与抛错文案、每次尝试后刷新、NDJSON 行读取与校验 | +| Bundle | `scripts/optional-bundles.spec.ts` | bundle 能叠加在 Web profile 上组合,并解析出标题、描述与图标 | +| 快照 | `apps/web/tests/deepseek-chat-import.e2e.ts`、`snapshots/web/deepseek-chat-import/` | 经路由上传一个 2026-11-12 结构的合成导出,其中包含分支、思考、一对搜索与抓取、一条读取链接记录、一个被内容过滤的轮次和一个未完成的回答;一个导入的会话以一轮录制的模型回复继续,持久化日志可 keyless 回放 | + +## Alternatives considered + +**输入导出文件的 host 路径。** 最初的设计从 host 绝对路径读取 ZIP 或解压目录,并在旁边新建 `_workspace` 目录。用户不应输入 host 路径,浏览器也不知道这个路径,远程 Host 也访问不到用户本地下载的文件;浏览器上传对本地和远程 Host 的行为相同。 + +**在所选工作区中列出导出文件。** 用户先把 ZIP 放进某个工作区目录,再从 Host 端列表中选择。用户否决了这一方案,选择直接从浏览器上传文件。 + +**把上传暂存到磁盘。** 把上传写进临时文件可以去掉内存上限,但要增加清理逻辑、留下崩溃残留,并在 Host 上多出一份私有数据。压缩包只保存在内存中,受 `maxUploadBytes` 约束,服务一次只运行一个导入。 + +**在写入任何会话之前解压并校验全部会话。** 这能让“被拒绝的导出不写入任何内容”对转换失败也成立,但要同时在内存中保留所有会话文件和转换后的日志,并在整个导入期间阻塞事件循环。跟随 `chat_session_index.json` 的两次流式扫描:一次在不解析任何会话的情况下保存选中会话的图片,另一次在会话到达时逐个转换并写入。 + +**通过单独的流式 Remote 报告进度。** 路由应答本身已经经由 Web server 流式传输,同一请求上的 NDJSON 行不需要第二个通道,能保持进度与结果的顺序,并随请求结束。 + +**只导入最新的叶子。** 它一定是叶子,也不需要额外字段,但导出如果是在用户切回较旧分支之后生成的,就会静默导入另一条分支。`current_message_id` 是导出自己的线性化依据,id 最大的兜底则让没有该字段的归档仍可导入。 + +**按选中消息的 `inserted_at` 选择。** 它直接表示最后一条导入事件的时间,但需要每个会话的消息,选择阶段就得先解压整个压缩包。`chat_session_index.json` 携带官网自己的更新顺序,让选择阶段跳过未选中的会话;代价是顺序跟随改标题与置顶,而不是最后一条导入事件。 + +**通过 `ctx.agents.create({ seed })` 创建 live Agent。** 它是现有的受支持入口,但 `createdAt` 只能是当前时间,导入的会话会全部挤在侧栏顶部;导入上千个会话还会同时创建上千个 live Agent。直接写持久化层保留原始时间,也不占用运行时资源。 + +**每个分支一个 Session,或在 DSH 中表达分叉。** DSH Session 是线性日志;为分支各建 Session 会让一个官网会话变成多个难以区分的会话。需求明确只导入最新链。 + +**保留被内容过滤回答的提问并写错误行。** 官网把这类轮次显示为已撤回,用户决定两个节点都不导入;剩下的轮次与用户在官网看到的一致。 + +**把非 FINISHED 回答或模板回答写成 `assistant/attempt`,或写成 `interrupted` 的 `assistant/message`。** attempt 在 Web 中不可见,并会和可重试错误码一起触发“继续生成”;`interrupted` 的消息内容会进入模型上下文,违反导出文档的约束。 + +**在 ui-sidebar 中写死导入按钮。** 侧栏外壳需要依赖导入插件的 Remote 命名空间,把业务分支放进外壳;slot 的成本是一个声明和少量布局改动。 + +**新增 Session 事件类型来展示 TIP / CONTENT_RISK 或记录导入来源。** 需要扩展 `SessionEventMap`、持久化目录和 Web 渲染器,超出小规模导入的范围;这些提示不影响回答内容。 + +**在默认 Web 组合中挂载导入器。** 该能力是实验性的,而 release 包不能依赖实验性包。可选 bundle 让默认产品保持不变,并向启用它的用户提供导入功能。 + +## Consequences + +导入把官网历史带进 DSH,保留原始标题、时间、思考与搜索卡片,导入的会话通过普通恢复路径继续对话。Host 内存受压缩包(`maxUploadBytes`)加一个条目(`maxEntryBytes`)、一个转换后的会话以及已保存图片的引用约束,事件循环在会话之间保持响应。代价是取消或导入中途失败时只有已写入的会话保留,而且补位的会话要按名读取,并再跑一次图片扫描。 + +- **冷写入是 agent loop 之外的生产写入方。** 导入使用全新的 Session id 且写完即关闭句柄,不与 live Session 竞争所有权;如果持久化层以后假设所有写入都经过 agent loop(例如在创建时注册额外的派生状态),导入路径需要同步更新。 +- **已存储但未附加的会话会留在存储中。** `SessionPersistence` 不提供删除;导入在 `skipped` 中报告这样的会话及其 id。 +- **历史工具调用没有工具记录。** 导入的 `web_search` / `web_fetch` 调用没有对应的 `request/header.tools` 记录。若部署未注册这两个工具,或某个提供方拒绝引用未声明工具的历史,恢复时的首个请求会失败;退路是只映射文本。 +- **抓取卡片的状态码是推断值。** 导出只记录页面打开成功,没有 HTTP 状态码;`statusCode: 200` 让卡片按成功抓取显示。 +- **外来 reasoning 会重新发给模型。** 导入的思考内容按无签名 thinking 发送,增加恢复后首个请求的输入 token;KV cache 从该请求开始建立。 +- **重复导入产生重复会话。** 再次导入同一导出会写入新的会话;导入不记录哪些会话已经导入过。 +- **用户正在查看的分支决定导入内容。** `current_message_id` 选中导入链,因此用户切回较旧分支后再导出时,导入的就是那条分支;只有字段缺失或指向不存在的消息时才回退到最新的叶子。 +- **只针对一种导出结构。** 导入器面向 2026-11-12 结构。该结构新增的字段按可选读取,所以更旧的 v3 归档仍能导入,但其中的 `READ_LINK` 没有 url 与 title,链接行能写出的内容更少(更旧的 `TOOL_FIND` 查找词已不再读取)。 +- **`maxTitleBytes` 是单独的设置。** session-title 服务不公开它的上限,因此修改 session-title 的 `maxTitleBytes` 的组合需要把导入器的这个字段设为相同的值。 +- **放弃的内容。** 其他分支、被内容过滤的轮次、`CONTENT_RISK` 免责声明、`TIP`、`TOOL_FIND` 与 `PARTIAL_FILE_READ` 记录、`READ_LINK` 的加密正文、搜索结果的 `snippet` 与 `site_name`、`pinned` 标记、非图片文件本体、思考的逐 token 时间、`accumulated_token_usage` 都不导入;导入后的 token 计量使用估算值。被排除回答和失败搜索的说明是固定英文文本。 diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.i18n.yaml b/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.i18n.yaml new file mode 100644 index 0000000000..df13f53679 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-11-forge-provider-command-rules.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-11-forge-provider-command-rules.md +/agent-note-forge-provider-command-rules: + en: 1b602c42430a77b4 + zh: 8109a6a56901fb89 +/agent-note-forge-provider-command-rules/problem: + en: 29def264f0ee5401 + zh: 829cdb87861757f5 +/agent-note-forge-provider-command-rules/decision: + en: 17e84e777b0d7380 + zh: 2cc4720c9437a839 +/agent-note-forge-provider-command-rules/alternatives-considered: + en: a5bdd96f8e814246 + zh: 29a4f0026cd9abaf +/agent-note-forge-provider-command-rules/consequences: + en: 506047cfeb4645d3 + zh: b587240a69b46b8a diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.md b/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.md new file mode 100644 index 0000000000..86e647a4ce --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.md @@ -0,0 +1,33 @@ +# Agent Note: Forge provider command rules + +Status: implemented + +English | [中文](2026-11-11-forge-provider-command-rules.zh.md) + +## Problem + +[Session change request bindings](2026-10-09-session-change-request-bindings.md) recognized `gh` commands inside forge-session, so every new code host's CLI, such as `glab`, meant editing forge-session, and numeric selectors such as `glab mr view 7 -R group/app` need knowledge of that CLI's options and URL forms. Recognition feeds a Session projection, so it must stay deterministic for replay and checkpoints, and a provider enabled after a Session ran its commands should still bind them. + +## Decision + +Each provider registers a declarative `ForgeCommandRule` with `ctx.forgeSession.registerCommands`: its executable, creation subcommands, reference and raw API request subcommand groups with their own options, change request page path, JSON URL members, and a pure `select` that maps one parsed command to a URL or a read-only lookup. An API request, such as `glab api`, binds only the change request its path names, since its output can list many. [forge-github](../../../../packages/experimental/forge-github/src/commands.ts) registers `gh` and [forge-gitlab](../../../../packages/experimental/forge-gitlab/src/commands.ts) registers `glab`. forge-session keeps the shared parts: the literal shell tokenizer, option parsing, output reading, lookups in the call's shell, and the projection. + +The `forgeChangeRequests` state version derives from the recognized rules, `5 × 2^32` plus a hash of the sorted `id@version` pairs, so a checkpoint folded under another rule set is discarded and the log folds again. A registration that changes the set releases the projection and registers it at the new version, then refreshes watchers; the released handle stays readable during the swap. Ending a registration keeps its rule recognized until the service restarts or another rule replaces its id or executable. + +## Alternatives considered + +**Recognition per CLI inside forge-session.** Every provider change would edit forge-session, and its tests would own other CLIs' option sets. + +**Rules on `ForgeProvider`.** forge-session could read rules from `ctx.forge`, but the forge Service Definition would carry a field that only one Consumer uses. + +**Rules for later events only.** Folding only events after a registration skips the commands a Session ran before the provider loaded. + +**A fixed state version.** Folding with whatever rules are loaded breaks the rule that a restored checkpoint plus suffix replay equals full replay once the rules change. + +**Rebuilding on unregistration.** Providers unload before forge-session at shutdown, so every exit would checkpoint a smaller rule set and every start would refold every Session. + +**Option parsing in each provider.** The token walk would repeat in every provider. + +## Consequences + +A new provider rule or a raised rule version refolds every Session once; until a Session is opened again, the Session list shows no cached bindings for it, and re-registration emits no projection change event, so an open Session's summary shows the refolded bindings after a later event. Providers own their rule versions. Unloading a provider at runtime leaves its commands recognized until restart, though they run no lookup; starting without it removes the bindings that only its commands made, while binding records stay. Each start registers the projection without rules and once more after the providers register theirs. The [forge-session README](../../../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition rules. diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.zh.md b/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.zh.md new file mode 100644 index 0000000000..e91f7c5398 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.zh.md @@ -0,0 +1,33 @@ +# Agent Note: Forge 提供方命令规则 + +Status: implemented + +[English](2026-11-11-forge-provider-command-rules.md) | 中文 + +## Problem + +[Session 变更请求绑定](2026-10-09-session-change-request-bindings.zh.md)在 forge-session 内部识别 `gh` 命令,因此每接入一个代码托管平台的 CLI(如 `glab`)都要修改 forge-session;而 `glab mr view 7 -R group/app` 这类数字编号需要了解该 CLI 的选项与 URL 形式。识别结果供 Session 投影使用,因此必须在重放与检查点下保持确定;提供方在 Session 执行过命令之后才启用时,也应能绑定这些命令。 + +## Decision + +每个提供方通过 `ctx.forgeSession.registerCommands` 注册一条声明式的 `ForgeCommandRule`:其可执行文件、创建子命令、各带选项的引用子命令组与原始 API 请求子命令组、变更请求页面路径、JSON URL 成员,以及一个纯函数 `select`,把一条解析后的命令映射为 URL 或只读查询。API 请求(如 `glab api`)只绑定其路径指向的变更请求,因为其输出可能列出许多变更请求。[forge-github](../../../../packages/experimental/forge-github/src/commands.ts) 注册 `gh`,[forge-gitlab](../../../../packages/experimental/forge-gitlab/src/commands.ts) 注册 `glab`。forge-session 保留共用部分:字面量 shell 拆词、选项解析、输出读取、在调用所在 shell 中的查询,以及投影。 + +`forgeChangeRequests` 的状态版本由已识别规则派生,即 `5 × 2^32` 加上排序后 `id@version` 对的哈希,因此按其他规则集折叠的检查点会被丢弃,日志重新折叠。改变规则集的注册会释放投影并以新版本重新注册,再刷新监听方;切换期间已释放的句柄仍可读取。注册结束后,其规则仍被识别,直到服务重启或另一条规则替换其 id 或可执行文件。 + +## Alternatives considered + +**在 forge-session 内按 CLI 识别。**每次提供方变化都要修改 forge-session,其测试还要承担其他 CLI 的选项集。 + +**把规则放在 `ForgeProvider` 上。**forge-session 可以从 `ctx.forge` 读取规则,但 forge 的 Service Definition 就会带上只有一个 Consumer 使用的字段。 + +**规则只作用于之后的事件。**只折叠注册之后的事件,会漏掉 Session 在提供方加载之前执行的命令。 + +**固定的状态版本。**按当前加载的规则折叠,一旦规则变化,就违背了"恢复的检查点加后缀重放等于完整重放"这一规则。 + +**注销时重建。**关闭时提供方先于 forge-session 卸载,因此每次退出都会按更小的规则集写入检查点,每次启动都要重新折叠所有 Session。 + +**由各提供方解析选项。**逐词解析会在每个提供方中重复。 + +## Consequences + +新增提供方规则或提高规则版本,会使每个 Session 重新折叠一次;Session 再次打开之前,Session 列表不显示它的缓存绑定;重新注册不发出投影变化事件,因此已打开 Session 的摘要要在后续事件之后才显示重新折叠的绑定。规则版本由提供方负责。运行时卸载提供方后,其命令仍被识别,直到重启,但不再执行反查;不加载该提供方启动时,只由其命令产生的绑定会消失,绑定记录保留。每次启动时投影先在没有规则的情况下注册,提供方注册规则后再注册一次。识别规则见 [forge-session README](../../../../packages/experimental/forge-session/README.zh.md#use-this-package)。 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-09-15-shipped-optional-bundles.i18n.yaml b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml index 970eaf9557..1472ca2a1e 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml @@ -9,8 +9,8 @@ en: dc43ba84345e1405 zh: dbc03572ab7710d2 /agent-note-ship-optional-bundles-with-the-installation/decision: - en: 0f3e0daee65b6510 - zh: 2e9c8000da75fb6c + en: e4ecfa61b6f71d8c + zh: a33d16e5843cf097 /agent-note-ship-optional-bundles-with-the-installation/alternatives-considered: en: 95b48b61757f1f13 zh: e9fb2d6ea492a4bc diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md index aaa055f7b5..179bb4b807 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md @@ -10,7 +10,7 @@ The Web plugin page manages only the bundles a person installed into the profile ## Decision -The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles. The [persistent-terminal bundle](../../../../packages/experimental/terminal-bundle/README.md) remains available to the Host but has no page switch, even when enabled; its existing profile selection remains intact. +The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles. Default-product isolation keeps its rules with one declared exception: an optional bundle's dependency graph is outside the default product. The static gate skips the `dependencies` edge from `@deepseek-ai/dsh` to a listed bundle and still rejects a runtime import, a shipped composition, a preset, or a default template that names it, an experimental dependency the list does not name, and a listed name that is not a runtime dependency or not a bundle. The workspace-constraints check accepts the same `dependencies` edges and no other runtime section, and the packed-install release check skips them from the installed entry package while requiring each listed bundle to be installed. diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md index 6135f08763..0f184372ef 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md @@ -10,7 +10,7 @@ Web 插件页只管理用户装进 profile 的组合包。像 Agent Teams 这样 ## 决策 -启动器在 `OPTIONAL_BUNDLES`(`packages/util/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。[持久终端组合包](../../../../packages/experimental/terminal-bundle/README.zh.md)仍可供 Host 使用,但即使已启用也不提供页面开关;已有的 profile 选择保持不变。 +启动器在 `OPTIONAL_BUNDLES`(`packages/util/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。 默认产品隔离的规则保持不变,只声明一个例外:可选组合包的依赖图在默认产品之外。静态门禁跳过从 `@deepseek-ai/dsh` 到列表中组合包的 `dependencies` 边,仍然拒绝运行时 import、随附组合、preset 或默认模板对它的引用,拒绝列表没有点名的实验依赖,也拒绝不是运行时依赖或不是组合包的列表项。workspace 约束检查接受同样的 `dependencies` 边而不接受其他运行时依赖段;发布时的 packed-install 检查对已安装入口包跳过这些边,并要求列表中的每个组合包都已安装。 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-04-dsh-home-path-categories.i18n.yaml b/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.i18n.yaml new file mode 100644 index 0000000000..0776d16e62 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-11-04-dsh-home-path-categories.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-04-dsh-home-path-categories.md +/agent-note-harness-home-path-categories: + en: 007593701a0d6bf5 + zh: 3bf266378e3bba08 +/agent-note-harness-home-path-categories/problem: + en: 3e98d90944daeb05 + zh: 596f750e878f3e69 +/agent-note-harness-home-path-categories/proposal: + en: 76abf280dfdba9bc + zh: 0ad29c3c67208086 +/agent-note-harness-home-path-categories/proposal/path-helper: + en: 6f34630c5b05b0d7 + zh: 2106fdbf4f5ca852 +/agent-note-harness-home-path-categories/proposal/conventional-top-level-entries: + en: 940f404152322a33 + zh: 5668927394d05723 +/agent-note-harness-home-path-categories/proposal/other-existing-entries: + en: a8242fc3bbe3fe7a + zh: b90f9e9deda18e78 +/agent-note-harness-home-path-categories/proposal/outside-the-home: + en: 9d78c323d3f9d159 + zh: e11a87b74fe11e5c +/agent-note-harness-home-path-categories/alternatives-considered: + en: cfa4bc5557af4117 + zh: 7971e54d5770d9aa +/agent-note-harness-home-path-categories/acceptance-criteria: + en: bf87d444099ebb2b + zh: 8315e6ddc07fe3c7 +/agent-note-harness-home-path-categories/risks: + en: aa70b3a0243a1853 + zh: 64c74b62d3a42472 diff --git a/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.md b/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.md new file mode 100644 index 0000000000..0751a78567 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.md @@ -0,0 +1,83 @@ +# Agent Note: Harness home path categories + +Status: proposed + +English | [中文](2026-11-04-dsh-home-path-categories.zh.md) + +## Problem + +Each package builds its own path under `$DSH_HOME` (default `~/.dsh`), so the home root mixes user configuration, durable records, logs, indexes, and downloads. A new service or plugin has no rule for where its files belong, and some owners resolve the home by hand: [liveshare](../../../../packages/experimental/liveshare/src/host/share-host.ts) reads `process.env.DSH_HOME` directly, and [migrate-sessions-to-v4](../../../../scripts/migrate-sessions-to-v4.ts) defaults to `~/.dsh/sessions` without reading `DSH_HOME`. + +## Proposal + +Group paths under `$DSH_HOME` by the kinds the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir/latest/) uses. Every category stays inside `$DSH_HOME`; the harness does not read `XDG_*` variables. + +| Category | Holds | Losing it | +|---|---|---| +| `config` | Files a person writes or edits to configure the harness | Loses the user's configuration | +| `data` | Durable records: user work, sign-ins, installed software | Loses user work, sign-ins, or installed software | +| `state` | Records that persist across runs but are not user work: logs, indexes, ids, retained outputs | Resets history; the harness keeps working | +| `cache` | Content the harness can rebuild or download again | Costs time or bandwidth only | +| `backup` | Backup archives the harness writes, such as compressed copies of the home or a profile | Nothing; the archives are not read during normal operation | + +There is no `runtime` category, the XDG kind for sockets and pid files, because no owner needs one under the home: locks sit beside the file they protect, and live sockets stay in the operating-system temporary directory because Unix socket paths have a length limit. `backup` is not an XDG kind: it gives backup archives one directory that users and cleanup tools can empty at any time without affecting a running harness or the records the archives copy. + +### Path helper + +[`dshPath(category, ...segments)`](../../../../packages/util/home-paths/src/index.ts) in `@deepseek-ai/dsh-home-paths` returns `//` without creating directories; `dshPath({ category, dshHome }, ...segments)` resolves an explicit configured home. Loader `!!js` config expressions receive the same function beside `dshHomePath`. A new path under the home uses `dshPath` and passes its owner's directory name, normally the package name without the `@deepseek-ai/dsh-` prefix, as the first segment. `dshHomePath` remains for the existing top-level entries, and `dshCachePath` is `dshPath('cache', ...)`. + +### Conventional top-level entries + +Users open, edit, and script against these entries directly, and documentation across the repository names them, so they keep their current top-level locations and are not candidates for moving: + +| Path under `$DSH_HOME` | Owner | Kind | +|---|---|---| +| `.env` | [app-boot](../../../../packages/boot/app-boot/README.md) environment layer | config | +| `cordis.patch.yml` | [app-boot](../../../../packages/boot/app-boot/README.md) home patch layer | config | +| `AGENTS.md` | [agent-instructions](../../../../packages/context/agent-instructions/README.md) | config | +| `skills/` | [skill-filesystem](../../../../packages/skill/skill-filesystem/README.md) | config | +| `.credentials.yaml` | [credentials-local](../../../../packages/credentials/credentials-local/README.md) | data | +| `profiles//` | [app-boot](../../../../packages/boot/app-boot/README.md), plugin-manager, Desktop (`desktop` profile and its `lock`) | data | +| `sessions/` | session-persistence-jsonl root in the base and sdk-minimal bundles | data | +| `cache/` | already the `cache` category | cache | + +Files inside a profile directory, such as `node_modules/`, `pnpm-lock.yaml`, `compatibility.json`, `.plugin-manager/`, `.plugin-market/repositories/`, `created-plugins/`, and `cua-*.lock`, stay with their profile because pnpm and the profile tools address them relative to it. The legacy `settings.yaml` importer keeps reading the home root because that file is the import source. + +### Other existing entries + +These entries have no user-facing convention. Each row names the category it belongs to; moving it is a separate change that needs a data migration plan: + +| Current path under `$DSH_HOME` | Category | Owner | Why | +|---|---|---|---| +| `storages/` | `data` | storage-json root in the base bundle | Workspace, schedule, and other domain records; its `session_projcache` unit is a rebuildable cache, but storage-json has one root | +| `attachments/v1/` | `data` | [attachment-local](../../../../packages/attachment/attachment-local/README.md) | User attachments; Session history records their absolute paths | +| `dsh-runtimes/` | `data` | Desktop offline runtimes ([workspace-dependencies](../../../../packages/bundle/web-app/cordis.patch.yml)) | Installed software that may hold user additions | +| `liveshare/` | `data` | [liveshare](../../../../packages/experimental/liveshare/README.md) owner state and credential | Holds management tokens | +| `.anonymous-user-id` | `state` | [anonymous-user-id](../../../../packages/identity/anonymous-user-id/README.md) | Losing it only issues a new id | +| `logs/` | `state` | CLI startup failure reports | Logs | +| `llm-deepseek/files-v3.json` | `state` | [llm-deepseek](../../../../packages/llm/llm-deepseek/README.md) upload index | Derived index | +| `office-kit/outputs/` | `state` | [office-kit](../../../../packages/document/office-kit/README.md) | Retained conversion outputs removed after their retention period | +| `speech-to-text/sensevoice/` | `cache` | voice-input-bundle | Downloadable models | +| `cache/attachments/` | `cache` | attachment-local request images | Already in `cache` | + +### Outside the home + +These locations are out of scope: `~/.agents` (`DSH_AGENTS_HOME`), shared with other agent tools; Electron `userData` and `logs`, managed by Electron; the Python SDK resource cache `~/.cache/deepseek-harness/resources` (`DSH_RESOURCE_CACHE`), shared across homes; spill and subprocess output directories under the operating-system temporary directory; and developer or release script state such as `~/.dsh-desktop-signing`. + +## Alternatives considered + +**Move every entry now.** A first draft moved all entries, including the conventional ones, into category directories with no fallback. It made every existing home look empty after an upgrade, broke absolute attachment paths recorded in Sessions, and renamed files users edit by hand. The conventional entries above now stay, and the remaining moves wait for a migration plan. + +**Read `XDG_*` variables.** Splitting the home across `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, and similar roots would scatter one installation across several directories and break the single `DSH_HOME` override that tests, the SDK, and Desktop rely on; the [single harness home resolver](../../implemented/architecture/2026-07-24-single-harness-home-resolver.md) already rejected separate roots. The proposal borrows only the classification, inside that one root. + +**Add a `runtime` category.** No current owner needs one; adding it would publish an unused value. + +## Acceptance criteria + +- New paths under `$DSH_HOME` are built with `dshPath` and land in one category directory. +- Each move of an entry from "Other existing entries" ships with a migration that preserves existing user data, plus an upgrade guide. +- The conventional top-level entries keep their locations. + +## Risks + +Until migrations land, the home holds both category directories and legacy top-level entries. Moving `attachments/` invalidates absolute paths in Session history unless the migration keeps the old location readable. Owners that resolve the home by hand do not pick up the helper until they are changed. diff --git a/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.zh.md b/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.zh.md new file mode 100644 index 0000000000..106d2b421d --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.zh.md @@ -0,0 +1,83 @@ +# Agent Note: harness home 路径类别 + +Status: proposed + +[English](2026-11-04-dsh-home-path-categories.md) | 中文 + +## 问题 + +各个包在 `$DSH_HOME`(默认 `~/.dsh`)下自行构造路径,因此 home 根目录混杂着用户配置、持久记录、日志、索引和下载内容。新的服务或插件没有规则可以确定其文件应放在哪里,部分负责方还会手动解析 home:[liveshare](../../../../packages/experimental/liveshare/src/host/share-host.ts) 直接读取 `process.env.DSH_HOME`,[migrate-sessions-to-v4](../../../../scripts/migrate-sessions-to-v4.ts) 默认使用 `~/.dsh/sessions`,不读取 `DSH_HOME`。 + +## 方案 + +按照 [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir/latest/) 使用的类型,对 `$DSH_HOME` 下的路径分组。每个类别都位于 `$DSH_HOME` 内;harness 不读取 `XDG_*` 变量。 + +| 类别 | 存放内容 | 丢失后果 | +|---|---|---| +| `config` | 用户为配置 harness 而编写或编辑的文件 | 丢失用户配置 | +| `data` | 持久记录:用户工作成果、登录信息、已安装的软件 | 丢失用户工作成果、登录信息或已安装的软件 | +| `state` | 跨运行保留但不属于用户工作成果的记录:日志、索引、id、保留的输出 | 历史被重置;harness 仍可正常工作 | +| `cache` | harness 可以重新构建或重新下载的内容 | 仅耗费时间或带宽 | +| `backup` | harness 写入的备份压缩包,例如 home 或 profile 的压缩副本 | 无影响;正常运行时不会读取这些压缩包 | + +不设 `runtime` 类别(XDG 中用于 socket 和 pid 文件的类型),因为没有负责方需要在 home 下使用它:锁文件放在其保护的文件旁边,而活动的 socket 留在操作系统临时目录中,因为 Unix socket 路径有长度限制。`backup` 不是 XDG 的类型:它为备份压缩包提供一个目录,用户和清理工具可以随时清空,不影响运行中的 harness,也不影响被备份的记录。 + +### 路径辅助函数 + +`@deepseek-ai/dsh-home-paths` 中的 [`dshPath(category, ...segments)`](../../../../packages/util/home-paths/src/index.ts) 返回 `//`,不创建目录;`dshPath({ category, dshHome }, ...segments)` 基于显式配置的 home 解析路径。Loader `!!js` 配置表达式在 `dshHomePath` 之外也可以使用同一个函数。home 下的新路径使用 `dshPath`,并把负责方的目录名作为第一个路径段传入,该目录名通常是去掉 `@deepseek-ai/dsh-` 前缀的包名。`dshHomePath` 继续用于现有的顶层条目,`dshCachePath` 等同于 `dshPath('cache', ...)`。 + +### 约定的顶层条目 + +用户会直接打开、编辑这些条目并在脚本中引用它们,仓库中的文档也提到它们,因此它们保留当前的顶层位置,不在迁移候选之列: + +| `$DSH_HOME` 下的路径 | 负责方 | 类型 | +|---|---|---| +| `.env` | [app-boot](../../../../packages/boot/app-boot/README.zh.md) 环境层 | config | +| `cordis.patch.yml` | [app-boot](../../../../packages/boot/app-boot/README.zh.md) home patch 层 | config | +| `AGENTS.md` | [agent-instructions](../../../../packages/context/agent-instructions/README.zh.md) | config | +| `skills/` | [skill-filesystem](../../../../packages/skill/skill-filesystem/README.zh.md) | config | +| `.credentials.yaml` | [credentials-local](../../../../packages/credentials/credentials-local/README.zh.md) | data | +| `profiles//` | [app-boot](../../../../packages/boot/app-boot/README.zh.md)、plugin-manager、Desktop(`desktop` profile 及其 `lock`) | data | +| `sessions/` | base 和 sdk-minimal bundle 中的 session-persistence-jsonl 根目录 | data | +| `cache/` | 已经是 `cache` 类别 | cache | + +profile 目录内的文件,例如 `node_modules/`、`pnpm-lock.yaml`、`compatibility.json`、`.plugin-manager/`、`.plugin-market/repositories/`、`created-plugins/` 和 `cua-*.lock`,随所属 profile 保留,因为 pnpm 和 profile 工具按相对于 profile 的路径访问它们。旧版 `settings.yaml` 导入器继续读取 home 根目录,因为该文件是导入来源。 + +### 其他现有条目 + +这些条目没有面向用户的约定。每一行给出该条目所属的类别;迁移它属于单独的变更,需要数据迁移方案: + +| `$DSH_HOME` 下的当前路径 | 类别 | 负责方 | 原因 | +|---|---|---|---| +| `storages/` | `data` | base bundle 中的 storage-json 根目录 | Workspace、schedule 及其他领域记录;其中 `session_projcache` 单元是可重建的缓存,但 storage-json 只有一个根目录 | +| `attachments/v1/` | `data` | [attachment-local](../../../../packages/attachment/attachment-local/README.zh.md) | 用户附件;Session 历史记录了它们的绝对路径 | +| `dsh-runtimes/` | `data` | Desktop 离线运行时([workspace-dependencies](../../../../packages/bundle/web-app/cordis.patch.yml)) | 已安装的软件,可能包含用户添加的内容 | +| `liveshare/` | `data` | [liveshare](../../../../packages/experimental/liveshare/README.zh.md) 的所有者状态和凭据 | 存放管理令牌 | +| `.anonymous-user-id` | `state` | [anonymous-user-id](../../../../packages/identity/anonymous-user-id/README.zh.md) | 丢失后只会生成新的 id | +| `logs/` | `state` | CLI 启动失败报告 | 日志 | +| `llm-deepseek/files-v3.json` | `state` | [llm-deepseek](../../../../packages/llm/llm-deepseek/README.zh.md) 上传索引 | 派生索引 | +| `office-kit/outputs/` | `state` | [office-kit](../../../../packages/document/office-kit/README.zh.md) | 保留的转换输出,超过保留期后删除 | +| `speech-to-text/sensevoice/` | `cache` | voice-input-bundle | 可下载的模型 | +| `cache/attachments/` | `cache` | attachment-local 请求图片 | 已位于 `cache` 中 | + +### home 之外 + +以下位置不在本提案范围内:`~/.agents`(`DSH_AGENTS_HOME`),与其他 agent 工具共享;Electron 的 `userData` 和 `logs`,由 Electron 管理;Python SDK 资源缓存 `~/.cache/deepseek-harness/resources`(`DSH_RESOURCE_CACHE`),在多个 home 之间共享;操作系统临时目录下的 spill 和子进程输出目录;以及开发者或发布脚本的状态,例如 `~/.dsh-desktop-signing`。 + +## 备选方案 + +**立即迁移所有条目。** 最初的草案把所有条目(包括约定的条目)都移入类别目录,且不提供回退。这样做会使每个现有 home 在升级后看起来为空,使 Session 中记录的附件绝对路径失效,并重命名用户手动编辑的文件。上述约定条目现在保持不动,其余迁移等待迁移方案。 + +**读取 `XDG_*` 变量。** 把 home 拆分到 `XDG_CONFIG_HOME`、`XDG_DATA_HOME` 等多个根目录,会让一次安装分散到多个目录,并破坏测试、SDK 和 Desktop 所依赖的单一 `DSH_HOME` 覆盖;[单一 harness home 解析器](../../implemented/architecture/2026-07-24-single-harness-home-resolver.zh.md)已经否决了拆分根目录。本提案只借用分类方式,并且仍在这一个根目录之内。 + +**增加 `runtime` 类别。** 当前没有负责方需要它;增加它会发布一个未使用的值。 + +## 验收标准 + +- `$DSH_HOME` 下的新路径使用 `dshPath` 构造,并落在某一个类别目录中。 +- 每次迁移“其他现有条目”中的条目时,都附带一个保留现有用户数据的迁移,以及一份升级指南。 +- 约定的顶层条目保留其位置。 + +## 风险 + +在迁移落地之前,home 中同时存在类别目录和旧的顶层条目。迁移 `attachments/` 会使 Session 历史中的绝对路径失效,除非迁移保持旧位置可读。手动解析 home 的负责方在被修改之前不会使用该辅助函数。 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/AGENTS.md b/.github/AGENTS.md index ffef007a51..c4e46b20ed 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -8,4 +8,4 @@ The merge checks run from three workflows named `Policy`, which run on `pull_req The manual Desktop publication workflow selects the original successful `package` job attempt independently of `upload-artifact` archival status, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job. -`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal. Rollout installs only publisher production dependencies in `desktop-rollout` and `website-rollout` checkouts; do not reuse the full-install publication checkouts. Both publication workflows run dependency-free preflights from `apps/desktop-publisher/src`. The required CI verdicts include isolated publisher installation checks: Linux/macOS in `ci.yml`, native Windows in `ci-windows.yml`. +`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery validates the prepared website approval digest and upload journal without another Environment approval. Rollout installs only publisher production dependencies in `desktop-rollout` and `website-rollout` checkouts; do not reuse the full-install publication checkouts. Both publication workflows run dependency-free preflights from `apps/desktop-publisher/src`. The required CI verdicts include isolated publisher installation checks: Linux/macOS in `ci.yml`, native Windows in `ci-windows.yml`. 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 new file mode 100644 index 0000000000..fb625e0d85 --- /dev/null +++ b/.github/stale-pull-requests/remind.mjs @@ -0,0 +1,140 @@ +/** + * 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 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` 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 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 +// 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']) + +const isBot = account => account?.type === 'Bot' || (account?.login ?? '').endsWith('[bot]') || BOT_LOGINS.has(account?.login) + +/** + * Returns the timestamps a timeline event contributes to the last activity. + * @param {object} event GitHub issue timeline event. + * @returns {string[]} ISO timestamps; empty for bot activity and events that are not activity. + */ +function activityTimes(event) { + switch (event.event) { + case 'committed': + return [event.committer?.date].filter(Boolean) + case 'head_ref_force_pushed': + case 'reopened': + case 'ready_for_review': + return [event.created_at] + case 'commented': + return isBot(event.actor) ? [] : [event.created_at] + case 'line-commented': + case 'commit-commented': + return (event.comments ?? []).filter(comment => !isBot(comment.user)).map(comment => comment.created_at) + case 'reviewed': + return isBot(event.user) ? [] : [event.submitted_at] + default: + return [] + } +} + +/** + * 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 {{ 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 dueStage({ createdAt, timeline, now }) { + const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) + const lastActivity = Math.max(...times) + const sent = timeline + .filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity) + .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 or closing comment. + * @param {string} author Pull-request author login. + * @param {number} days Stage in days; `CLOSE_DAYS` builds the closing comment. + * @returns {string} Comment body. + */ +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 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`. + * @param {object} options.core Actions toolkit core from `actions/github-script`. + * @param {Date} [options.now] Evaluation time. + * @param {(ms: number) => Promise} [options.sleep] Delay between comments. + * @returns {Promise} + */ +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 + let failed = 0 + for (const pull of pulls) { + if (posted >= MAX_COMMENTS_PER_RUN) break + if (isBot(pull.user)) continue + 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 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}`) + } + } + if (failed > 0) core.setFailed(`${failed} pull requests failed; see the warnings above.`) +} diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs new file mode 100644 index 0000000000..c6033e1fc5 --- /dev/null +++ b/.github/stale-pull-requests/remind.test.mjs @@ -0,0 +1,128 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +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, stageBody('author', stage)) +const dueStage = options => dueAction(options)?.days + +test('no reminder is due within 7 days of the last activity', () => { + 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(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(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(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 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), + pull(2, { labels: [{ name: 'DO_NOT_CLOSE' }] }), + pull(3, { user: { login: 'dependabot[bot]', type: 'Bot' } }), + // A bot comment or label refreshes `updated_at` without being activity. + 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', + update: async params => { + if (params.pull_number === 8) throw new Error('close failed') + closed.push(params) + }, + }, + issues: { + listEventsForTimeline: 'timeline', + createComment: async params => { + if (params.issue_number === 6) throw new Error('locked') + comments.push(params) + }, + }, + }, + paginate: async (method, params) => { + if (method === 'pulls') return pulls + timelines.push(params.issue_number) + 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 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, 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 () => { + const pulls = Array.from({ length: 105 }, (_, number) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20) })) + let comments = 0 + const github = { + rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } }, + paginate: async method => method === 'pulls' ? pulls : [], + } + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) + assert.equal(comments, 100) +}) diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 848ecc3099..c0fcc08d47 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -67,6 +67,7 @@ jobs: outputs: route: ${{ steps.local.outputs.route }} preset: ${{ steps.local.outputs.preset }} + rollout-requested: ${{ steps.check.outputs.rollout-requested }} approval: ${{ steps.check.outputs.approval }} website-approval: ${{ steps.check.outputs.website-approval }} website-destination: ${{ steps.check.outputs.website-destination }} @@ -110,6 +111,7 @@ jobs: publish: name: Approve ${{ needs.prepare.outputs.label }} needs: [route, prepare] + if: needs.prepare.outputs.rollout-requested == 'true' runs-on: [self-hosted, '${{ needs.route.outputs.runner }}'] environment: ${{ needs.prepare.outputs.preset == 'production' && 'desktop-production' || 'desktop-test' }} concurrency: @@ -159,8 +161,9 @@ jobs: retention-days: 30 upload-website-installer: + name: Website ${{ needs.prepare.outputs.label }} needs: [route, prepare, publish] - if: inputs.upload_website && needs.prepare.outputs.preset != 'test' + if: ${{ !cancelled() && inputs.upload_website && needs.prepare.result == 'success' && needs.prepare.outputs.preset != 'test' && (needs.publish.result == 'success' || (needs.publish.result == 'skipped' && needs.prepare.outputs.rollout-requested == 'false')) }} runs-on: [self-hosted, '${{ needs.route.outputs.runner }}'] environment: desktop-production timeout-minutes: 60 @@ -216,9 +219,8 @@ jobs: purge-website-installer: needs: [route, prepare, upload-website-installer] - if: inputs.upload_website && needs.prepare.outputs.preset != 'test' + if: ${{ !cancelled() && inputs.upload_website && needs.prepare.outputs.preset != 'test' && needs.upload-website-installer.result == 'success' }} runs-on: [self-hosted, '${{ needs.route.outputs.runner }}'] - environment: desktop-production timeout-minutes: 60 concurrency: group: desktop-website-purge-${{ needs.prepare.outputs.website-destination }} diff --git a/.github/workflows/pr-check-on-head-branch.yml b/.github/workflows/pr-check-on-head-branch.yml index ef456f5a9b..f2d36b10af 100644 --- a/.github/workflows/pr-check-on-head-branch.yml +++ b/.github/workflows/pr-check-on-head-branch.yml @@ -65,7 +65,6 @@ jobs: CHECK_MODE: ${{ vars.MERGE_POLICY_PRE_MERGE }} BASE_SHA: ${{ needs.master.outputs.base_sha }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} - SINCE: ${{ needs.master.outputs.since }} run: | stop() { if [ "$CHECK_MODE" = block ]; then @@ -75,24 +74,39 @@ jobs: echo "::warning title=Pre-Merge Check::$1" exit 0 } - if [[ ! "$BASE_SHA" =~ ^[0-9a-f]{40}$ || ! "$SINCE" =~ ^[0-9]+$ ]]; then + if [[ ! "$BASE_SHA" =~ ^[0-9a-f]{40}$ ]]; then stop "the master diff check reported no base commit, so nothing was merged or compiled" fi - # A shallow fetch starts a background maintenance run that rewrites .git/shallow, and the second shallow fetch - # below then fails with "shallow file has changed since we read it". - fetch() { - git -c maintenance.auto=false -c gc.auto=0 fetch --no-tags --no-write-fetch-head "$@" origin "$HEAD_SHA" "$BASE_SHA" - } - fetch --shallow-since="$SINCE" || + # The checkout is already shallow, and a shallow fetch starts a background maintenance run that rewrites + # .git/shallow, so the fetch below would fail with "shallow file has changed since we read it". + # The history is bounded by depth, not by date: a date window marks a merge commit shallow when one parent + # predates it, which drops the other parent too and lets the merge base settle on an older commit. Within its + # depth every commit keeps all parents; 150 covers the base-branch commits a 72-hour-old base can be behind. + git -c maintenance.auto=false -c gc.auto=0 fetch --no-tags --no-write-fetch-head --depth=150 --filter=blob:none origin "$HEAD_SHA" "$BASE_SHA" || stop "the base commit $BASE_SHA could not be fetched, so nothing was merged or compiled" - # A time window records a merge commit itself as shallow when one of its parents predates the window, which - # drops the other, in-window parent too; a depth bound keeps both parents of every commit it covers. if ! git merge-base "$HEAD_SHA" "$BASE_SHA" >/dev/null; then - fetch --depth=20 --filter=blob:none || - stop "the base commit $BASE_SHA could not be fetched, so nothing was merged or compiled" + 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 new file mode 100644 index 0000000000..db1c3f8115 --- /dev/null +++ b/.github/workflows/stale-pull-requests.yml @@ -0,0 +1,35 @@ +# 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 + +on: + schedule: + - cron: '0 2 * * *' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: stale-pull-requests + cancel-in-progress: false + +jobs: + remind: + name: Remind and close stale pull requests + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - name: Check out reminder rules + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + sparse-checkout: .github/stale-pull-requests + persist-credentials: false + - name: Post due reminders and close stale pull requests + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 + with: + script: | + const { processStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) + await processStalePullRequests({ github, context, core }) diff --git a/.gitignore b/.gitignore index 6255c7081b..e3b3ba67b0 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,7 @@ mise.toml dist-exe/ /dist/ apps/desktop/.desktop-build/ +apps/desktop/.desktop-dev/ python/sdk-runtime/src/deepseek_harness_runtime/runtime/ python/**/__pycache__/ python/**/.pytest_cache/ 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 71f86f2253..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 | @@ -101,6 +102,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`execa`](https://github.com/sindresorhus/execa) | MIT | | [`fast-xml-parser`](https://github.com/NaturalIntelligence/fast-xml-parser) | MIT | | [`fflate`](https://github.com/101arrowz/fflate) | MIT | +| [`fuzzysort`](https://github.com/farzher/fuzzysort) | MIT | | [`got`](https://github.com/sindresorhus/got) | MIT | | [`hosted-git-info`](https://github.com/npm/hosted-git-info) | ISC | | [`immer`](https://github.com/immerjs/immer) | MIT | diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index fe1ef0f3eb..f60b605949 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: bedb55bd3a80599c zh: a381da5cd5db885b diff --git a/apps/cli/README.md b/apps/cli/README.md index db26de93ad..bf989c919a 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 0992f936ff..3c62793f4b 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..824fd37a99 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"] @@ -68,8 +70,6 @@ flowchart LR cfg --> plugin_dsh_base_session_query_sqlite plugin_dsh_base_working_directory["working-directory
@deepseek-ai/dsh-working-directory"] cfg --> plugin_dsh_base_working_directory - plugin_dsh_base_tool_working_directory["tool-working-directory
@deepseek-ai/dsh-tool-working-directory"] - cfg --> plugin_dsh_base_tool_working_directory plugin_dsh_base_session_projection["session-projection
@deepseek-ai/dsh-session-projection"] cfg --> plugin_dsh_base_session_projection plugin_dsh_base_storage["storage
@deepseek-ai/dsh-storage"] @@ -86,6 +86,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"] @@ -120,6 +122,8 @@ flowchart LR cfg --> plugin_dsh_base_skill_filesystem plugin_dsh_base_tool_skill["tool-skill
@deepseek-ai/dsh-tool-skill"] cfg --> plugin_dsh_base_tool_skill + plugin_dsh_base_upstream_skills["upstream-skills
@deepseek-ai/dsh-upstream-skills"] + cfg --> plugin_dsh_base_upstream_skills plugin_dsh_base_commands["commands
@deepseek-ai/dsh-commands"] cfg --> plugin_dsh_base_commands plugin_dsh_base_command_feedback["command-feedback
@deepseek-ai/dsh-command-feedback"] @@ -234,13 +238,13 @@ 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` | | `attachment-local` | `@deepseek-ai/dsh-attachment-local` | | `session-query-sqlite` | `@deepseek-ai/dsh-session-query-sqlite` | | `working-directory` | `@deepseek-ai/dsh-working-directory` | -| `tool-working-directory` | `@deepseek-ai/dsh-tool-working-directory` | | `session-projection` | `@deepseek-ai/dsh-session-projection` | | `storage` | `@deepseek-ai/dsh-storage` | | `storage-json` | `@deepseek-ai/dsh-storage-json` | @@ -249,6 +253,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` | @@ -266,6 +271,7 @@ flowchart LR | `skill` | `@deepseek-ai/dsh-skill` | | `skill-filesystem` | `@deepseek-ai/dsh-skill-filesystem` | | `tool-skill` | `@deepseek-ai/dsh-tool-skill` | +| `upstream-skills` | `@deepseek-ai/dsh-upstream-skills` | | `commands` | `@deepseek-ai/dsh-commands` | | `command-feedback` | `@deepseek-ai/dsh-command-feedback` | | `goal` | `@deepseek-ai/dsh-goal` | diff --git a/apps/cli/package.json b/apps/cli/package.json index b3f8a8c093..9656f7c1a2 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh", "description": "dsh CLI: profile launch, plugin management, and configuration inspection", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -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:*", @@ -119,7 +120,8 @@ "@deepseek-ai/dsh-timeline": "workspace:*", "@deepseek-ai/dsh-experimental-plugin-market-bundle": "workspace:*", "@deepseek-ai/dsh-personalized-recommendations": "workspace:*", - "@deepseek-ai/dsh-experimental-forge-bundle": "workspace:*" + "@deepseek-ai/dsh-experimental-forge-bundle": "workspace:*", + "@deepseek-ai/dsh-deepseek-chat-import": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -175,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..84a966f601 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: b9bf517793555b80 + zh: 3dd96ecaaa6faea3 /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..49d3c5a78d 100644 --- a/apps/cli/reference/README.md +++ b/apps/cli/reference/README.md @@ -128,11 +128,11 @@ 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. -Web, headless, and SDK inherit native tool execution from the base bundle; use a [PTC overlay](../config/examples/ptc.yml) to select PTC. The shipped `minimal` agent preset keeps that deployment presentation, fixes the complete system prompt to `You are a helpful software engineer assistant.`, and provides the platform-selected persistent shell, `read_image`, and `working_directory`. It supports automatic context compaction and the human `/compact` command. Select 极简模式 when creating a Web session; the shared browser, workspace, persistence, sandbox, and permission host remains in place. +Web, headless, and SDK inherit native tool execution from the base bundle; use a [PTC overlay](../config/examples/ptc.yml) to select PTC. The shipped `minimal` agent preset keeps that deployment presentation, fixes the complete system prompt to `You are a helpful software engineer assistant.`, and provides the platform-selected persistent shell and `read_image`. It supports automatic context compaction and the human `/compact` command. Select 极简模式 when creating a Web session; the shared browser, workspace, persistence, sandbox, and permission host remains in place. ## Shared deployment behavior diff --git a/apps/cli/reference/README.zh.md b/apps/cli/reference/README.zh.md index 2de7755983..e58ddef171 100644 --- a/apps/cli/reference/README.zh.md +++ b/apps/cli/reference/README.zh.md @@ -128,11 +128,11 @@ 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 服务。 -Web、headless 与 SDK 继承 base bundle 的原生工具执行;使用 [PTC overlay](../config/examples/ptc.yml) 可选择 PTC。随附的 `minimal` agent preset 会保留该部署的呈现方式,将完整系统提示词固定为 `You are a helpful software engineer assistant.`,并提供按平台选择的持久 shell、`read_image` 和 `working_directory`。它支持自动上下文压缩和用户 `/compact` 命令。创建 Web 会话时请选择极简模式;共享的浏览器、workspace、持久化、沙箱与权限宿主保持不变。 +Web、headless 与 SDK 继承 base bundle 的原生工具执行;使用 [PTC overlay](../config/examples/ptc.yml) 可选择 PTC。随附的 `minimal` agent preset 会保留该部署的呈现方式,将完整系统提示词固定为 `You are a helpful software engineer assistant.`,并提供按平台选择的持久 shell 和 `read_image`。它支持自动上下文压缩和用户 `/compact` 命令。创建 Web 会话时请选择极简模式;共享的浏览器、workspace、持久化、沙箱与权限宿主保持不变。 ## 共享部署行为 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 1c8765d268..abf66a630e 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -13,9 +13,8 @@ import { } from '@agentclientprotocol/sdk' import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { execa } from 'execa' -import * as yaml from 'js-yaml' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { testProfileResolution } from './profiles/headless/tests/profile-resolution.ts' @@ -144,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']) { @@ -1259,20 +1256,20 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', ) expect(code).toBe(0) expect(stderr).toBe('') - const rows = yaml.load(stdout, { schema: entryListSchema }) as Array<{ id?: string; name?: string }> + const rows = parseEntryYaml(stdout) as Array<{ id?: string; name?: string }> expect(rows.map(row => [row.id, row.name])).toEqual([ ['sdk-app-startup', '@deepseek-ai/dsh-sdk-app'], ['sdk-jsonrpc-server', '@deepseek-ai/dsh-sdk-jsonrpc-server'], ['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'], ['attachment-local', '@deepseek-ai/dsh-attachment-local'], ['tool-fs', '@deepseek-ai/dsh-tool-fs'], ['working-directory', '@deepseek-ai/dsh-working-directory'], - ['tool-working-directory', '@deepseek-ai/dsh-tool-working-directory'], ['session-projection', '@deepseek-ai/dsh-session-projection'], ['token-meter', '@deepseek-ai/dsh-token-meter'], ['compaction-basic', '@deepseek-ai/dsh-compaction-basic'], diff --git a/apps/cli/tests/dump-config-schema.expected.e2e.ts b/apps/cli/tests/dump-config-schema.expected.e2e.ts index d481c9bd2a..b6472adabb 100644 --- a/apps/cli/tests/dump-config-schema.expected.e2e.ts +++ b/apps/cli/tests/dump-config-schema.expected.e2e.ts @@ -3,8 +3,7 @@ import { existsSync, mkdtempSync, realpathSync } from 'node:fs' import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { Ajv2020 } from 'ajv/dist/2020.js' -import * as yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import type { ConfigSchemaDump } from '@deepseek-ai/dsh-app-boot' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -162,7 +161,7 @@ describe.skipIf(!builtArtifactsExist)('dsh --dump-config-schema assembled output const composed = await dump(fixture, [], '--dump-config') const validator = new Ajv2020({ strict: false, validateFormats: false }) const validate = validator.compile(document) - expect(validate(yaml.load(composed.stdout, { schema: entryListSchema })), JSON.stringify(validate.errors)).toBe(true) + expect(validate(parseEntryYaml(composed.stdout)), JSON.stringify(validate.errors)).toBe(true) expect(validate([{ name: `${packageName}/namespace`, config: { attempts: 'wrong' } }])).toBe(false) const patch = validator.compile({ $schema: document.$schema, $defs: document.$defs, $ref: '#/$defs/patchList' }) expect(patch([{ id: 'schema-class', config: { enabled: 'wrong' } }])).toBe(false) 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/lazy-search-startup.compat.spec.ts b/apps/cli/tests/lazy-search-startup.compat.spec.ts index dfb92dc340..ed1efb0a16 100644 --- a/apps/cli/tests/lazy-search-startup.compat.spec.ts +++ b/apps/cli/tests/lazy-search-startup.compat.spec.ts @@ -15,7 +15,7 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import yaml from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { describe, expect, it } from 'vitest' const repoRoot = fileURLToPath(new URL('../../../', import.meta.url)) @@ -37,12 +37,6 @@ interface PatchEntry extends ConfigRow { insert?: ConfigRow[] } -const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { - kind: 'scalar', - construct: value => String(value), -}) -const configSchema = yaml.JSON_SCHEMA.extend(jsExprType) - /** Boot the built Web CLI, wait for its settled URL, then dispose through SIGTERM. */ function runBuiltWeb(cwd: string): Promise<{ stdout: string; stderr: string; code: number }> { return new Promise((resolveRun, rejectRun) => { @@ -103,9 +97,9 @@ describe.skipIf(!requireBuiltArtifacts)('built CLI lazy-search startup', () => { it('boots and disposes the shipped composition with full-text search off by default', async () => { expect(existsSync(builtBin), `missing built CLI ${resolve(builtBin)}; run pnpm build`).toBe(true) expect(existsSync(webDist), `missing Web dist ${resolve(webDist)}; run pnpm run build:web`).toBe(true) - const baseRows = (yaml.load(await readFile(baseConfigPath, 'utf8'), { schema: configSchema }) as PatchEntry[]) + const baseRows = (parseEntryYaml(await readFile(baseConfigPath, 'utf8')) as PatchEntry[]) .flatMap(entry => entry.insert ?? [entry]) - const webRows = (yaml.load(await readFile(webConfigPath, 'utf8'), { schema: configSchema }) as PatchEntry[]) + const webRows = (parseEntryYaml(await readFile(webConfigPath, 'utf8')) as PatchEntry[]) .flatMap(entry => entry.insert ?? [entry]) const baseRow = baseRows.find(row => row.id === 'session-query-sqlite') const webRow = webRows.find(row => row.id === 'session-query-sqlite') diff --git a/apps/cli/tests/optional-bundle-transitions.e2e.ts b/apps/cli/tests/optional-bundle-transitions.e2e.ts index ac04460a79..33f08f4640 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>() @@ -172,8 +172,8 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option it('keeps the default host and minimal tool catalogs while every optional bundle is off', async () => { const minimal = await agent('minimal') const standard = await agent() - expect(names()).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(names()).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) + expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) for (const name of ['str_replace_editor', 'session_search', 'terminal_open', 'user_terminal_list', 'ralph']) expect(names(standard.agent)).not.toContain(name) expect((await ctx.skills.list({ cwd: workspace, scope: standard.agent })).some(skill => skill.name === 'dsh-badge')).toBe(false) }) @@ -247,7 +247,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option expect(toolResult(owner.agent, 'badge-on')).toContain('dsh-badge.png') const minimal = await agent('minimal') expect((await ctx.skills.list({ cwd: workspace, scope: minimal.agent })).map(skill => skill.name)).toContain('dsh-badge') - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) await select(bundles.badge, false) expect((await load('badge-after')).isError).toBe(true) }) @@ -347,7 +347,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option ]) expect(toolResult(coded, 'combined-program')).toContain(coded.session.id) expect(toolResult(coded, 'combined-program')).toContain('dsh-badge') - expect(names()).toEqual(expect.arrayContaining(['session_search', 'terminal_open', 'ralph', 'working_directory'])) + expect(names()).toEqual(expect.arrayContaining(['session_search', 'terminal_open', 'ralph'])) for (const name of [...Object.values(bundles)].reverse()) await select(name, false) expect(names((await agent()).agent)).not.toContain('session_search') }) diff --git a/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts b/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts index 77602a0788..a6f8a1c350 100644 --- a/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts +++ b/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts @@ -1,7 +1,8 @@ import { fileURLToPath } from 'node:url' +import { realpathSync } from 'node:fs' import { createServer } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http' -import { join } from 'node:path' +import { basename, dirname, join } from 'node:path' import { expect, it } from 'vitest' import { runScenario, @@ -140,8 +141,9 @@ it('pins Messages Files offload and inline fallback in assembled requests', asyn const fileImage = { type: 'image', source: { type: 'file', file_id: 'file-api-snapshot-1' } } const offloadedImage = `[image omitted to fit request image limits; ${attachmentId}.${normalizedAccess}]` const imageHandle = `Image ${attachmentId}; request preview 1x1px.${normalizedAccess}` + // The Session header records the canonical spelling of the scenario's directory, which is removed by now. const runtimeContext = (cwd: string): string => '\nThe following information describes your current session:\n\n' - + `Current working directory: ${JSON.stringify(cwd)}.\n\n` + + `Current working directory: ${JSON.stringify(join(realpathSync.native(dirname(cwd)), basename(cwd)))}.\n\n` + 'Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\n' + 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\n' + 'You are the root agent. Your name is "lead".\n\n' 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-inheritance/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl index a7352b5dd7..7b11a97e74 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl @@ -17,8 +17,8 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} -{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","write"]},"reason":"resume","startsSeries":true}} +{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Tighten this session to read-only.","messageSeqs":[3],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"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.\"}"}],"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":"delegate-write","name":"subagent","args":["{\"description\": \"Delegated write probe\", \"prompt\": \"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":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"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":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"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/subagent-settlement-fence.ts b/apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts index c2c8a87885..22c632247b 100644 --- a/apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts +++ b/apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts @@ -3,7 +3,7 @@ * @module subagent-settlement-fence */ -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-agent-loop' import type {} from '@deepseek-ai/dsh-subagent' @@ -24,12 +24,12 @@ export function apply(ctx: Context): void { let hasDelivered = false ctx.effect(() => { - const disposeInbox = ctx.root.on('agent/inbox/inserted', ({ agent, message }) => { + const disposeInbox = ctx[Context.root].on('agent/inbox/inserted', ({ agent, message }) => { if (agent.session.header.parentSession !== undefined || message.source.kind !== 'subagent-settled') return hasDelivered = true delivered.resolve(undefined) }) - const disposeStep = ctx.root.on('agent/pre-step', async ({ agent, turn, step }, next) => { + const disposeStep = ctx[Context.root].on('agent/pre-step', async ({ agent, turn, step }, next) => { if (agent.session.header.parentSession === undefined && turn === 1 && step === 2 && !hasDelivered) { await delivered.promise } 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/official-installer-packed.e2e.ts b/apps/cli/tests/profiles/official-installer-packed.e2e.ts index e9039e8a5a..699f8deb7c 100644 --- a/apps/cli/tests/profiles/official-installer-packed.e2e.ts +++ b/apps/cli/tests/profiles/official-installer-packed.e2e.ts @@ -5,8 +5,8 @@ import { join } from 'node:path' import { createInterface } from 'node:readline' import { fileURLToPath } from 'node:url' import { execa } from 'execa' -import yaml from 'js-yaml' import { expect, it, onTestFinished } from 'vitest' +import { stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' import type { BundleInfo, ChangeResult } from '@deepseek-ai/dsh-plugin-manager' import { getDshRuntimeVersion } from '../../../../packages/boot/app-boot/src/plugin-compatibility.ts' import { generateOfficialBundleCatalog } from '../../../../scripts/gen-official-bundle-catalog.ts' @@ -118,7 +118,7 @@ it.skipIf(!built)('installs the exported registry\'s local closure and switches const observer = join(temporary, 'official-installer-observer.mjs') await writeFile(observer, await readFile(new URL('./fixtures/official-installer-observer.mjs', import.meta.url), 'utf8')) const patch = join(temporary, 'official-installer.patch.yml') - await writeFile(patch, yaml.dump([{ insert: [{ id: 'official-installer-observer', name: observer, + await writeFile(patch, stringifyEntryYaml([{ insert: [{ id: 'official-installer-observer', name: observer, config: { registry: registry.url, profile, 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/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index ffe6efef60..3b0bc2fa65 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -392,7 +392,6 @@ describe('Python SDK dsh profile keyless smoke', () => { process.platform === 'win32' ? 'pwsh' : 'bash', ...(optOut ? [] : ['read_image']), ...(editorEnabled ? ['str_replace_editor'] : []), - 'working_directory', ]) expect(modelRequests).toHaveLength(editorEnabled ? 3 : imageEnabled ? 2 : 1) if (imageEnabled) { 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/profiles/webhook-packed.e2e.ts b/apps/cli/tests/profiles/webhook-packed.e2e.ts index 3844ceb22b..ac0214a76d 100644 --- a/apps/cli/tests/profiles/webhook-packed.e2e.ts +++ b/apps/cli/tests/profiles/webhook-packed.e2e.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url' import { execa } from 'execa' import yaml from 'js-yaml' import { expect, it } from 'vitest' +import { stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { assertInstalledTree, createPackedInstallation } from './packed-installation.ts' const root = fileURLToPath(new URL('../../../..', import.meta.url)) @@ -64,7 +65,7 @@ export function apply(ctx) { } `) const patch = join(temporary, 'test.patch.yml') - await writeFile(patch, yaml.dump([ + await writeFile(patch, stringifyEntryYaml([ { id: 'session-telemetry-otel', disabled: true }, { id: 'github-webhook-ingress', insert: [{ id: 'observe-packed-ingress', name: observer }] }, ])) 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..3adb15bf54 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: () => () => {} }, @@ -252,7 +252,7 @@ beforeAll(async () => { describe('the shipped Web composition', () => { it('registers the directory and conditional Team tools in the global layer', () => { // Team registrations are shared; session mode controls their step-time availability. - expect(toolNames(ctx)).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(toolNames(ctx)).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) }) it('keeps the token meter and its context-meter projections on the host plane', async () => { @@ -351,20 +351,32 @@ 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', 'subagent', 'subagent_fork', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'todo_write', 'update_goal', 'wait_agent', 'web_fetch', 'web_search', - 'workflow', 'working_directory', 'write', + 'workflow', '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,25 +393,25 @@ 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', ])) for (const agent of [disabled.agent, enabled.agent]) { - expect(toolParameterNames(ctx, agent, 'subagent_fork')).toEqual(['cwd', 'description', 'name', 'prompt']) + expect(toolParameterNames(ctx, agent, 'subagent_fork')).toEqual(['description', 'name', 'prompt']) } } finally { - await policy.dispose() await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false }) await enabled.dispose() await disabled.dispose() @@ -459,7 +471,7 @@ describe('the shipped Web composition', () => { expect(assembly.sections).toEqual([ { name: 'deployment:persona-prefix', text: MINIMAL_PROMPT }, ]) - expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION) expect(ctx.commands.find(handle.agent, 'goal')).toBeUndefined() // serviceFor reports preset-owned providers; unisolated consumers inherit the host fs. @@ -501,7 +513,7 @@ describe('the shipped Web composition', () => { if (image?.type !== 'image') throw new Error('minimal image read produced no durable image') expect((await ctx.attachments.readImage(image.attachment)).data.byteLength).toBe(image.attachment.bytes) expect(JSON.stringify(adapter.requests[1]?.messages)).toContain(image.attachment.attachmentId) - expect(adapter.requests[0]?.tools?.map(tool => tool.name)).toEqual(['bash', 'read_image', 'working_directory']) + expect(adapter.requests[0]?.tools?.map(tool => tool.name)).toEqual(['bash', 'read_image']) expect(result?.data.meta).toMatchObject({ path: await realpath(join(cwd, 'red.png')) }) } finally { await handle.dispose() @@ -536,7 +548,7 @@ describe('the shipped Web composition', () => { const last = adapter.requests.at(-1) expect(last?.messages.flatMap(message => message.content) .some(block => block.type === 'text' && block.text.includes('Preserve the requested project task.'))).toBe(true) - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) } finally { await handle.dispose() } @@ -580,7 +592,7 @@ describe('the shipped Web composition', () => { setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), }) try { - expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10) expect(ctx.agentPresets.serviceFor(minimal.agent, 'compaction')) .not.toBe(ctx.agentPresets.serviceFor(full.agent, 'compaction')) @@ -589,7 +601,7 @@ describe('the shipped Web composition', () => { // Tearing the minimal session down leaves the full one whole. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10) - expect(toolNames(ctx)).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(toolNames(ctx)).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) } finally { await full.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) @@ -800,7 +812,7 @@ describe('the shipped Web composition', () => { // stays the preset's choice — minimal mounts no `tool-skill`, so its // tool table has no loader even though the global layer is readable. expect((await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)).toContain('dsh-badge') - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) } finally { await handle.dispose() } @@ -905,7 +917,7 @@ describe.each(['web', 'desktop'] as const)('%s native subagent bundles', (surfac }) try { for (const product of installed) { - expect(toolParameterNames(productCtx, handle.agent, toolName(product))).toEqual(['cwd', 'description', 'name', 'prompt']) + expect(toolParameterNames(productCtx, handle.agent, toolName(product))).toEqual(['description', 'name', 'prompt']) } } finally { await handle.dispose() } expect(spawn).not.toHaveBeenCalled() @@ -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, }) @@ -1341,7 +1352,7 @@ describe('the default preset as a user setting', () => { }) try { // An omitted preset id resolves the stored default instead of the composed default. - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) } finally { await handle.dispose() } @@ -1387,7 +1398,7 @@ describe('a profile patch stored before Developer tools owned preset selection', setup: agentCtx => legacy.agentPresets.mount(agentCtx).then(() => undefined), }) try { - expect(toolNames(legacy, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(toolNames(legacy, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update']) } finally { await handle.dispose() } diff --git a/apps/cli/tests/windows-shell.spec.ts b/apps/cli/tests/windows-shell.spec.ts index c10f7c869a..858080ef42 100644 --- a/apps/cli/tests/windows-shell.spec.ts +++ b/apps/cli/tests/windows-shell.spec.ts @@ -15,8 +15,7 @@ import { mkdtempSync, rmSync, readFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { evaluate } from '@deepseek-ai/cordis-plugin-loader' import { bundlePatchPaths, composeEntries, initProfile, loadProfile, PROFILES_DIR } from '@deepseek-ai/dsh-app-boot' @@ -104,7 +103,7 @@ describe('shipped agent presets gate both shell tools by platform', () => { const webBundle = fileURLToPath(new URL('../../../packages/bundle/web-app/', import.meta.url)) const webManifest = JSON.parse(readFileSync(join(webBundle, 'package.json'), 'utf8')) as { dsh: { bundle: { patch: string[] } } } const presetRows = composeEntries([bundlePatchPaths(webBundle, webManifest.dsh.bundle).flatMap(file => - yaml.load(readFileSync(file, 'utf8'), { schema: entryListSchema }) as import('@deepseek-ai/cordis-plugin-include').PatchOptions[])]) + parseEntryYaml(readFileSync(file, 'utf8')) as import('@deepseek-ai/cordis-plugin-include').PatchOptions[])]) const definitions = presetRows.filter(row => row.name === '@deepseek-ai/dsh-agent-preset').map(row => row.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition) diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index 07943dc431..e667b5c23d 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop-host", "description": "Private Node-mode host process for the Electron desktop application", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "private": true, "license": "MIT", "type": "module", @@ -37,6 +37,8 @@ "@deepseek-ai/dsh-session-persistence": "workspace:*", "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", - "@deepseek-ai/dsh-brand": "workspace:*" + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-tool-executor-native": "workspace:*", + "@deepseek-ai/dsh-api-workspace-files": "workspace:*" } } diff --git a/apps/desktop-host/src/file-drag.ts b/apps/desktop-host/src/file-drag.ts index 473ab67e56..4297d804d9 100644 --- a/apps/desktop-host/src/file-drag.ts +++ b/apps/desktop-host/src/file-drag.ts @@ -1,10 +1,8 @@ /** Resolve desktop-only file references through the active Host filesystem and Session. */ import { createHash } from 'node:crypto' import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-workspace-files' import type {} from '@deepseek-ai/dsh-fs' -import type {} from '@deepseek-ai/dsh-session' -import type {} from '@deepseek-ai/dsh-session-persistence' -import type {} from '@deepseek-ai/dsh-sandbox-policy' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { parseFileAddress } from '@deepseek-ai/dsh-util-workspace-path' @@ -17,6 +15,7 @@ export interface LocalDragResource { /** * Authorize an unmodified local file through the composed filesystem's actual read operations. + * Relative paths resolve from the same workspace root the workspace file service uses for the Session. * @param ctx - booted Desktop Host. * @param address - Session-scoped resource reference. * @param cancellation - caller cancellation, combined with the read deadline. @@ -25,17 +24,14 @@ export interface LocalDragResource { export async function localDragResource(ctx: Context, address: string, cancellation?: AbortSignal): Promise { const resource = parseFileAddress(address) if (resource?.scope !== 'session') throw new Error('File drag requires a Session resource') - const sessions = ctx.get('sessions') - const persistence = ctx.get('sessionPersistence') const fs = ctx.get('fs') - const policy = ctx.get('sandboxPolicy') - if (fs === undefined || sessions === undefined || policy === undefined) throw new Error('File access unavailable') - const sessionId = resource.sessionId as SessionId - const header = sessions.get(sessionId)?.header ?? (await persistence?.stat(sessionId))?.header - if (header === undefined) throw new Error('File drag Session unavailable') + const workspaceFiles = ctx.get('workspaceFiles') + if (fs === undefined || workspaceFiles === undefined) throw new Error('File access unavailable') const signal = cancellation === undefined ? AbortSignal.timeout(10_000) : AbortSignal.any([cancellation, AbortSignal.timeout(10_000)]) signal.throwIfAborted() - const cwd = header.cwd ?? policy.workspaceRoot + const scope = await workspaceFiles.scopeOf(resource.sessionId as SessionId, signal) + if (scope === undefined) throw new Error('File drag Session unavailable') + const cwd = scope.workspaceRoot const entry = await fs.lstat(resource.path, { cwd }, signal) if (entry?.type !== 'file') return null const target = await fs.resolve(resource.path, { cwd, signal }) diff --git a/apps/desktop-host/tests/file-drag.spec.ts b/apps/desktop-host/tests/file-drag.spec.ts index dc8ee85af2..97dbf0c811 100644 --- a/apps/desktop-host/tests/file-drag.spec.ts +++ b/apps/desktop-host/tests/file-drag.spec.ts @@ -17,9 +17,13 @@ async function fixture() { onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) await ctx.plugin(LocalFileSystem, { cwd: root }) await ctx.plugin(SessionStore) - ctx.provide('sandboxPolicy', { workspaceRoot: root } as never) const id = brandString('file-drag-test') ctx.sessions.create(id, { meta: { cwd: root, origin: 'subagent' } }) + // The workspace file service resolves a live Session's root; its own tests cover that resolution. + ctx.provide('workspaceFiles', { + scopeOf: (sessionId: SessionId) => + Promise.resolve(ctx.sessions.get(sessionId) === undefined ? undefined : { sessionId, workspaceRoot: root }), + } as never) const path = join(root, '报告.pdf') const bytes = Buffer.from('%PDF-1.4\n原始内容\n%%EOF') await writeFile(path, bytes) diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index b26c7e5db3..6449b60f32 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -11,6 +11,7 @@ { "path": "../../packages/host/authentication-desktop" }, { "path": "../../vendor/cordis" }, { "path": "../../packages/core/agent" }, + { "path": "../../packages/api/workspace-files/tsconfig.host.json" }, { "path": "../../packages/jobs/jobs" }, { "path": "../../packages/schedule/schedule" }, { "path": "../../packages/workspace/workspace" }, @@ -27,7 +28,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-publisher/package.json b/apps/desktop-publisher/package.json index c9b8a21db2..a10f0bfcb0 100644 --- a/apps/desktop-publisher/package.json +++ b/apps/desktop-publisher/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-desktop-publisher", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "description": "Private Desktop release metadata, rollout and website publisher", "private": true, "type": "module", diff --git a/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts index 2863950ab1..d9ddd1b97a 100644 --- a/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts +++ b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts @@ -85,7 +85,7 @@ export async function publishDesktopRolloutCi(mode: 'check' | 'apply' | 'website const { route, root, recordsRoot, config, manifest, plan, target, website, destination, approval } = context if (mode === 'check') { if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, - `approval=${approval}\nwebsite-approval=${websiteApproval(manifest, config.bucket)}\nwebsite-destination=${createHash('sha256').update(`${config.bucket}/${route.target}`).digest('hex')}\nlabel=${manifest.source.version} / ${route.channel} / ${route.target} → ${target === undefined ? 'website only' : `${target}%`}\n`) + `rollout-requested=${target !== undefined}\napproval=${approval}\nwebsite-approval=${websiteApproval(manifest, config.bucket)}\nwebsite-destination=${createHash('sha256').update(`${config.bucket}/${route.target}`).digest('hex')}\nlabel=${manifest.source.version} / ${route.channel} / ${route.target} → ${target === undefined ? 'website only' : `${target}%`}\n`) if (env.GITHUB_STEP_SUMMARY && !env.DESKTOP_ROLLOUT_APPROVAL) await appendFile(env.GITHUB_STEP_SUMMARY, `## 桌面放量与官网发布确认\n\n打包运行:${route.runId} / 第 ${route.attempt} 次;版本:${manifest.source.version};平台:${route.target};环境 / 渠道:${route.preset} / ${route.channel}。\n\n目标放量比例:${target === undefined ? '保持当前比例' : `${target}%`}。执行时从 COS 核对当前比例,不允许降低比例。\n\n官网:${website ? desktopWebsiteInstallerUrl(route.target) + '(上传安装包并刷新缓存)' : '不变'}。${website ? '官网安装包面向所有下载用户,不受自动更新放量比例限制,也不要求放量达到 100%。固定下载地址无防降级保护,发布较早版本会替换较新安装包。' : ''}\n\n已确认首次 COS 发布记录;不重新计算全部安装包哈希或校验签名。\n`) return diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 6bf82ad4e2..3347189cd7 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 @@ -42,8 +42,8 @@ en: 98cf848762482d48 zh: 74f9100a39ec8c2f /deepseek-harness-desktop/develop: - en: faf7676ba18bbf2f - zh: f1d7b75ad348c548 + en: 4e4b26cfaaa098ee + zh: e0a2965606020041 /deepseek-harness-desktop/develop/startup-onboarding: en: 67dc7ef3e293236a zh: 1b224db684a2d1d7 @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: f1302ed4a3ab58bb - zh: cb53b9b349815028 + en: 3a70021830865253 + zh: 0467be8b505446cb /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 9e225fe856..91380fb670 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. @@ -199,7 +199,7 @@ The development application menu offers Reload Page (Cmd+R on macOS, Ctrl+R else pnpm run dev:desktop ``` -Development Harness state defaults to `apps/desktop/.desktop-build/development/home`, the disposable npm project lives at `apps/desktop/.desktop-build/development/project`, and Electron browser data lives at `apps/desktop/.desktop-build/development/electron-user-data`. Sessions, settings, credentials, package links, and browser data therefore stay out of the user's normal Harness home. An explicit `DSH_HOME` replaces only the development Harness home. Renderer DevTools opens automatically; Main, Renderer, and dsh Host debugging listen on ports 9229, 9222, and 9230. `DSH_DESKTOP_MAIN_INSPECT_PORT`, `DSH_DESKTOP_RENDERER_DEBUG_PORT`, and `DSH_DESKTOP_HOST_INSPECT_PORT` replace those ports, while `DSH_DESKTOP_OPEN_DEVTOOLS=0` keeps the detached Renderer tools closed. +Development Harness state defaults to `apps/desktop/.desktop-dev/home` and Electron browser data to `apps/desktop/.desktop-dev/electron-user-data`; `pnpm run clean` removes `.desktop-build` but keeps this directory. The disposable npm project lives at `apps/desktop/.desktop-build/development/project`. Sessions, settings, credentials, package links, and browser data therefore stay out of the user's normal Harness home. A launch moves each missing default directory from `.desktop-build/development`, and stops instead while a running Harness Dev still uses that browser data. An explicit `DSH_HOME` replaces only the development Harness home, and `DSH_DESKTOP_USER_DATA_DIR` replaces only the browser data. Renderer DevTools opens automatically; Main, Renderer, and dsh Host debugging listen on ports 9229, 9222, and 9230. `DSH_DESKTOP_MAIN_INSPECT_PORT`, `DSH_DESKTOP_RENDERER_DEBUG_PORT`, and `DSH_DESKTOP_HOST_INSPECT_PORT` replace those ports, while `DSH_DESKTOP_OPEN_DEVTOOLS=0` keeps the detached Renderer tools closed. After an explicit build, `start:desktop` reconstructs the disposable project and launches the existing artifacts without building again: @@ -257,7 +257,7 @@ Use the dedicated guides for build and release operations. Shared Windows runner ## Windows installer interface -During a confirmed Windows update restart, a separate process displays a draggable status notice until the installation stage ends. The installer does not wait for this window; installation and relaunch continue if it cannot start or stops responding. A gap can remain before the new application window appears. Optional DPI APIs are resolved at runtime, with 96 DPI layout when unavailable. +During a confirmed Windows update restart, a separate process displays a draggable status notice until the installation stage ends. The status process starts in the Windows system directory so it cannot pin the installation directory during replacement. The installer does not wait for this window; installation and relaunch continue if it cannot start or stops responding. A gap can remain before the new application window appears. Optional DPI APIs are resolved at runtime, with 96 DPI layout when unavailable. The Windows installer uses native NSIS pages with light and dark palettes, system shadows, an editable installation directory, and a finish page whose launch checkbox is selected by default. Installation is restricted to the current user. Clicking Install or pressing Enter validates the current path; drive roots remain invalid after normalization, including repeated trailing separators. New destinations must be empty, and nonempty destinations must be registered installations. Running executables at the affected installation path produce a native prompt and remain running; same-named applications in other directories do not block installation. Silent updates wait up to ten seconds for the affected application to exit, then stop with exit code 2 if it is still running. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 43b6c0c1df..d71b68fddc 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 和工作区均显示本地化的登录失效提示。 @@ -199,7 +199,7 @@ macOS 和 Linux 从图形界面启动的程序只继承会话管理器提供的 pnpm run dev:desktop ``` -开发 Harness 状态默认写入 `apps/desktop/.desktop-build/development/home`,一次性 npm 项目位于 `apps/desktop/.desktop-build/development/project`,Electron 浏览器数据则位于 `apps/desktop/.desktop-build/development/electron-user-data`。因此,会话、设置、凭据、包链接和浏览器数据都不会进入用户正常使用的 Harness home;显式 `DSH_HOME` 只会替换开发 Harness home。Renderer DevTools 默认自动打开,Main、Renderer 和 dsh Host 调试端口依次为 9229、9222 和 9230。`DSH_DESKTOP_MAIN_INSPECT_PORT`、`DSH_DESKTOP_RENDERER_DEBUG_PORT` 与 `DSH_DESKTOP_HOST_INSPECT_PORT` 可以替换这些端口,`DSH_DESKTOP_OPEN_DEVTOOLS=0` 则保持 Renderer 调试窗口关闭。 +开发 Harness 状态默认写入 `apps/desktop/.desktop-dev/home`,Electron 浏览器数据默认写入 `apps/desktop/.desktop-dev/electron-user-data`;`pnpm run clean` 会删除 `.desktop-build`,但保留该目录。一次性 npm 项目位于 `apps/desktop/.desktop-build/development/project`。因此,会话、设置、凭据、包链接和浏览器数据都不会进入用户正常使用的 Harness home。启动时会把每个缺失的默认目录从 `.desktop-build/development` 移过来;若正在运行的 Harness Dev 仍在使用那里的浏览器数据,启动会停止而不迁移。显式 `DSH_HOME` 只会替换开发 Harness home,`DSH_DESKTOP_USER_DATA_DIR` 只会替换浏览器数据。Renderer DevTools 默认自动打开,Main、Renderer 和 dsh Host 调试端口依次为 9229、9222 和 9230。`DSH_DESKTOP_MAIN_INSPECT_PORT`、`DSH_DESKTOP_RENDERER_DEBUG_PORT` 与 `DSH_DESKTOP_HOST_INSPECT_PORT` 可以替换这些端口,`DSH_DESKTOP_OPEN_DEVTOOLS=0` 则保持 Renderer 调试窗口关闭。 显式构建完成后,`start:desktop` 会重新生成一次性项目,并跳过构建直接启动已有产物: @@ -257,7 +257,7 @@ Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否 ## Windows 安装界面 -Windows 更新确认重启后,独立进程显示可拖动的状态提示,直到安装阶段结束。安装器不等待提示窗;提示窗无法启动或失去响应时,安装和重新启动仍会继续。新版应用窗口出现前仍可能有一段空白。可选的 DPI API 在运行时解析,不可用时采用 96 DPI 布局。 +Windows 更新确认重启后,独立进程显示可拖动的状态提示,直到安装阶段结束。状态进程以 Windows 系统目录为工作目录,避免在替换期间占用安装目录。安装器不等待提示窗;提示窗无法启动或失去响应时,安装和重新启动仍会继续。新版应用窗口出现前仍可能有一段空白。可选的 DPI API 在运行时解析,不可用时采用 96 DPI 布局。 Windows 安装程序使用原生 NSIS 页面,提供亮暗配色、系统阴影、可编辑的安装目录,以及默认勾选立即启动的完成页。安装仅面向当前用户。点击安装或按 Enter 均校验当前路径;路径规范化后仍拒绝磁盘根目录,包括带重复末尾分隔符的写法。新安装位置必须为空,非空位置必须是已登记的安装目录。受影响安装路径中的程序运行时显示系统提示,并保持应用运行;其他目录中的同名应用不阻止安装。静默更新最多等待受影响应用退出十秒,若仍在运行则以退出码 2 结束。 diff --git a/apps/desktop/installer/restart-status.h b/apps/desktop/installer/restart-status.h index cfd9b5330d..d19ea79921 100644 --- a/apps/desktop/installer/restart-status.h +++ b/apps/desktop/installer/restart-status.h @@ -8,6 +8,7 @@ namespace restart_status { struct Launch { std::wstring command; std::wstring program; + std::wstring directory; HANDLE job; }; @@ -28,7 +29,7 @@ static DWORD WINAPI LaunchWorker(void* data) { startup.lpAttributeList = attributes; PROCESS_INFORMATION process{}; started = CreateProcessW(launch->program.c_str(), &launch->command[0], nullptr, nullptr, FALSE, - EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, &startup.StartupInfo, &process) != FALSE; + EXTENDED_STARTUPINFO_PRESENT, nullptr, launch->directory.c_str(), &startup.StartupInfo, &process) != FALSE; if (started) { CloseHandle(process.hThread); CloseHandle(process.hProcess); @@ -61,6 +62,8 @@ extern "C" __declspec(dllexport) HANDLE __cdecl InstallerStartRestartStatus(LPCW const UINT sysLength = GetSystemDirectoryW(system, ARRAYSIZE(system)); if (!length || length >= ARRAYSIZE(dll) || !sysLength || sysLength >= ARRAYSIZE(system)) return nullptr; auto launch = std::make_unique(); + // An inherited installation directory would prevent its rename while the status window is alive. + launch->directory = system; launch->program = std::wstring(system) + L"\\rundll32.exe"; launch->command = L"\"" + launch->program + L"\" \"" + dll + L"\",ShowRestartStatus \"" + installer + L"\" " + std::to_wstring(language) + L" " + theme + L" " + text; diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 6be1ff8a3f..269e06a139 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop", "description": "Electron desktop shell for a bundled dsh runtime and external plugins", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "private": true, "license": "MIT", "author": { diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml index 132f847407..7d9a3d1d4a 100644 --- a/apps/desktop/publishing/ci/README.i18n.yaml +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -27,11 +27,11 @@ en: 6325c71df74a9915 zh: edaa8a4502ed80a1 /desktop-ci-publication/rollout-and-website-publication: - en: ee7a9ab8c66df979 - zh: c355668bc9bdb635 + en: b6c39cec0946d5f4 + zh: 3a6014ffbbec81f1 /desktop-ci-publication/recovery-and-records: - en: 8751f415f189ebf5 - zh: e51c84f7cb4f4d3f + en: ee57863af9784f02 + zh: 4680f5c181685e32 /desktop-ci-publication/restore-a-channel: en: d82e2ccf70cce397 zh: d93dcb77cc4b463e diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md index 64f6c29077..4b65c1eec2 100644 --- a/apps/desktop/publishing/ci/README.md +++ b/apps/desktop/publishing/ci/README.md @@ -83,11 +83,11 @@ Before installing dependencies on the original runner, preparation and the appro ## Rollout and website publication -For a 10% → 30% → 100% rollout, first publish through COS with `staging_percentage=10` and `upload_website=false`. Then dispatch **Publish Desktop · Rollout & Website** from `master` with the original package run ID and selected attempt (defaults to 1; verify it against the package run). Set `rollout_percentage` to 30, then 100 for progressive delivery; leave it empty for website-only publication. `upload_website` defaults to false; select a percentage or enable website publication. For this sequence, enable it on the final invocation to upload the production website installer and refresh its cache. Website publication is independent of the rollout percentage and does not require 100%; the installer is available to all website download users. In website-only mode, the publish job verifies the feed without changing its percentage. Each platform uses its own package run. +For a 10% → 30% → 100% rollout, first publish through COS with `staging_percentage=10` and `upload_website=false`. Then dispatch **Publish Desktop · Rollout & Website** from `master` with the original package run ID and selected attempt (defaults to 1; verify it against the package run). Set `rollout_percentage` to 30, then 100 for progressive delivery; leave it empty for website-only publication. `upload_website` defaults to false; select a percentage or enable website publication. For this sequence, enable it on the final invocation to upload the production website installer and refresh its cache. Website publication is independent of the rollout percentage and does not require 100%; the installer is available to all website download users. Percentage changes require approval before modifying the feed. Website upload requires a separate approval; after a successful upload, cache refresh runs without another approval. A failed or cancelled upload prevents refresh. Website-only mode skips the percentage-change job and requires only website approval; the upload job still verifies the current feed without changing its percentage. Each platform uses its own package run. Preparation checks GitHub identity, the retained manifest, the small update YAML and a completed initial publication record; it does not rehash package binaries or repeat signature/notarization checks. After Environment approval, execution reads the current COS feed, verifies that its version, payload URL, size, hash and other metadata still match the published package, and changes only `stagingPercentage`. Missing or replaced feeds reject the operation. Repeating the same percentage is a no-op; lowering the percentage is rejected. The approval shows the requested percentage; the current percentage is read from COS during execution. -Website upload reuses the original retained installer, hashes that installer alone and uses the existing upload/purge recovery records. Cache-only retries use the existing website approval and upload journal without requiring the retained update YAML or initial feed journal. The website upload holds the feed channel lock through installer verification and upload so a newer feed cannot replace the selected version midway; competing publications on that channel fail while the lock is held. A metadata-only rollout therefore does not require installer files, but website publication requires its installer. Percentage changes retain before/after YAML in separate rollout audit records. Initial COS publication remains required; this workflow never builds packages, uploads versioned binaries or creates release tags. +Website upload reuses the original retained installer, hashes that installer alone and uses the existing upload/purge recovery records. Rollout cache-only retries validate the prepared website approval digest and upload journal. They require neither another Environment approval nor the retained update YAML or initial feed journal. The website upload holds the feed channel lock through installer verification and upload so a newer feed cannot replace the selected version midway; competing publications on that channel fail while the lock is held. A metadata-only rollout therefore does not require installer files, but website publication requires its installer. Percentage changes retain before/after YAML in separate rollout audit records. Initial COS publication remains required; this workflow never builds packages, uploads versioned binaries or creates release tags. @@ -99,7 +99,7 @@ The packaging workflows separate `package` from `upload-artifact` (GitHub artifa Production COS publication enables website installer upload and cache refresh by default (`upload_website=true`). Clear it to publish only versioned resources and automatic-update feeds; test publication never changes the production website. `upload-website-installer` uploads the fixed installer and `purge-website-installer` refreshes its URL. The website installer validator needs only the final DMG/EXE and retained manifest. It matches production qualification, build identity and target, hashes the installer once and uploads through the same open file handle. Both production nightly and stable packages can replace the fixed website installer. Operators select the intended version; the fixed object has no downgrade protection, so rerunning an older publication can replace a newer installer. The pre-approval summary names the fixed website URL, selected version and lack of downgrade protection when website upload is selected. The existing version/update publication retains its own checks. -Set `edgeOneZoneId` in each publishing runner’s `publishing/production.json` to the production EdgeOne zone (for example, `"edgeOneZoneId": "zone-example"`). Website publication requires this field before approval; COS-only publication and rollout do not. Actions do not read the repository variable `DOWNLOAD_PROD_EO_ZONE_ID`. The production COS credential pair also needs `teo:CreatePurgeTask` and `teo:DescribePurgeTasks`. Website uploads serialize by bucket/target in Actions and by bucket/object on the original machine. Cache observation runs separately. Version publication, website upload and cache refresh each use the production approval Environment; later jobs and reruns may require another approval. GitHub concurrency retains at most one pending job per group, so a newer pending job can cancel an older pending job; inspect canceled jobs before rerunning them. +Set `edgeOneZoneId` in each publishing runner’s `publishing/production.json` to the production EdgeOne zone (for example, `"edgeOneZoneId": "zone-example"`). Website publication requires this field before approval; COS-only publication and rollout do not. Actions do not read the repository variable `DOWNLOAD_PROD_EO_ZONE_ID`. The production COS credential pair also needs `teo:CreatePurgeTask` and `teo:DescribePurgeTasks`. Website uploads serialize by bucket/target in Actions and by bucket/object on the original machine. Cache observation runs separately. In the COS workflow, version publication, website upload and cache refresh each use the production approval Environment. In the Rollout workflow, only percentage changes and website upload use it; cache refresh follows the approved upload without another Environment approval. Rerunning a job with an Environment may require approval again. GitHub concurrency retains at most one pending job per group, so a newer pending job can cancel an older pending job; inspect canceled jobs before rerunning them. Website state lives in `upload-records/website--/state.json`, beside the retained releases root. macOS and Windows use the same record format on separate local disks. Website URLs and download filenames follow the [fixed-download rules](../README.md#fixed-downloads). Upload retries reconcile both bytes and `Content-Disposition`; identical bytes with a missing or different header receive one upload and readback. A completed journal with different remote bytes stops recovery and requires a newly approved publication. Completion evidence survives failed metadata repairs. Each new upload intent clears the previous purge record, so repaired metadata requires a new cache refresh; inspect EdgeOne history for the previous task ID and diagnostics. Unknown writes are read before any retry; CDN header forwarding requires real-environment validation. Rerun only the purge job to inspect its saved task when the original routing and preparation outputs remain available. With website upload enabled, website jobs skip only an explicitly selected test deployment. Each job requires its injected `route` or `selection` output for local preflight. Missing or changed website approval fails before upload or purge submission. Missing `website-destination` broadens both website concurrency groups. Missing `runner` output can prevent scheduling before preflight. Stop partial retries when outputs are missing; the workflow does not reconstruct them. Before restarting the publication workflow, inspect current remote state and obtain approval for its upload scope; this is not cache-only recovery. Do not rerun packaging to recover publication outputs. A manually rerun purge may submit once after confirming the previous task failed. A lost submission response queries matching history instead of resubmitting. An unknown result with a task ID means submission was confirmed; without an ID it may never have been submitted. Inspect EdgeOne history before manual recovery, and a fresh publication run is one recovery option. Operators may instead use the documented [fixed-download purge command](../README.md#fixed-downloads); Windows operators use the existing DPAPI credential launcher described there. This submits only a fixed-URL purge: it does not observe completion or update this Actions run’s journal. Inspect the returned task in EdgeOne before considering recovery complete. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md index 26fbbe578b..097eeb4298 100644 --- a/apps/desktop/publishing/ci/README.zh.md +++ b/apps/desktop/publishing/ci/README.zh.md @@ -83,11 +83,11 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任 ## 放量与官网发布 -按 10% → 30% → 100% 放量时,先通过 COS 流程以 `staging_percentage=10`、`upload_website=false` 完成首次发布,再从 `master` 发起 **Publish Desktop · Rollout & Website**,填写原打包 run ID 并选择 attempt(默认 1,请与原打包 run 核对)。逐步放量时将 `rollout_percentage` 分别设为 30、100;仅发布官网时留空。`upload_website` 默认为 false;必须填写比例或启用官网发布。在此示例中,最后一轮启用它即可上传生产官网安装器并刷新缓存。官网发布独立于放量比例,不要求达到 100%;官网安装包面向所有下载用户。仅发布官网时,publish job 只校验 feed,不修改放量比例。每个平台使用各自的打包 run。 +按 10% → 30% → 100% 放量时,先通过 COS 流程以 `staging_percentage=10`、`upload_website=false` 完成首次发布,再从 `master` 发起 **Publish Desktop · Rollout & Website**,填写原打包 run ID 并选择 attempt(默认 1,请与原打包 run 核对)。逐步放量时将 `rollout_percentage` 分别设为 30、100;仅发布官网时留空。`upload_website` 默认为 false;必须填写比例或启用官网发布。在此示例中,最后一轮启用它即可上传生产官网安装器并刷新缓存。官网发布独立于放量比例,不要求达到 100%;官网安装包面向所有下载用户。修改放量比例前审批一次,官网上传前另行审批一次;上传成功后自动刷新缓存,不再重复审批。上传失败或取消时不执行刷新。仅发布官网时跳过放量 job,只需官网审批;上传 job 仍校验当前 feed,不修改放量比例。每个平台使用各自的打包 run。 准备阶段检查 GitHub 身份、保留清单、小体积更新 YAML 和已完成的首次发布记录,不重新计算安装包哈希,也不重复检查签名或公证。Environment 审批后,执行阶段读取当前 COS 更新清单,核对版本、安装包 URL、大小、哈希和其他元数据仍对应已发布包,只修改 `stagingPercentage`。更新清单缺失或已被其他包替换时拒绝执行。同一比例重复执行不写入;不允许降低比例。审批展示目标比例,当前比例在执行时从 COS 读取。 -官网上传复用原机保留的安装器,只校验该安装器的哈希,沿用已有上传与刷新恢复记录。仅重试缓存刷新时沿用官网审批和上传记录,不再依赖原更新 YAML 或首次 feed 发布记录。官网上传在安装器校验、上传期间保持频道锁,防止中途被更新的 feed 替换;此时竞争该频道的发布会失败。因此纯放量不需要安装器文件,发布官网则需要。比例变更前后的 YAML 写入独立放量审计记录。此流程必须在首次 COS 发布之后执行,不构建安装包、不上传版本化安装包,也不创建 release tag。 +官网上传复用原机保留的安装器,只校验该安装器的哈希,沿用已有上传与刷新恢复记录。Rollout 仅重试缓存刷新时校验准备阶段生成的官网审批摘要和上传记录,不再要求 Environment 审批,不再依赖原更新 YAML 或首次 feed 发布记录。官网上传在安装器校验、上传期间保持频道锁,防止中途被更新的 feed 替换;此时竞争该频道的发布会失败。因此纯放量不需要安装器文件,发布官网则需要。比例变更前后的 YAML 写入独立放量审计记录。此流程必须在首次 COS 发布之后执行,不构建安装包、不上传版本化安装包,也不创建 release tag。 @@ -99,7 +99,7 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任 生产 COS 发布默认启用官网安装包上传和缓存刷新(`upload_website=true`)。取消后仅发布版本化资源及自动更新清单;test 发布不修改生产官网。`upload-website-installer` 上传固定安装包,`purge-website-installer` 刷新该 URL。官网安装包校验器只需要最终 DMG/EXE 和保留的 manifest,匹配生产资格、构建身份及平台,只计算一次安装包 hash,并通过同一打开的文件句柄上传。production nightly 和 stable 包都可以替换官网固定安装包。操作者负责选择预期版本;固定对象没有防降级保护,重跑旧发布可能覆盖新安装包。勾选官网上传时,审批前摘要展示固定官网 URL、选定版本和无防降级保护的说明。原有版本与自动更新发布保留自身校验。 -在每台发布 runner 的 `publishing/production.json` 中将 `edgeOneZoneId` 配置为生产 EdgeOne 站点(例如 `"edgeOneZoneId": "zone-example"`)。官网发布在审批前要求该字段;仅 COS 发布和放量不需要。Actions 不读取仓库变量 `DOWNLOAD_PROD_EO_ZONE_ID`。生产 COS 凭据还需要 `teo:CreatePurgeTask` 和 `teo:DescribePurgeTasks` 权限。官网上传在 Actions 中按 bucket/平台互斥,在原机器上按 bucket/对象互斥;缓存观察单独运行。版本发布、官网上传和缓存刷新分别使用生产审批 Environment,后续 job 和重跑可能需要再次审批。GitHub 每个并发组最多保留一个排队 job,新排队 job 可能取消旧排队 job;重跑前应检查取消记录。 +在每台发布 runner 的 `publishing/production.json` 中将 `edgeOneZoneId` 配置为生产 EdgeOne 站点(例如 `"edgeOneZoneId": "zone-example"`)。官网发布在审批前要求该字段;仅 COS 发布和放量不需要。Actions 不读取仓库变量 `DOWNLOAD_PROD_EO_ZONE_ID`。生产 COS 凭据还需要 `teo:CreatePurgeTask` 和 `teo:DescribePurgeTasks` 权限。官网上传在 Actions 中按 bucket/平台互斥,在原机器上按 bucket/对象互斥;缓存观察单独运行。COS 工作流的版本发布、官网上传和缓存刷新分别使用生产审批 Environment。Rollout 工作流仅在放量修改和官网上传时使用它;缓存刷新跟随已批准的上传执行,不再要求 Environment 审批。重跑带 Environment 的 job 可能需要再次审批。GitHub 每个并发组最多保留一个排队 job,新排队 job 可能取消旧排队 job;重跑前应检查取消记录。 官网状态保存在 releases 根目录同级的 `upload-records/website-<发布 run ID>-/state.json`。macOS 和 Windows 在各自本地磁盘使用相同记录格式。官网 URL 和保存文件名遵循[固定下载规则](../README.zh.md#fixed-downloads)。上传重跑同时核对字节和 `Content-Disposition`;字节相同但响应头缺失或错误时,上传一次并读回验证。记录已完成但远端字节改变时停止恢复,需要重新审批发布。完成标记在元数据修复失败后仍保留。每次新的上传意图清除旧刷新记录,因此修复元数据后需重新刷新缓存;上一次任务 ID 和诊断需查 EdgeOne 历史。未知写入先读取再决定重试;CDN 响应头透传仍需实测。原机器路由和准备阶段输出完整时,仅重跑刷新 job 即可查询已保存任务。启用官网上传时,官网 job 仅跳过明确选择的 test 环境。各 job 的本地预检要求其注入的 `route` 或 `selection` 输出存在。官网审批缺失或变化时,在上传或提交刷新任务前失败。`website-destination` 缺失会扩大两个官网并发组的互斥范围。`runner` 输出缺失可能导致无法调度,尚未进入预检。输出缺失时停止局部重试,workflow 不重建这些输出。重新启动发布 workflow 前,先检查当前远端状态并确认上传范围的审批;这不属于仅缓存恢复。不要为恢复发布输出重跑打包。人工重跑确认旧任务失败后可提交一次。提交响应丢失时查询匹配的历史记录,不重新提交。unknown 带任务 ID 表示提交已确认;没有 ID 则可能从未提交。人工恢复前应检查 EdgeOne 历史,重新发起发布运行是恢复方式之一。操作者也可使用已有的[固定下载刷新命令](../README.zh.md#fixed-downloads);Windows 操作者使用该处说明的 DPAPI 凭据启动器。该命令只提交固定 URL 刷新,不观察完成状态,也不更新本次 Actions 运行的 journal。确认恢复完成前应在 EdgeOne 检查返回的任务。 diff --git a/apps/desktop/scripts/dev.ts b/apps/desktop/scripts/dev.ts index 37515c20b0..0753678c0a 100644 --- a/apps/desktop/scripts/dev.ts +++ b/apps/desktop/scripts/dev.ts @@ -10,6 +10,7 @@ import type { DesktopRelease } from '../src/release.ts' import { developmentRuntimeDirectory, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' import { prepareDevelopmentProject } from './development-project.ts' import { prepareDevelopmentApp } from './development-app.ts' +import { prepareDevelopmentState } from './development-state.ts' import { preparePrimaryRuntime } from './prepare-primary-runtime.ts' const APP_ROOT = resolve(import.meta.dirname, '..') @@ -63,8 +64,7 @@ async function launchElectron(): Promise { const mainPort = debugPort('DSH_DESKTOP_MAIN_INSPECT_PORT', 9229) const rendererPort = debugPort('DSH_DESKTOP_RENDERER_DEBUG_PORT', 9222) const hostPort = debugPort('DSH_DESKTOP_HOST_INSPECT_PORT', 9230) - const home = resolve(process.env.DSH_HOME ?? join(DEVELOPMENT_ROOT, 'home')) - const userData = resolve(process.env.DSH_DESKTOP_USER_DATA_DIR ?? join(DEVELOPMENT_ROOT, 'electron-user-data')) + const { home, userData } = prepareDevelopmentState(APP_ROOT) const environment: NodeJS.ProcessEnv = { ...process.env, DSH_HOME: home, diff --git a/apps/desktop/scripts/development-state.ts b/apps/desktop/scripts/development-state.ts new file mode 100644 index 0000000000..6f5233d8fc --- /dev/null +++ b/apps/desktop/scripts/development-state.ts @@ -0,0 +1,69 @@ +/** Persistent Harness home and Electron browser data for unpackaged Desktop launches. */ +import { existsSync, mkdirSync, readlinkSync, renameSync } from 'node:fs' +import { join, resolve } from 'node:path' + +/** Development state locations selected for one launch. */ +export interface DevelopmentState { + readonly home: string + readonly userData: string +} + +function running(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (error) { + return error instanceof Error && 'code' in error && error.code === 'EPERM' + } +} + +/** Chromium links `SingletonLock` to `-` while a browser process owns the profile on macOS and Linux. */ +function profileInUse(userData: string): boolean { + let target: string + try { + target = readlinkSync(join(userData, 'SingletonLock')) + } catch (error) { + // A missing lock or a non-link lock file means no live owner records itself this way. + if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'EINVAL')) return false + throw error + } + const pid = /-(\d+)$/.exec(target)?.[1] + return pid !== undefined && running(Number(pid)) +} + +/** + * Resolve development state outside `.desktop-build`, which `pnpm run clean` removes. + * A default location that does not exist yet receives the state an earlier launcher left under + * `.desktop-build/development` unless a running Harness Dev still owns that browser profile; + * explicit `DSH_HOME` and `DSH_DESKTOP_USER_DATA_DIR` are used as given. + * @param appRoot - Desktop application directory. + * @param environment - Launch environment with optional location overrides. + * @returns Harness home and Electron user-data directories. + */ +export function prepareDevelopmentState(appRoot: string, environment: NodeJS.ProcessEnv = process.env): DevelopmentState { + const legacyRoot = join(appRoot, '.desktop-build', 'development') + const select = (override: string | undefined, name: string): string => { + if (override !== undefined) return resolve(override) + const path = join(appRoot, '.desktop-dev', name) + const legacy = join(legacyRoot, name) + if (!existsSync(path) && existsSync(legacy)) { + // POSIX renames a directory that a running process still writes, which would split its state. + if (profileInUse(join(legacyRoot, 'electron-user-data'))) { + throw new Error(`desktop development: a running Harness Dev still uses ${legacyRoot}; quit it and retry`) + } + try { + mkdirSync(join(appRoot, '.desktop-dev'), { recursive: true }) + renameSync(legacy, path) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new Error(`desktop development: cannot move ${legacy} to ${path}: ${reason}`, { cause: error }) + } + console.log(`desktop development: moved ${legacy} to ${path}`) + } + return path + } + return { + home: select(environment.DSH_HOME, 'home'), + userData: select(environment.DSH_DESKTOP_USER_DATA_DIR, 'electron-user-data'), + } +} 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/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index e644bb231c..06a57a2239 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -174,15 +174,31 @@ it('keeps rollout approval and website recovery separate without tag creation or const workflow = load(text) as { name: string on: { workflow_dispatch: { inputs: Record } } - jobs: Record; needs?: string[] }> + jobs: Record + if?: string + environment?: unknown + env?: Record + needs?: string[] + }> } expect(workflow.name).toBe('Publish Desktop · Rollout & Website') expect(workflow.on.workflow_dispatch.inputs.package_run_attempt!.required).toBe(true) expect(workflow.on.workflow_dispatch.inputs.upload_website!.default).toBe(false) expect(workflow.on.workflow_dispatch.inputs.rollout_percentage!.default).toBe('') expect(workflow.jobs.publish!.environment).toContain('desktop-production') - expect(workflow.jobs['upload-website-installer']!.needs).toContain('publish') - expect(workflow.jobs['purge-website-installer']!.needs).toContain('upload-website-installer') + expect(workflow.jobs.publish!.if).toBe("needs.prepare.outputs.rollout-requested == 'true'") + const upload = workflow.jobs['upload-website-installer']! + const purge = workflow.jobs['purge-website-installer']! + expect(workflow.jobs.prepare!.outputs!['rollout-requested']).toBe('${{ steps.check.outputs.rollout-requested }}') + expect(upload.name).toBe('Website ${{ needs.prepare.outputs.label }}') + expect(upload.environment).toBe('desktop-production') + expect(upload.if).toBe("${{ !cancelled() && inputs.upload_website && needs.prepare.result == 'success' && needs.prepare.outputs.preset != 'test' && (needs.publish.result == 'success' || (needs.publish.result == 'skipped' && needs.prepare.outputs.rollout-requested == 'false')) }}") + expect(purge.environment).toBeUndefined() + expect(purge.if).toBe("${{ !cancelled() && inputs.upload_website && needs.prepare.outputs.preset != 'test' && needs.upload-website-installer.result == 'success' }}") + expect(purge.needs).toEqual(['route', 'prepare', 'upload-website-installer']) + expect(upload.needs).toEqual(['route', 'prepare', 'publish']) expect(text).not.toMatch(/create-github-app-token|publish-desktop-ci.ts|resolve-retained-desktop-publish-ci.ts/u) expect(text).toContain('publish-desktop-rollout-ci.ts route') expect(workflow.jobs.publish!.env!.DESKTOP_UPLOAD_WEBSITE).toBe('${{ inputs.upload_website }}') @@ -207,11 +223,12 @@ it.each(['apply', 'changed-approval', 'replaced-feed', 'website'] as const)('che await record.record({ type: 'feeds-complete' }) const env = { RUNNER_NAME: 'runner', GITHUB_REPOSITORY: 'owner/repo', DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify({ ...f.manifest.source, runnerLabel: 'dsh-runner' }), - DESKTOP_ROLLOUT_PERCENTAGE: scenario === 'website' ? '' : '30', DESKTOP_UPLOAD_WEBSITE: scenario === 'website' ? 'true' : 'false', + DESKTOP_ROLLOUT_PERCENTAGE: scenario === 'website' ? ' ' : '30', DESKTOP_UPLOAD_WEBSITE: scenario === 'website' ? 'true' : 'false', GITHUB_OUTPUT: join(f.root, 'output'), GITHUB_STEP_SUMMARY: join(f.root, 'summary') } const context = await prepareDesktopRolloutCi(env) await publishDesktopRolloutCi('check', env) expect(await readFile(env.GITHUB_OUTPUT, 'utf8')).toContain(`approval=${context.approval}`) + expect(await readFile(env.GITHUB_OUTPUT, 'utf8')).toContain(`rollout-requested=${scenario !== 'website'}\n`) if (scenario === 'website') { const summary = await readFile(env.GITHUB_STEP_SUMMARY, 'utf8') expect(summary).toContain('官网安装包面向所有下载用户,不受自动更新放量比例限制') diff --git a/apps/desktop/tests/development-state.spec.ts b/apps/desktop/tests/development-state.spec.ts new file mode 100644 index 0000000000..b7e42bd0d2 --- /dev/null +++ b/apps/desktop/tests/development-state.spec.ts @@ -0,0 +1,75 @@ +/** Development launches keep Harness state where repository cleaning does not remove it. */ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { prepareDevelopmentState } from '../scripts/development-state.ts' + +function fixture(): string { + const root = mkdtempSync(join(tmpdir(), 'dsh-development-state-')) + onTestFinished(() => { rmSync(root, { recursive: true, force: true }) }) + return root +} + +it('moves state from .desktop-build into the default development state directory', () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + onTestFinished(() => { vi.restoreAllMocks() }) + const root = fixture() + const legacy = join(root, '.desktop-build', 'development') + mkdirSync(join(legacy, 'home'), { recursive: true }) + mkdirSync(join(legacy, 'electron-user-data')) + writeFileSync(join(legacy, 'home', 'session.jsonl'), 'session') + + const state = prepareDevelopmentState(root, {}) + + expect(state).toEqual({ home: join(root, '.desktop-dev', 'home'), userData: join(root, '.desktop-dev', 'electron-user-data') }) + expect(readFileSync(join(state.home, 'session.jsonl'), 'utf8')).toBe('session') + expect(existsSync(state.userData)).toBe(true) + expect(existsSync(join(legacy, 'home'))).toBe(false) +}) + +it('keeps existing default state and leaves legacy state in place', () => { + const root = fixture() + mkdirSync(join(root, '.desktop-dev', 'home'), { recursive: true }) + mkdirSync(join(root, '.desktop-build', 'development', 'home'), { recursive: true }) + + expect(prepareDevelopmentState(root, {}).home).toBe(join(root, '.desktop-dev', 'home')) + expect(existsSync(join(root, '.desktop-build', 'development', 'home'))).toBe(true) +}) + +it('moves only the default directory that is missing', () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + onTestFinished(() => { vi.restoreAllMocks() }) + const root = fixture() + const legacy = join(root, '.desktop-build', 'development') + mkdirSync(join(legacy, 'home'), { recursive: true }) + mkdirSync(join(legacy, 'electron-user-data')) + + const state = prepareDevelopmentState(root, { DSH_HOME: join(root, 'h') }) + + expect(state).toEqual({ home: join(root, 'h'), userData: join(root, '.desktop-dev', 'electron-user-data') }) + expect(existsSync(state.userData)).toBe(true) + expect(existsSync(join(legacy, 'home'))).toBe(true) +}) + +it('uses explicit locations without moving legacy state', () => { + const root = fixture() + mkdirSync(join(root, '.desktop-build', 'development', 'home'), { recursive: true }) + + expect(prepareDevelopmentState(root, { DSH_HOME: join(root, 'h'), DSH_DESKTOP_USER_DATA_DIR: join(root, 'u') })) + .toEqual({ home: join(root, 'h'), userData: join(root, 'u') }) + expect(existsSync(join(root, '.desktop-build', 'development', 'home'))).toBe(true) + expect(existsSync(join(root, '.desktop-dev'))).toBe(false) +}) + +it.skipIf(process.platform === 'win32')('does not move state that a running Harness Dev still owns', () => { + const root = fixture() + const legacy = join(root, '.desktop-build', 'development') + mkdirSync(join(legacy, 'home'), { recursive: true }) + mkdirSync(join(legacy, 'electron-user-data')) + symlinkSync(`host-${String(process.pid)}`, join(legacy, 'electron-user-data', 'SingletonLock')) + + expect(() => prepareDevelopmentState(root, {})).toThrow('a running Harness Dev still uses') + expect(existsSync(join(legacy, 'home'))).toBe(true) + expect(existsSync(join(root, '.desktop-dev'))).toBe(false) +}) diff --git a/apps/desktop/tests/fixtures/restart-status-owner.nsi b/apps/desktop/tests/fixtures/restart-status-owner.nsi index 59046685d9..d81b9dcc37 100644 --- a/apps/desktop/tests/fixtures/restart-status-owner.nsi +++ b/apps/desktop/tests/fixtures/restart-status-owner.nsi @@ -12,6 +12,7 @@ Section InitPluginsDir File "/oname=$PLUGINSDIR\window-frame.dll" "${STATUS_DLL}" StrCpy $InstallerTheme "dark" + SetOutPath "$EXEDIR\install-root" SetErrors !insertmacro ShowRestartBanner IfErrors +3 @@ -19,6 +20,11 @@ Section Quit StrCpy $0 0 wait: + IfFileExists "$EXEDIR\release-directory" 0 still_owned + SetOutPath "$EXEDIR" + FileOpen $1 "$EXEDIR\directory-released" w + FileClose $1 + still_owned: IfFileExists "$EXEDIR\finish-owner" done Sleep 50 IntOp $0 $0 + 1 diff --git a/apps/desktop/tests/windows-restart-status.ps1 b/apps/desktop/tests/windows-restart-status.ps1 index b48444b29b..a2a39a727d 100644 --- a/apps/desktop/tests/windows-restart-status.ps1 +++ b/apps/desktop/tests/windows-restart-status.ps1 @@ -2,6 +2,10 @@ param([Parameter(Mandatory)][string]$OwnerExe) $ErrorActionPreference = 'Stop' $marker = Join-Path (Split-Path $OwnerExe) 'finish-owner' +$release = Join-Path (Split-Path $OwnerExe) 'release-directory' +$released = Join-Path (Split-Path $OwnerExe) 'directory-released' +$installation = Join-Path (Split-Path $OwnerExe) 'install-root' +$backup = "$installation.old" foreach ($interrupt in 'window', 'owner') { $owner = Start-Process -FilePath $OwnerExe -WindowStyle Hidden -PassThru $window = $null @@ -14,18 +18,31 @@ foreach ($interrupt in 'window', 'owner') { if ($owner.HasExited -or $timer.Elapsed.TotalSeconds -gt 12) { throw 'No status window under the private owner' } Start-Sleep -Milliseconds 40 } while ($true) + New-Item -ItemType File -Path $release | Out-Null + while (-not (Test-Path -LiteralPath $released)) { + if ($owner.HasExited -or $timer.Elapsed.TotalSeconds -gt 15) { throw 'Owner did not release its working directory' } + Start-Sleep -Milliseconds 40 + } + # The window is alive while the installer promotes the staged application. + if ($window.HasExited) { throw 'Status process exited before directory replacement' } + Move-Item -LiteralPath $installation -Destination $backup + Move-Item -LiteralPath $backup -Destination $installation + if ($window.HasExited) { throw 'Status process exited during directory replacement' } if ($interrupt -eq 'window') { $window.Kill() New-Item -ItemType File -Path $marker | Out-Null if (-not $owner.WaitForExit(5000) -or $owner.ExitCode -ne 0) { throw 'Window failure changed owner completion' } } else { $owner.Kill() + if (-not $owner.WaitForExit(5000)) { throw 'Owner did not exit after termination' } } if (-not $window.WaitForExit(5000)) { throw 'The status window survived its owner' } } finally { - if (-not $owner.HasExited) { $owner.Kill() } - if ($window -and -not $window.HasExited) { $window.Kill() } - if (Test-Path -LiteralPath $marker) { Remove-Item -LiteralPath $marker } + if (-not $owner.HasExited) { $owner.Kill(); $owner.WaitForExit() } + if ($window -and -not $window.HasExited) { $window.Kill(); $window.WaitForExit() } + foreach ($file in @($marker, $release, $released)) { + if (Test-Path -LiteralPath $file) { Remove-Item -LiteralPath $file } + } $owner.Dispose() if ($window) { $window.Dispose() } } 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/plugin-market-generator/package.json b/apps/plugin-market-generator/package.json index c2b3aa4e62..1378585bf9 100644 --- a/apps/plugin-market-generator/package.json +++ b/apps/plugin-market-generator/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-market-generator", "description": "Reference generator of plugin market index files from a list of npm packages and Git repositories", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "private": true, "type": "module", "scripts": { diff --git a/apps/web/package.json b/apps/web/package.json index 50e3497c0a..edd7bb580a 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-web-frontend", "description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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-preset/tsconfig.json b/packages/client/ui-agent-preset/tsconfig.json index 6857e811d7..c411802016 100644 --- a/packages/client/ui-agent-preset/tsconfig.json +++ b/packages/client/ui-agent-preset/tsconfig.json @@ -39,7 +39,7 @@ "path": "../ui-session" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" }, { "path": "../ui-settings/tsconfig.client.json" 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 a6dec0971b..57d662c94a 100644 --- a/packages/client/ui-agent-team/package.json +++ b/packages/client/ui-agent-team/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-agent-team", "description": "Web shared task board for a subagent tree", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -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-approval/package.json b/packages/client/ui-approval/package.json index 364ec07e77..4de4c4de44 100644 --- a/packages/client/ui-approval/package.json +++ b/packages/client/ui-approval/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-approval", "description": "Approval composer takeover over the scoped Remote Event waterfall", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-attachment/package.json b/packages/client/ui-attachment/package.json index 8169eb1f26..8d7d0544f0 100644 --- a/packages/client/ui-attachment/package.json +++ b/packages/client/ui-attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-attachment", "description": "Dynamic attachment presentation plugin for conversation input, message-image, and trajectory image slots", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-brand-official/package.json b/packages/client/ui-brand-official/package.json index 2ec4de313f..85432f41d5 100644 --- a/packages/client/ui-brand-official/package.json +++ b/packages/client/ui-brand-official/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-brand-official", "description": "Official DeepSeek Harness brand artwork and click-triggered home background", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 28af833f22..505a358bbf 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -21,11 +21,11 @@ en: 8ca277dc7fed699f zh: 167478dba50f3904 /deepseek-ai-dsh-client-ui-chat/command-and-failure-rows: - en: 30878be703edac57 - zh: 16b84188c8660850 + en: 384a3d7363818b34 + zh: feebd24a46446644 /deepseek-ai-dsh-client-ui-chat/inherited-history-divider: - en: b8b735733697ffdf - zh: 9c735d3798b89d4d + en: a191f90e9a64f6fe + zh: 8e91b8660f9baa18 /deepseek-ai-dsh-client-ui-chat/turn-token-usage: en: d363057b5c0b2571 zh: 0f6fe864d9673576 @@ -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 8d6a921724..75197e7e97 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -70,7 +70,7 @@ Text and reasoning contribute to Assistant visibility only when they contain a n Subagent result notices use the Users icon and show only the localized execution outcome in their heading, without a task description or child ID. Completed means that execution ended normally, not that its output passed validation. Historical notices without a readable outcome retain the generic title; unfamiliar outcomes display “Subagent run ended unexpectedly”. Expanded notices preserve their original model-facing body. -Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions this Client has bound and materialized publish; quota failures in Sessions it never opened do not. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped. +Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions whose `conversation` retain facet a rendering reference currently holds publish; quota failures in Sessions this Client never opened, or that occur while a Session is kept only as a recent view, do not, and resuming the facet does not replay them. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped. Chat adapts Markdown targets at `MarkdownDelegateProvider.getTriggerProps`. The assistant-node Slot obtains `useContextMenu` directly and passes a file-path adapter to the optional mention service; intermediate flow and node owners carry no menu callbacks. Paths resolve against the originating Session’s current working directory when the gesture begins. Menus retain that captured path and line even if focus changes. Undeclared plugin links keep native behavior. @@ -79,7 +79,7 @@ Chat adapts Markdown targets at `MarkdownDelegateProvider.getTriggerProps`. The ## Inherited history divider -A forked Session, such as a fork subagent or a branched conversation, shows a divider labelled “Inherited history above” at its latest inherited `session/end-seed` marker, between the copied history and the Session's own messages. A cut inside a Turn keeps the divider outside that Turn's process folding. The divider appears once the history page that holds the marker is loaded, so a long inherited history may show it only after scrolling up. Sessions without inherited history show no divider. +A forked Session, such as a fork subagent or a branched conversation, shows a divider labelled “Inherited history above” at its latest inherited `session/end-seed` marker, between the copied history and the Session's own messages. The caption starts with the branch glyph that the branch action uses. A cut inside a Turn keeps the divider outside that Turn's process folding. The divider appears once the history page that holds the marker is loaded, so a long inherited history may show it only after scrolling up. Sessions without inherited history show no divider. ----- @@ -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 bd57e895a5..a5693880ce 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -70,7 +70,7 @@ Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node, 子智能体结果通知使用 Users 图标,标题仅显示本地化的执行状态,不附加任务描述或子智能体 ID。完成表示执行正常结束,不表示输出已通过验证。历史通知没有可读取的结束状态时保留通用标题;未知状态显示“子智能体异常结束”。展开后的通知保留原始模型可见正文。 -通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有本 Client 已绑定并已物化的 Session 会发布提示;它从未打开的 Session 中的欠费不会发布。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。 +通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有当前被渲染方引用保留了 `conversation` retain 子要素的 Session 会发布提示;本 Client 从未打开的 Session,以及仅作为最近访问会话保留期间发生的欠费都不会发布,恢复保留后也不补发。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。 Chat 在 `MarkdownDelegateProvider.getTriggerProps` 接入处适配 Markdown 目标。助手节点 Slot 直接获取 `useContextMenu`,向可选的文件引用服务传入路径适配函数;消息流和节点中间层不再携带菜单回调。手势发生时按原始 Session 的当前工作目录解析路径,菜单保留捕获的路径和行号,不受焦点变化影响。未声明的插件链接保留原生行为。 @@ -79,7 +79,7 @@ Chat 在 `MarkdownDelegateProvider.getTriggerProps` 接入处适配 Markdown 目 ## 继承历史分隔线 -分叉产生的会话(例如 fork 子智能体或分支出的对话)在最后一个继承的 `session/end-seed` 标记处显示一条标注“以上为继承的历史消息”的分隔线,把复制来的历史与该会话自己的消息分开。切点位于某个 Turn 内部时,分隔线留在该 Turn 的过程折叠之外。分隔线在包含标记的历史页加载后才出现,因此继承历史较长时,可能要向上滚动才能看到。没有继承历史的会话不显示分隔线。 +分叉产生的会话(例如 fork 子智能体或分支出的对话)在最后一个继承的 `session/end-seed` 标记处显示一条标注“以上为继承的历史消息”的分隔线,把复制来的历史与该会话自己的消息分开。标注以“在新对话中分支”操作所用的分支图标开头。切点位于某个 Turn 内部时,分隔线留在该 Turn 的过程折叠之外。分隔线在包含标记的历史页加载后才出现,因此继承历史较长时,可能要向上滚动才能看到。没有继承历史的会话不显示分隔线。 ----- @@ -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/package.json b/packages/client/ui-chat/package.json index 99b09c1836..7d7f19ea05 100644 --- a/packages/client/ui-chat/package.json +++ b/packages/client/ui-chat/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-chat", "description": "Chat Conversation target, node definitions, renderers, and details surface", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 7e4a3a5f01..9c54cd1753 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -6,6 +6,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type {} from '@deepseek-ai/dsh-api-remotes/client' import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type { GroupKey } from '@deepseek-ai/dsh-client-ui-conversation/client' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -105,18 +106,35 @@ export function apply(ctx: Context): void { // replacement or paging never does, because an old failure scrolling // back into view is not news. const dispose = binding.ctx.effect(() => { - const stop = binding.eventSource.subscribe(() => { - const { change } = binding.eventSource.getSnapshot() - if (change.kind !== 'append') return - for (const { event } of change.entries) { - if (event.type !== 'turn/end' || event.data.reason.kind !== 'error') continue - const { code } = event.data.reason.error - if (quotaNoticeHolds.size > 0 || (code !== 'QUOTA' && code !== 'ACCOUNT_QUOTA')) continue - quotaNotice.set({ code, seq: ++quotaNoticeSeq }) + // Live quota failures are reported only while a rendering reference retains the Session's Conversation. + const retainInfo = ctx.sessions.retainInfo(binding.sessionId) + const retained = (): boolean => ctx.sessions.binding(binding.sessionId) === binding + && (retainInfo.getSnapshot().retainedFacets?.conversation ?? 0) > 0 + let stopEvents: (() => void) | undefined + const follow = (): void => { + if (!retained()) { + stopEvents?.() + stopEvents = undefined + return } - }) + stopEvents ??= binding.eventSource.subscribe(() => { + // A dispatch in progress keeps calling copied listeners after unsubscription. + if (!retained()) return + const { change } = binding.eventSource.getSnapshot() + if (change.kind !== 'append') return + for (const { event } of change.entries) { + if (event.type !== 'turn/end' || event.data.reason.kind !== 'error') continue + const { code } = event.data.reason.error + if (quotaNoticeHolds.size > 0 || (code !== 'QUOTA' && code !== 'ACCOUNT_QUOTA')) continue + quotaNotice.set({ code, seq: ++quotaNoticeSeq }) + } + }) + } + const stopRetained = retainInfo.subscribe(follow) + follow() return () => { - stop() + stopRetained() + stopEvents?.() chatSources.delete(binding) quotaSubscriptions.delete(dispose) } @@ -245,6 +263,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 => { @@ -272,9 +291,8 @@ export function apply(ctx: Context): void { // its top or at line 400, so the same tab is revealed and told where // to land. openFile: async (path, options) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - const url = fileAddressFor(sessionId, cwd, resolveWorkspacePath(current ?? undefined, path)) + const directory = sessionDirectory(ctx.sessions, sessionId) + const url = fileAddressFor(sessionId, directory, resolveWorkspacePath(directory, path)) if (options?.line === undefined) ctx.sidebarRight.openResource(url) else ctx.sidebarRight.openResource(url, { params: { line: options.line } }) await Promise.resolve() 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/MessageItem.module.css b/packages/client/ui-chat/src/client/chat/MessageItem.module.css index 7bb1349e59..02a83126a7 100644 --- a/packages/client/ui-chat/src/client/chat/MessageItem.module.css +++ b/packages/client/ui-chat/src/client/chat/MessageItem.module.css @@ -44,11 +44,31 @@ border-top: 0.5px solid var(--dsw-alias-border-l2); } +/* Glyph and label share one caption and its tertiary ink. The 6px gap matches + a flow row's glyph-to-label gap; without the flow row's 16px leading box the + label starts 20px in rather than 22px. */ +.inheritedHistoryCaption { + flex: 0 1 auto; + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + color: var(--dsw-alias-label-tertiary); +} + +/* The 14px flow-row glyph edge shared with DisclosureRow's leading icon: the + CSS edge overrides the svg's own width/height so the glyph follows the font + delta. */ +.inheritedHistoryIcon { + flex: none; + width: calc(14px + var(--dsh-content-font-delta, 0px)); + height: calc(14px + var(--dsh-content-font-delta, 0px)); +} + .inheritedHistoryLabel { flex: 0 1 auto; min-width: 0; overflow: hidden; - color: var(--dsw-alias-label-tertiary); font-size: var(--dsh-content-font-size-secondary, 13px); line-height: calc(24px + var(--dsh-content-font-delta, 0px)); text-overflow: ellipsis; diff --git a/packages/client/ui-chat/src/client/chat/MessageItem.tsx b/packages/client/ui-chat/src/client/chat/MessageItem.tsx index 8c637e6e6c..d946cc620b 100644 --- a/packages/client/ui-chat/src/client/chat/MessageItem.tsx +++ b/packages/client/ui-chat/src/client/chat/MessageItem.tsx @@ -3,7 +3,7 @@ import type { ReactNode } from 'react' import type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client' import type { PropsRenderFactories, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import type { UserTextFacts } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { JsonBlock, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconBranchOutlineRegular, JsonBlock, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' import type { ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps, UserContentAttachment, UserContentData, UserContentInput, } from '../contract/slots.ts' @@ -384,7 +384,10 @@ export const InheritedHistoryNodeView = memo(function InheritedHistoryNodeView({ return (
- {t('message.inheritedHistory')} + + + {t('message.inheritedHistory')} +
) 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/src/client/file-path.ts b/packages/client/ui-chat/src/client/file-path.ts index 9c23fdc21d..96d39d5000 100644 --- a/packages/client/ui-chat/src/client/file-path.ts +++ b/packages/client/ui-chat/src/client/file-path.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' -import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' /** * Bind path resolution to the originating Session without capturing its current directory. @@ -11,9 +11,5 @@ import type {} from '@deepseek-ai/dsh-api-session-controller/client' * @returns Resolver using the live working directory, falling back to the workspace root. */ export function sessionFilePath(ctx: Context, sessionId: SessionId): (path: string) => string { - return (path) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = ctx.sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - return resolveWorkspacePath(current ?? cwd, path) - } + return path => resolveWorkspacePath(sessionDirectory(ctx.sessions, sessionId), path) } 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..a680f0bf90 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' @@ -46,6 +47,7 @@ type ChatActions = ChatInstance['actions'] function sessionFakeFor() { return { loadOlder: vi.fn(() => Promise.resolve()), + consumeOlder: vi.fn(() => true), loadThrough: vi.fn(() => Promise.resolve()), readAttachment: vi.fn(() => Promise.resolve({ ok: true, @@ -105,12 +107,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 }) @@ -256,6 +258,8 @@ describe('Chat inject API', () => { const { injected } = b.chatViewApi(b.rootReference) injected.loadOlder() expect(b.session.loadOlder).toHaveBeenCalledExactlyOnceWith({ deferConsumption: true }) + expect(injected.consumeOlder()).toBe(true) + expect(b.session.consumeOlder).toHaveBeenCalledOnce() void injected.loadThrough(SessionSeq(42)) expect(b.session.loadThrough).toHaveBeenCalledWith(42) @@ -322,8 +326,9 @@ describe('Chat inject API', () => { const { injected } = b.chatViewApi(b.rootReference) vi.spyOn(b.runtime.ctx.contextMenus, 'open') await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', '/proj/.agents/worktrees/w') + // The address is relative to the same directory the Host resolves it from. await injected.openFile('src/a.ts') - expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/.agents/worktrees/w/src/a.ts') + expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/src/a.ts') expect(injected.resolveFilePath('src/a.ts')).toBe('/proj/.agents/worktrees/w/src/a.ts') await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', null) expect(injected.resolveFilePath('file.ts')).toBe('/proj/file.ts') @@ -331,14 +336,14 @@ describe('Chat inject API', () => { // A leading `./` names the same file, so the Sidebar reuses its tab. await injected.openFile('./src/a.ts') - expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/.agents/worktrees/w/src/a.ts') - await injected.openFile('/proj/src/a.ts') expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/src/a.ts') - // Outside the workspace, the address carries the absolute path after the Session id. + // Outside the Session's directory, the address carries the absolute path after the Session id. + await injected.openFile('/proj/src/a.ts') + expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1//proj/src/a.ts') await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', '/elsewhere') await injected.openFile('src/a.ts') - expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1//elsewhere/src/a.ts') + expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/src/a.ts') await b.runtime.dispose() }) 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-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx index 88c42d6dc2..dea8285608 100644 --- a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx @@ -227,11 +227,32 @@ describe('MessageItem arms', () => { expect(exec).toHaveBeenCalledWith('copy') }) + it('user copy succeeds through execCommand when the host refuses the async write', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }) + const exec = vi.fn().mockReturnValue(true) + Object.defineProperty(document, 'execCommand', { configurable: true, value: exec }) + render( + , + ) + fireEvent.click(screen.getByRole('button', { name: '复制' })) + expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy() + expect(exec).toHaveBeenCalledWith('copy') + }) + it('user copy never claims success when the host rejects the write', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => false) }) render( { ])) }) + it('the inherited-history caption glyph scales with its label', () => { + expect(declarationsFrom(read('MessageItem.module.css'), '.inheritedHistoryIcon')).toEqual(expect.arrayContaining([ + 'width: calc(14px + var(--dsh-content-font-delta, 0px))', + 'height: calc(14px + var(--dsh-content-font-delta, 0px))', + ])) + }) + it('expanded bodies indent by 22px + delta so content stays under the shifted title start', () => { // The DisclosureRow title starts at leading (16 + delta) + gap 6; a fixed // 22px indent would misalign at every non-default size. 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 c7cee3bded..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) @@ -3723,6 +3748,7 @@ describe('ChatView', () => { const own = view.getByText('own question') expect(inherited.compareDocumentPosition(separator) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() expect(separator.compareDocumentPosition(own) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(separator.querySelector('[data-icon="dsw-icon-branch-outline-regular"]')).not.toBeNull() }) it('disables fork when the indexed Turn has a later steering Node', () => { @@ -4921,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-settings-plugin-inventory/src/css-modules.d.ts b/packages/client/ui-connector-account/src/css-modules.d.ts similarity index 100% rename from packages/client/ui-settings-plugin-inventory/src/css-modules.d.ts rename to packages/client/ui-connector-account/src/css-modules.d.ts 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-settings-plugin-inventory/tsconfig.json b/packages/client/ui-connector-account/tsconfig.client.json similarity index 58% rename from packages/client/ui-settings-plugin-inventory/tsconfig.json rename to packages/client/ui-connector-account/tsconfig.client.json index 7f4d2516c2..115af386fd 100644 --- a/packages/client/ui-settings-plugin-inventory/tsconfig.json +++ b/packages/client/ui-connector-account/tsconfig.client.json @@ -2,32 +2,32 @@ "extends": "../../../tsconfig.base.client.json", "compilerOptions": { "rootDir": "src", - "outDir": "lib/types" + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" }, "include": [ - "src" + "src/client", + "src/css-modules.d.ts", + "src/types.ts" ], "references": [ { - "path": "../../util/package-manifest" + "path": "../../../vendor/cordis" }, { - "path": "../../../vendor/cordis" + "path": "../../api/gateway/tsconfig.client.json" }, { "path": "../../api/remotes/tsconfig.client.json" }, { - "path": "../locale/tsconfig.client.json" + "path": "../store" }, { - "path": "../ui-settings/tsconfig.client.json" + "path": "../ui-layout" }, { - "path": "../ui-agent-preset" - }, - { - "path": "../../preset/agent-preset-registry" + "path": "../ui-plugin-manager/tsconfig.client.json" }, { "path": "../ui-primitives" @@ -39,10 +39,19 @@ "path": "../ui-slots" }, { - "path": "../modules" + "path": "../../typert/protocol" }, { - "path": "../store" + "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 c839e300f8..8bbbaa13d3 100644 --- a/packages/client/ui-context-menu/package.json +++ b/packages/client/ui-context-menu/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-context-menu", "description": "Typed, plugin-extensible context menus with captured targets and shared Web presentation", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -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..5161d66a9b 100644 --- a/packages/client/ui-context-menu/src/index.ts +++ b/packages/client/ui-context-menu/src/index.ts @@ -1,4 +1,20 @@ -/** Host Loader entry; menus belong to the Client. */ +/** Host Loader entry declaring the browser menu preparation budget; menus belong to the Client. */ +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type { ContextMenuConfig } from './types.ts' -/** Register the browser plugin without Host behavior. */ -export function apply(): void {} +/** 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; the Loader validates the entry's Config, and the browser face + * receives its volatile fields. + * @param _ctx - Host context; unused. + * @param _config - validated Config; unused on the Host. + */ +export function apply(_ctx: Context, _config: Config): 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 c1b711fdd5..4ea34ddaa5 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -15,14 +15,17 @@ en: eef4f18c3972ccc4 zh: 6be65c6ac84ce497 /deepseek-ai-dsh-client-ui-conversation/conversation-assembly: - en: ef43c4f149195939 - zh: 49fc6c83fd3a05ce + en: 4dcb2d887e3df57f + zh: d4a6e5f4f9a4d67d /deepseek-ai-dsh-client-ui-conversation/sent-user-text: en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 25dd776b1c1562f1 - zh: 1efe8e6e56e73153 + en: 5914222b76430956 + zh: 0eefa0c999bc17a7 +/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 104a182d11..87e68b0a19 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -30,7 +30,9 @@ Desktop product events use the optional [product analytics service](../product-a `UiConversation.events` is the single registry for event Definitions, and `UiConversation.views` is the single registry for target snapshot builders. Both registries reject duplicate keys, preserve registration order, return idempotent disposers, and rebuild existing bindings when their contribution roster changes. `UiConversation.binding(bindingOrSessionId)` returns one identity-stable Conversation binding for the current Session Controller binding. It does not open another event source. A View Definition may declare `toolCallFocus` to translate a tool-call id into its focus identity. Conversation supplies an Inspect callback only while such a target has a visible View entry; Chat consumes this callback without selecting a target. -`ConversationBinding.openTurn` is an identity-stable, read-only source of the latest turn number when its start is loaded and it remains open, or `undefined` otherwise. Observed turn changes publish synchronously even when no View is active. Fixed stop input reads this source alongside Session running and pending-interaction state. Unloading the Session binding detaches its event-source subscription. +`ConversationBinding.openTurn` is an identity-stable, read-only source of the latest turn number when its start is loaded and it remains open, or `undefined` otherwise. While the `conversation` retain facet is held, observed turn changes publish synchronously even when no View is active. Fixed stop input reads this source alongside Session running and pending-interaction state. Unloading the Session binding detaches its event-source subscription. + +The package declares the `conversation` retain facet. A binding follows its event source only while some Session reference retains that facet, which rendering owners such as the main view and Sidebar views request. When the last such reference is released, the binding drops its fold and publishes the empty result; the Session still receives events, and the Session Controller keeps only the last page of its window visible. When retention resumes, the binding folds that window once and publishes it, and paging back folds each older page as it arrives. The adapter passes each `SessionEventLikeEntry` directly to the assembler. Its outer `type` distinguishes durable events from Client-only transient events, while its inner `event` always exposes `type`, `seq`, `time`, and `data`; Definitions receive that inner `SessionEventLike`. Replacement windows may include both entry variants, while historical prepends carry durable entries and live appends may carry either. Definitions use the same match/start/update interface for durable and transient events. The earliest loaded start initializes State; every later Match, including another start for that identity, updates it. Definitions that do not consume Assistant deltas return `null` for `assistant/live-chunk`. Replacement windows and revision gaps rebuild from the complete loaded window; contiguous append, prepend, and Assistant-settlement revisions use incremental assembly. Settlement removes only the named attempt's transient matches, applies its optional durable entry, and recomputes the affected Contexts from their remaining earliest start, refreshing predecessor indexes and dependents without replacing unrelated target nodes. A Context with no remaining start has no State. Its key and previously published nodes remain available to later evidence until a full window rebuild; the owning Definition may hide those nodes. The assembler owns Context matching, Turn/Step locations, target node materialization, target activity, and stable target sources. `ConversationSnapshot` contains only target-neutral views and active-target facts; Session lifecycle state remains in `SessionSnapshot`. @@ -100,13 +102,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; while a draft has attachments, the input hub holds its Session with a `draft` reference that keeps no event connection, so the same composer keeps them after every view releases the Session. 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. 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 +118,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 +134,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 +148,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 +233,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 fb1ecf3770..8302065571 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -30,7 +30,9 @@ kind: "package-reference" `UiConversation.events` 是 event Definition 的唯一 registry,`UiConversation.views` 是 target snapshot builder 的唯一 registry。两者都拒绝重复 key、保持注册顺序、返回幂等 disposer,并在 contribution roster 变化时重建现有 binding。`UiConversation.binding(bindingOrSessionId)` 为当前 Session Controller binding 返回 identity 稳定的 Conversation binding,不会另开事件源。 View Definition 可以声明 `toolCallFocus`,将工具调用 id 转换为自身的焦点标识。仅当此目标拥有可见的 View 条目时,Conversation 才提供 Inspect 回调;Chat 直接使用回调,不选择目标。 -`ConversationBinding.openTurn` 是对象标识稳定的只读来源:最新轮次的开始事件已加载且尚未结束时提供其编号,否则为 `undefined`。观察到的轮次变化同步发布,即使没有活动视图也是如此。固定停止输入同时读取这个来源、会话运行状态和待处理交互状态。卸载会话绑定会解除其事件源订阅。 +`ConversationBinding.openTurn` 是对象标识稳定的只读来源:最新轮次的开始事件已加载且尚未结束时提供其编号,否则为 `undefined`。在 `conversation` retain 子要素被保留期间,观察到的轮次变化同步发布,即使没有活动视图也是如此。固定停止输入同时读取这个来源、会话运行状态和待处理交互状态。卸载会话绑定会解除其事件源订阅。 + +本包声明 `conversation` retain 子要素。只有当某个 Session 引用保留该子要素时,绑定才跟随其事件源;主视图和侧栏视图等渲染方会请求它。最后一个这样的引用被释放时,绑定丢弃折叠结果并发布一次空结果;Session 仍接收事件,Session Controller 只让其窗口的最后一页可见。恢复保留后,绑定对该窗口折叠一次并发布,往上翻页时逐页折叠新进入的页。 适配器把每个 `SessionEventLikeEntry` 直接交给 assembler。外层 `type` 区分持久事件与 Client-only transient event,内部 `event` 则统一公开 `type`、`seq`、`time` 与 `data`;Definition 接收这个内部 `SessionEventLike`。replacement window 可以包含两种 entry,历史 prepend 携带持久 entry,实时 append 则可以携带任一种。持久与瞬态事件使用同一组 match/start/update 接口。当前最早的 start 初始化 State;后续所有 Match,包括同一身份的其他 start,都用于更新。不消费 Assistant delta 的 Definition 对 `assistant/live-chunk` 返回 `null`。replace window 或 revision 断档从完整已加载窗口重建;连续 revision 的 append、prepend 与 Assistant settlement 使用增量组装。settlement 只删除具名 attempt 的 transient match,应用可选持久 entry,并从剩余最早的 start 重算受影响的 Context,刷新前序索引及 dependent,不替换无关 target node。没有剩余 start 的 Context 不保留 State,但其 key 和已发布节点仍保留,供后续证据复用,直到完整窗口重建;所属 Definition 可以隐藏这些节点。assembler 拥有 Context 匹配、Turn/Step location、target node 物化、target activity 和稳定 target source。`ConversationSnapshot` 只包含与 target 无关的 View 与 active-target 事实;Session lifecycle 状态仍属于 `SessionSnapshot`。 @@ -100,13 +102,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 对象不由这一机制持久化;草稿有附件期间,输入 hub 以不保留事件连接的 `draft` 引用持有其 Session,因此所有视图都释放该 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。共享正文与 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 +118,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 +134,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 +148,12 @@ Send 和 Stop 按钮禁用时不显示提示气泡,轮次结束后由 Stop 切 在获得焦点的 Chat 或 Composer 中连续独立按下两次 Esc,可停止当前运行轮次并保留排队消息。间隔由 shortcuts 插件的 `stopSequenceMs` 配置决定,默认 500 ms。菜单、审批、模态层、终端、内嵌网页、输入法、重复按键,以及输入区域、Session 或轮次变化会清空序列。快捷键与 Stop 按钮调用同一作用域取消操作。插件将 Stop 注册为 `input` 展示分组中的固定操作。该注册使普通 Esc 不能分配给可编辑快捷键,并为 Stop 按钮的悬停和键盘聚焦提示提供 `Esc Esc` 序列。 +### 控件布局 + +初始输入区与底部输入区的附件、发送控件共用 32px 直径及工具栏中心线。 + +任务面板的标题和任务文字共用一列,通过相同的前导槽对齐,不改变图标绘制。 + ## 临时 composer entry @@ -223,6 +233,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 3b9b445457..eabdc3ac5a 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-conversation", "description": "Target-neutral Conversation assembly, shell, composer, queue, and view navigation", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -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 4f292f0ece..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,7 +112,7 @@ function hostPathBridge(): HostPathBridge | undefined { interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( - workspaceId: Parameters[0], + workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise } @@ -158,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) @@ -338,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: { @@ -368,7 +363,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), }, - selectWorkspace: workspaceId => workspaceNavigation.openWorkspace(workspaceId, (nextId) => { + 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. @@ -393,7 +388,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { } } } - }), + }, }), }, ConversationContent) @@ -589,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() @@ -602,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 f8bbf67c5b..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,10 +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 and open a blank Session in the selected Workspace. */ - selectWorkspace: (workspaceId: WorkspaceId) => Promise + /** + * 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. + */ + moveDraft: WorkspaceSessionAdopter /** Session-addressed composer block source, or the stable absent source. */ hooks: { composerBlock: ObservableSnapshot } } @@ -683,6 +705,10 @@ export interface ConversationContentInputProps { variant: 'main' | 'embedded' phase: 'settling' | 'hero' | 'active' hero: boolean + /** 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 } /** Values passed from shared content to its occurrence-selected width controls. */ 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/conversation/assembler.ts b/packages/client/ui-conversation/src/client/conversation/assembler.ts index ab1ab05f7b..5398debee0 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembler.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembler.ts @@ -378,11 +378,16 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore /** * Rebuild against the current Registry set after a low-frequency plugin change. + * @param entries - complete window to rebuild from; omitted replays the loaded inputs. + * @param hasMore - whether older history remains outside `entries`. * @returns immediate publication request. */ - rebuildRegistry(): ConversationPublication { + rebuildRegistry( + entries: readonly SessionEventLikeEntry[] = this.sortedInputs(), + hasMore: boolean = this.hasMore, + ): ConversationPublication { this.resetViewBuilders() - return this.replaceWindow(this.sortedInputs(), this.hasMore) + return this.replaceWindow(entries, hasMore) } /** diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index 233a72e23f..75c8ca3364 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -27,16 +27,31 @@ import { ConversationGroupRegistry } from './group-registry.ts' import { ConversationInteractionRegistry } from './interaction-registry.ts' import { UserTextRegistry } from './user-text-registry.ts' -/** Observable faces published for one Session's Conversation assembly. */ +declare module '@deepseek-ai/dsh-api-session-controller/client' { + interface SessionRetainFacetMap { + /** + * Conversation assembly of the Session's event window. While a reference retains it, the binding folds the + * window and follows its changes; when the last such reference is released, the binding drops the fold and + * publishes the empty result, and retaining it again folds the current window once. + */ + conversation: unknown + } +} + +/** + * Observable faces published for one Session's Conversation assembly. Every face follows the + * Session only while a reference retains the `conversation` facet. + */ export interface ConversationBinding { readonly snapshot: ObservableSnapshot /** * Identity-stable source of the latest turn number, undefined unless its start is loaded and it remains open. - * Turn changes publish synchronously, including without an active View. + * Turn changes publish synchronously while the facet is retained, including without an active View. */ readonly openTurn: ObservableSnapshot /** - * Add one selected target to the Session's monotonic active set. + * Add one selected target to the Session's monotonic active set; while the facet is not retained, + * the target's view stays empty until retention folds the window. * @param target - registered or subsequently registered Conversation target. */ activate(target: string): void @@ -59,19 +74,34 @@ class BoundConversation implements ConversationBinding { private readonly targetSources = new Map>() private revision = -1 private frame: number | undefined + private following = false + /** Whether the assembler holds the window at `revision`; a failed fold leaves nothing to extend incrementally. */ + private folded = false private disposeFeed: () => void = () => {} + private disposeRetained: () => void = () => {} + /** + * @param feed - the Session's contiguous event window. + * @param assembler - this binding's Node assembler. + * @param retained - whether any reference retains the `conversation` facet; assembly follows the feed only while true. + */ constructor( - feed: SessionEventSource, + private readonly feed: SessionEventSource, private readonly assembler: ConversationNodeAssembler, + private readonly retained: ObservableSnapshot, ) { this.viewStore = assembler this.snapshot = createSnapshotStore(this.currentSnapshot()) this.openTurn = createSnapshotStore(assembler.openTurn()) - this.replace(feed.getSnapshot()) - this.disposeFeed = feed.subscribe(() => { - this.accept(feed.getSnapshot()) - }) + } + + /** + * Begin following facet retention; the owner registers this binding's disposal first, + * so subscriptions acquired before a failed initial fold still have an owner. + */ + start(): void { + this.disposeRetained = this.retained.subscribe(() => { this.follow(this.retained.getSnapshot()) }) + this.follow(this.retained.getSnapshot()) } target>( @@ -97,19 +127,68 @@ class BoundConversation implements ConversationBinding { this.publishing(() => this.assembler.activateTarget(target)) } - rebuild(): void { this.publish(this.assembler.rebuildRegistry()) } + rebuild(): void { + // A binding that does not follow holds no fold; following again rebuilds against the current registry. + if (!this.following) return + this.publish(this.assembler.rebuildRegistry()) + } dispose(): void { + this.following = false + this.disposeRetained() this.cancelFrame() this.disposeFeed() } + /** + * Start or stop following the feed. Starting folds the whole current window and publishes it at once; + * stopping drops the fold and publishes the empty result. + */ + private follow(retained: boolean): void { + if (retained === this.following) return + this.following = retained + this.cancelFrame() + if (!retained) { + this.disposeFeed() + this.disposeFeed = () => {} + this.folded = false + this.publishing(() => { + this.assembler.rebuildRegistry([], false) + return this.assembler.flush() + }) + return + } + // A dispatch already in progress keeps a copy of its listeners, so the callback checks + // whether the binding still follows rather than relying on unsubscription alone. + this.disposeFeed = this.feed.subscribe(() => { + if (this.following) this.accept(this.feed.getSnapshot()) + }) + this.foldWindow() + } + + /** Fold the whole current window against the current registry and publish it synchronously. */ + private foldWindow(): void { + const window = this.feed.getSnapshot() + this.folded = false + this.cancelFrame() + this.publishing(() => { + this.assembler.rebuildRegistry(window.entries, window.hasMore) + this.revision = window.revision + this.folded = true + return this.assembler.flush() + }) + } + private replace(window: SessionEventWindow): void { this.revision = window.revision this.publish(this.assembler.replaceWindow(window.entries, window.hasMore)) } private accept(window: SessionEventWindow): void { + if (!this.folded) { + this.foldWindow() + return + } if (window.revision === this.revision) return if (window.revision !== this.revision + 1 || window.change.kind === 'replace') { this.replace(window) @@ -269,6 +348,7 @@ export class UiConversation extends Service { const binding = new BoundConversation( owner.eventSource, new ConversationNodeAssembler(this.events, this.views, this.groups), + this.retainedConversation(owner), ) const record: BindingRecord = { source: owner, binding, disposeScope: () => {} } this.bindings.set(owner, record) @@ -277,9 +357,29 @@ export class UiConversation extends Service { 'ui-conversation binding', ) record.disposeScope = () => { void disposeScope() } + try { + binding.start() + } catch (error: unknown) { + // A failed initial fold leaves no binding behind, so the next resolution starts afresh. + this.drop(record, true) + throw error + } return binding } + /** + * Whether a reference retains the `conversation` facet of this exact binding; a same-id + * replacement generation's counts do not apply to a binding that is no longer current. + */ + private retainedConversation(owner: SessionBinding): ObservableSnapshot { + const info = this.sessions.retainInfo(owner.sessionId) + return { + getSnapshot: () => this.sessions.binding(owner.sessionId) === owner + && (info.getSnapshot().retainedFacets?.conversation ?? 0) > 0, + subscribe: listener => info.subscribe(listener), + } + } + /** * Resolve one Gateway-authorized durable image URL, cached per Session so * every Conversation target shares one read and one browser URL. 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..ad18048d26 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -9,7 +9,7 @@ import type { PlanProjection } from '@deepseek-ai/dsh-plan-mode/types' import type { GoalProjection } from '@deepseek-ai/dsh-goal/types' import type { Context } from '@deepseek-ai/cordis' import type { - ISessions, SessionBinding, SessionFace, + ISessions, SessionBinding, SessionFace, SessionReference, SessionSnapshot, } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types' import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client' @@ -17,8 +17,8 @@ import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { ModelSelectionProjection } from '@deepseek-ai/dsh-agent/types' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { - DraftAttachmentId, DraftAttachmentSerializationResult, DraftInitializationOptions, DraftInitializationResult, InputTriggerController, - SessionInputResolver, SessionInput, SubmitOutcome, + DraftAttachmentId, DraftAttachmentSerializationResult, DraftInitializationOptions, DraftInitializationResult, InputState, + InputTriggerController, SessionInputResolver, SessionInput, SubmitOutcome, } from '../contract/input.ts' import type { ComposerKeyboard } from '../contract/draft-editor.ts' import type { ComposerBlocks } from '../contract/composer-blocks.ts' @@ -54,6 +54,43 @@ interface ConversationAttachmentFace { releaseDraftAttachment(id: DraftAttachmentId): void } +declare module '@deepseek-ai/dsh-api-session-controller/client' { + interface SessionReferenceSourceMap { + /** A Session whose composer draft holds attachments, kept without its event connection. */ + draft: unknown + } +} + +/** Whether a draft must keep its Session: it holds browser-owned attachments that nothing can restore. */ +function draftNeedsHold(input: InputState, session: SessionSnapshot): boolean { + return input.attachmentIds.length > 0 && !session.removed +} + +/** 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() @@ -65,7 +102,23 @@ export class InputHub implements SessionInputResolver { constructor( private readonly rootCtx: Context, private readonly t: TranslateNS<'conversation'>, - ) {} + ) { + // An unloading page discards the attachments of every draft that holds its Session. + rootCtx.effect(() => { + const onHide = (): void => { writeUnloadMarks(this.draftHeldSessions()) } + // A back-forward cache restore keeps the drafts, so the marks just written are stale. + const onShow = (event: PageTransitionEvent): void => { + if (!event.persisted) return + for (const sessionId of this.draftHeldSessions()) takeUnloadMark(sessionId) + } + window.addEventListener('pagehide', onHide) + window.addEventListener('pageshow', onShow) + return () => { + window.removeEventListener('pagehide', onHide) + window.removeEventListener('pageshow', onShow) + } + }, 'conversation.input: draft attachment unload marks') + } /** * Resolve the facade for one session-scope ctx (SessionInputResolver face). @@ -127,12 +180,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) => { @@ -170,10 +219,12 @@ export class InputHub implements SessionInputResolver { for (const off of offs) off() const drafts = shell.dispose() this.shells.delete(binding) + // The draft hold keeps this scope while the draft has attachments, so teardown releases them for good. const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined for (const attachmentId of drafts) conversation?.releaseDraftAttachment(attachmentId) } }, 'conversation.input: session shell') + actx.effect(() => this.holdDraft(binding, shell), 'conversation.input: draft hold') actx.inject(['inputTriggers'], (scope) => { scope.effect(() => { shell.refreshLexiconSubscription() @@ -181,9 +232,50 @@ export class InputHub implements SessionInputResolver { }, 'conversation.input: reference catalogs') }) shell.setDraft(readConversationDraft(binding.sessionId)) + // A reload discarded the browser-owned attachments; say so instead of dropping them silently. + if (takeUnloadMark(binding.sessionId)) shell.notify('error', this.t('attachments.unavailable')) return shell } + /** + * Hold the Session without its event connection while its draft has attachments, so leaving the recent views + * keeps the scope, and with it the shell and its attachments. + * @returns disposer releasing the hold. + */ + private holdDraft(binding: SessionBinding, shell: SessionInputShell): () => void { + const sessions = this.sessions() + let reference: SessionReference | undefined + const release = (): void => { + const held = reference + reference = undefined + held?.release() + } + const sync = (): void => { + const needed = draftNeedsHold(shell.snapshot, binding.session.getSnapshot()) + if (needed === (reference !== undefined)) return + if (!needed) { + release() + return + } + const target = sessions.subagentAddress(binding.sessionId) ?? binding.sessionId + reference = sessions.retain(target, { source: 'draft', connection: false }) + } + const stops = [shell.state.subscribe(sync), binding.session.subscribe(sync)] + sync() + return () => { + for (const stop of stops) stop() + release() + } + } + + /** Sessions a draft reference currently holds. */ + private draftHeldSessions(): SessionId[] { + const sessions = this.sessions() + // byId also lists retained subagent Sessions outside the Host list. + return (Object.keys(sessions.list.getSnapshot().byId) as SessionId[]) + .filter(id => (sessions.retainInfo(id).getSnapshot().retainedBy.draft ?? 0) > 0) + } + /** * 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 192446b712..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}', @@ -447,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}', @@ -852,6 +854,7 @@ export const ja = { 'attachment.pathUnavailable': 'フォルダのパスを取得できませんでした。もう一度ドラッグしてください', 'attachment.pathUnsupported': 'パスに参照できない文字が含まれています。名前を変更して再試行してください', 'image.pending': '保留中の画像', + 'attachments.unavailable': '一部の下書き添付ファイルは利用できなくなりました。再度追加してください', 'image.openOriginal': '元の画像を表示', 'image.openOriginalLabel': '{label}、クリックで元の画像を表示', 'image.remove': '画像{name}を削除', @@ -1255,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}', @@ -1660,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}", @@ -2065,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', @@ -2470,6 +2476,7 @@ export const ru = { 'attachment.pathUnavailable': 'Не удалось получить путь к папке; перетащите это снова', 'attachment.pathUnsupported': 'Путь содержит символы, которые не может содержать ссылка; переименуй его и попробуй еще раз', 'image.pending': 'Ожидающие изображения', + 'attachments.unavailable': 'Некоторые вложения черновика больше недоступны; добавьте их снова', 'image.openOriginal': 'Посмотреть оригинал', 'image.openOriginalLabel': '{label}, нажмите, чтобы посмотреть оригинал', 'image.remove': 'Удалить изображение {name}', @@ -2875,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}', 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..72614f500b 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). */ @@ -168,7 +171,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 +183,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() @@ -442,7 +447,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 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 5c5d1149f8..17ab15294e 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -23,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) @@ -123,7 +123,7 @@ export function ConversationContent(props: ConversationContentProps) { onPick: (workspaceId) => { setPickerOpen(false) setPendingWorkspaceId(workspaceId) - void selectWorkspace(workspaceId).catch(() => { + void props.onWorkspaceSelected(workspaceId, moveDraft).catch(() => { setPendingWorkspaceId(current => current === workspaceId ? undefined : current) }) }, @@ -164,7 +164,7 @@ export function ConversationContent(props: ConversationContentProps) { const composerBar = (
- {hero && } + {hero && } {hero && heroWorkspaceRow} {zone !== undefined && renderSlot('conversation.input.dock', zone)} {inputBar} 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/EmptyHero.tsx b/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx index b46db926da..9adcf1e0ac 100644 --- a/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx @@ -67,6 +67,8 @@ export interface HeroShellProps { t: HeroTranslate /** Authorized renderer for the hero brand-mark slot. */ renderSlot: ConversationContentProps['renderSlot'] + /** Text shown instead of the default headline and preview badge. */ + headline?: string | undefined /** Overlay content after the stack (modals). */ children?: ReactNode } @@ -129,7 +131,7 @@ function HeroFish({ hovering }: { hovering: boolean }) { * @param props - see {@link HeroShellProps}. * @returns the centered hero element tree. */ -export function HeroShell({ t, renderSlot, children }: HeroShellProps) { +export function HeroShell({ t, renderSlot, headline, children }: HeroShellProps) { const [hovering, setHovering] = useState(false) return (
@@ -152,8 +154,8 @@ export function HeroShell({ t, renderSlot, children }: HeroShellProps) { {/* Own element: keeps the headline text addressable apart from the badge. */} - {t('hero.headline')} - {t('hero.preview')} + {headline ?? t('hero.headline')} + {headline === undefined && {t('hero.preview')}}
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/client/stop-sequence.ts b/packages/client/ui-conversation/src/client/stop-sequence.ts index bf51f4776e..7eb89bac0f 100644 --- a/packages/client/ui-conversation/src/client/stop-sequence.ts +++ b/packages/client/ui-conversation/src/client/stop-sequence.ts @@ -17,10 +17,10 @@ export class StopSequence { private timer: ReturnType | undefined /** - * @param intervalMs - validated maximum time between independent presses. + * @param intervalMs - reads the current validated maximum time between independent presses; each first press reads it. * @param release - releases observations retained by the pending first press. */ - constructor(private readonly intervalMs: number, private readonly release: () => void) {} + constructor(private readonly intervalMs: () => number, private readonly release: () => void) {} /** Clear the first press and its expiry timer. */ reset(): void { @@ -45,8 +45,9 @@ export class StopSequence { target.cancel() return true } - this.first = { target, deadline: performance.now() + this.intervalMs } - this.timer = setTimeout(() => { this.reset() }, this.intervalMs + 1) + const intervalMs = this.intervalMs() + this.first = { target, deadline: performance.now() + intervalMs } + this.timer = setTimeout(() => { this.reset() }, intervalMs + 1) return false } } diff --git a/packages/client/ui-conversation/src/client/stop-shortcut.ts b/packages/client/ui-conversation/src/client/stop-shortcut.ts index f9b7520073..1c5a0cc584 100644 --- a/packages/client/ui-conversation/src/client/stop-shortcut.ts +++ b/packages/client/ui-conversation/src/client/stop-shortcut.ts @@ -8,7 +8,7 @@ import { StopSequence } from './stop-sequence.ts' /** * Subscribe fixed input to the same Session cancellation used by the stop button. - * @param shortcuts - window keyboard arbitration and validated sequence interval. + * @param shortcuts - window keyboard arbitration and the current validated sequence interval, read at each first press. * @param sessions - live Session identities and lifecycle sources. * @param openTurn - stable current-turn source for a live Session binding. * @param uiSession - effective pending interaction of each Session. @@ -23,7 +23,7 @@ export function installStopShortcut( cancel: (sessionId: SessionId) => void, ): () => void { let unwatch = (): void => {} - const sequence = new StopSequence(shortcuts.stopSequenceMs, () => { + const sequence = new StopSequence(() => shortcuts.stopSequenceMs, () => { unwatch() unwatch = () => {} }) 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 e6384343ef..7634435bea 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' @@ -79,7 +80,7 @@ async function bench(renderQuote = false) { const opened = vi.fn<(id: SessionId) => void>() let mainReference: SessionReference | undefined const replaceMain = (id: SessionId, beforeOpen?: (id: SessionId) => void): void => { - const next = runtime.sessions.retain(id, { source: 'mainView' }) + const next = runtime.sessions.retain(id, { source: 'mainView', facets: { conversation: true } }) try { beforeOpen?.(id) } catch (error: unknown) { @@ -110,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' }, @@ -120,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') => @@ -140,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 @@ -160,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, } } @@ -475,7 +481,7 @@ describe('Conversation inject API', () => { expect(activate).toHaveBeenLastCalledWith('custom') activate.mockClear() - using mainReference = b.runtime.sessions.retain(ROOT, { source: 'mainView' }) + using mainReference = b.runtime.sessions.retain(ROOT, { source: 'mainView', facets: { conversation: true } }) await b.runtime.flush() expect(mainReference.sessionId).toBe(ROOT) expect(activate).not.toHaveBeenCalled() @@ -665,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?.([ @@ -674,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') @@ -689,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') @@ -710,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') @@ -731,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('') @@ -742,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..6d436d46db 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' @@ -57,7 +58,7 @@ const LAYOUT_CHILDREN = { function provideWorkspaceNavigation(runtime: SlotTestRuntime): (id: SessionId) => void { let mainReference: ReturnType | undefined const openSession = (id: SessionId): void => { - const next = runtime.sessions.retain(id, { source: 'mainView' }) + const next = runtime.sessions.retain(id, { source: 'mainView', facets: { conversation: true } }) mainReference?.release() mainReference = next } @@ -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/conversation-registry.client.spec.ts b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts index 9ab5e58380..47e653fbae 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -1,10 +1,10 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { SessionSeq } from '@deepseek-ai/dsh-session/types' -import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types' import { brandString } from '@deepseek-ai/dsh-brand' import { createAssistantMessage, type LlmAttemptId } from '@deepseek-ai/dsh-llm' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import { createScope, MutableSessionEventSource, } from '@deepseek-ai/dsh-api-session-controller/client' @@ -69,8 +69,13 @@ function fakeSession(): SessionFace { } } -function fakeSessions(ctx: Context): { sessions: ISessions; binding: SessionBinding } { +function fakeSessions(ctx: Context): { + sessions: ISessions + binding: SessionBinding + retained: SnapshotStore +} { const scope = createScope(ctx, SESSION_ID) + const retained = createSnapshotStore(true) const binding: SessionBinding = { sessionId: SESSION_ID, session: fakeSession(), @@ -96,7 +101,12 @@ function fakeSessions(ctx: Context): { sessions: ISessions; binding: SessionBind create: () => Promise.reject(new Error('unused fake Sessions operation')), retain: () => reference, using: async (_target, _options, operation) => await operation(reference), - retainInfo: () => createSnapshotStore({ referenceCount: 1, retainedBy: {} }), + retainInfo: () => ({ + getSnapshot: () => ({ + referenceCount: 1, retainedBy: {}, ...(retained.getSnapshot() ? { retainedFacets: { conversation: 1 } } : {}), + }), + subscribe: listener => retained.subscribe(listener), + }), subagentAddress: () => undefined, refreshProjections: () => Promise.reject(new Error('unused fake Sessions operation')), refresh: () => Promise.reject(new Error('unused fake Sessions operation')), @@ -107,7 +117,7 @@ function fakeSessions(ctx: Context): { sessions: ISessions; binding: SessionBind sessionOf: candidate => candidate === binding.ctx ? binding.session : undefined, binding: id => id === SESSION_ID ? binding : undefined, } - return { sessions, binding } + return { sessions, binding, retained } } function eventDefinition(kind: string): ConversationNodeDefinition { @@ -136,17 +146,19 @@ async function bootRegistries(): Promise<{ ctx: Context uiConversation: UiConversation binding: SessionBinding + retained: SnapshotStore events: ConversationEventRegistry views: ConversationViewRegistry }> { const ctx = new Context() onTestFinished(async () => { await ctx.fiber.dispose() }) - const { sessions, binding } = fakeSessions(ctx) + const { sessions, binding, retained } = fakeSessions(ctx) const uiConversation = new UiConversation(ctx, sessions) return { ctx, uiConversation, binding, + retained, events: uiConversation.events, views: uiConversation.views, } @@ -441,6 +453,349 @@ describe('Conversation registries', () => { await binding.ctx.fiber.dispose() }) + it('drops the fold when the conversation facet is released and folds the received window once on resume', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const match = vi.fn((event: SessionEventLike) => event.type === 'turn/start' + ? { id: String(event.data.turn), role: 'start' as const } + : event.type === 'turn/end' ? { id: String(event.data.turn), role: 'update' as const } : null) + events.register({ + kind: 'turn-probe', + target: 'chat', + match, + start: () => 'open', + update: () => 'closed', + buildViewNode: context => ({ key: context.key, kind: 'turn-probe', id: context.id, target: 'chat', data: context.state }), + }) + const built: unknown[] = [] + const chatView: ConversationViewDefinition = { + target: 'chat', + create: () => ({ + empty: [], + replace: ({ nodes }) => { + const data = nodes.map(node => node.data) + built.push(data) + return data + }, + apply: ({ upserts }) => upserts.map(node => node.data), + }), + } + views.register(chatView) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + const source = binding.eventSource as MutableSessionEventSource + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + const listener = vi.fn() + const unsubscribe = conversation.snapshot.subscribe(listener) + retained.set(false) + // Releasing the facet drops the fold and publishes the empty result once. + expect(listener).toHaveBeenCalledOnce() + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + const released = conversation.snapshot.getSnapshot() + listener.mockClear() + match.mockClear() + source.append({ type: 'event', event: { + type: 'turn/end', seq: SessionSeq(2), time: 2, data: { turn: 1, reason: { kind: 'completed' } }, + } }) + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(3), time: 3, data: { turn: 2 } } }) + expect(match).not.toHaveBeenCalled() + expect(listener).not.toHaveBeenCalled() + expect(conversation.snapshot.getSnapshot()).toBe(released) + built.length = 0 + retained.set(true) + expect(listener).toHaveBeenCalledOnce() + expect(built).toEqual([['closed', 'open']]) + expect(conversation.openTurn.getSnapshot()).toBe(2) + source.append({ type: 'event', event: { + type: 'turn/end', seq: SessionSeq(4), time: 4, data: { turn: 2, reason: { kind: 'completed' } }, + } }) + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + unsubscribe() + }) + + it('applies activations and registry changes made while not following once retention resumes', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + retained.set(false) + const source = binding.eventSource as MutableSessionEventSource + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + events.register(eventDefinition('message')) + views.register(viewDefinition('chat')) + await Promise.resolve() + expect(conversation.snapshot.getSnapshot().activeTargets.size).toBe(0) + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + retained.set(true) + expect(conversation.openTurn.getSnapshot()).toBe(1) + expect(conversation.snapshot.getSnapshot().views.get('chat')).toBeNull() + }) + + it('cancels a frame-paced update on release and publishes synchronously when retention resumes', async () => { + const frames = new Map() + let nextFrame = 0 + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++nextFrame, callback) + return nextFrame + }) + vi.stubGlobal('cancelAnimationFrame', (frame: number) => { frames.delete(frame) }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const chunkProbe: ConversationNodeDefinition = { + kind: 'chunk-probe', + target: 'chat', + match: event => event.type === 'assistant/live-chunk' ? { id: 'chunk', role: 'start' } : null, + start: () => 1, + update: context => context.state + 1, + publication: () => 'animation-frame', + buildViewNode: context => ({ key: context.key, kind: 'chunk-probe', id: context.id, target: 'chat', data: context.state }), + } + events.register(chunkProbe) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + const listener = vi.fn() + const unsubscribe = conversation.snapshot.subscribe(listener) + ;(binding.eventSource as MutableSessionEventSource).append({ type: 'transient', event: { + seq: SessionSeq(1), time: 1, type: 'assistant/live-chunk', + data: { attemptId: brandString('chunk'), turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'a' } }, + } }) + expect(frames.size).toBe(1) + retained.set(false) + expect(frames.size).toBe(0) + listener.mockClear() + retained.set(true) + expect(listener).toHaveBeenCalledOnce() + expect(frames.size).toBe(0) + unsubscribe() + }) + + it('leaves no subscription behind when the initial fold fails and folds afresh on the next resolution', async () => { + const { uiConversation, binding, events, views } = await bootRegistries() + let failing = true + const match = vi.fn((event: SessionEventLike) => { + if (failing) throw new Error('definition failed') + return event.type === 'turn/start' ? { id: String(event.data.turn), role: 'start' as const } : null + }) + events.register({ + kind: 'failing-probe', target: 'chat', match, start: () => null, update: context => context.state, + buildViewNode: context => ({ key: context.key, kind: 'failing-probe', id: context.id, target: 'chat', data: null }), + }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const source = binding.eventSource as MutableSessionEventSource + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + expect(() => uiConversation.binding(binding)).toThrow('definition failed') + match.mockClear() + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(2), time: 2, data: { turn: 2 } } }) + expect(match).not.toHaveBeenCalled() + failing = false + const conversation = uiConversation.binding(binding) + expect(match).toHaveBeenCalledTimes(2) + expect(conversation.openTurn.getSnapshot()).toBe(2) + }) + + it('ignores a window change dispatched after an earlier listener released the facet', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const match = vi.fn(() => null) + events.register(eventDefinition('message')) + events.register({ ...eventDefinition('probe'), match }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const source = binding.eventSource as MutableSessionEventSource + const stopReleaser = source.subscribe(() => { retained.set(false) }) + const conversation = uiConversation.binding(binding) + const listener = vi.fn() + conversation.snapshot.subscribe(listener) + match.mockClear() + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + expect(match).not.toHaveBeenCalled() + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + stopReleaser() + }) + + it('publishes one live chunk received while not following synchronously on resume', async () => { + const frames = new Map() + let nextFrame = 0 + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++nextFrame, callback) + return nextFrame + }) + vi.stubGlobal('cancelAnimationFrame', (frame: number) => { frames.delete(frame) }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const chunkProbe: ConversationNodeDefinition = { + kind: 'chunk-probe', + target: 'chat', + match: event => event.type === 'assistant/live-chunk' ? { id: 'chunk', role: 'start' } : null, + start: () => 1, + update: context => context.state + 1, + publication: () => 'animation-frame', + buildViewNode: context => ({ key: context.key, kind: 'chunk-probe', id: context.id, target: 'chat', data: context.state }), + } + events.register(chunkProbe) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + retained.set(false) + const listener = vi.fn() + conversation.snapshot.subscribe(listener) + ;(binding.eventSource as MutableSessionEventSource).append({ type: 'transient', event: { + seq: SessionSeq(1), time: 1, type: 'assistant/live-chunk', + data: { attemptId: brandString('chunk'), turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'a' } }, + } }) + retained.set(true) + expect(listener).toHaveBeenCalledOnce() + expect(frames.size).toBe(0) + }) + + it('folds the window once when a registry rebuild and a window gap wait for resumption', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const match = vi.fn(() => null) + events.register({ ...eventDefinition('probe'), match }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + const source = binding.eventSource as MutableSessionEventSource + retained.set(false) + for (let seq = 1; seq <= 3; seq++) { + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(seq), time: seq, data: { turn: seq } } }) + } + events.register(eventDefinition('late')) + await Promise.resolve() + match.mockClear() + const listener = vi.fn() + conversation.snapshot.subscribe(listener) + retained.set(true) + expect(match).toHaveBeenCalledTimes(3) + expect(conversation.openTurn.getSnapshot()).toBe(3) + }) + + it('keeps following and keeps its activations after the resuming fold fails', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + let failing = false + events.register({ ...eventDefinition('probe'), match: () => { + if (failing) throw new Error('resume failed') + return null + } }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + retained.set(false) + conversation.activate('chat') + failing = true + ;(binding.eventSource as MutableSessionEventSource).replace([{ type: 'event', event: { + type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 }, + } }], false) + retained.set(true) + expect(errors).toHaveBeenCalled() + failing = false + ;(binding.eventSource as MutableSessionEventSource).append({ type: 'event', event: { + type: 'turn/start', seq: SessionSeq(2), time: 2, data: { turn: 2 }, + } }) + expect(conversation.snapshot.getSnapshot().views.get('chat')).toBeNull() + expect(conversation.openTurn.getSnapshot()).toBe(2) + }) + + it('rebuilds the whole window on the next change after a resuming fold fails', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + let failTurn: number | undefined + events.register({ + kind: 'turn-probe', + target: 'recovery-probe', + match: (event) => { + if (event.type !== 'turn/start') return null + if (event.data.turn === failTurn) { + failTurn = undefined + throw new Error('one-time failure') + } + return { id: String(event.data.turn), role: 'start' } + }, + start: () => null, + update: context => context.state, + buildViewNode: context => ({ key: context.key, kind: 'turn-probe', id: context.id, target: 'recovery-probe', data: null }), + }) + const idsView: ConversationViewDefinition = { + target: 'recovery-probe', + create: () => { + let ids: readonly string[] = [] + return { + empty: [], + replace: ({ nodes }) => (ids = nodes.map(node => node.id)), + apply: ({ upserts }) => (ids = [...ids, ...upserts.map(node => node.id).filter(id => !ids.includes(id))]), + } + }, + } + views.register(idsView) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('recovery-probe') + const source = binding.eventSource as MutableSessionEventSource + const start = (turn: number): void => { + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(turn), time: turn, data: { turn } } }) + } + start(1) + retained.set(false) + start(2) + start(3) + failTurn = 2 + retained.set(true) + expect(errors).toHaveBeenCalled() + start(4) + expect(conversation.snapshot.getSnapshot().views.get('recovery-probe')).toEqual(['1', '2', '3', '4']) + }) + + it('reaches the same views on resume as when following every event', async () => { + const turnProbe: ConversationNodeDefinition = { + kind: 'turn-probe', + target: 'recovery-probe', + match: event => event.type === 'turn/start' + ? { id: String(event.data.turn), role: 'start' } + : event.type === 'turn/end' ? { id: String(event.data.turn), role: 'update' } : null, + start: () => 'open', + update: () => 'closed', + buildViewNode: context => ({ key: context.key, kind: 'turn-probe', id: `${context.id}:${context.state}`, target: 'recovery-probe', data: null }), + } + const idsView: ConversationViewDefinition = { + target: 'recovery-probe', + create: () => { + let ids: string[] = [] + return { + empty: [], + replace: ({ nodes }) => (ids = nodes.map(node => node.id)), + apply: ({ upserts }) => { + for (const node of upserts) { + const key = node.id.split(':')[0] + ids = [...ids.filter(id => id.split(':')[0] !== key), node.id] + } + return ids + }, + } + }, + } + const events: SessionEvent[] = [ + { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } }, + { type: 'turn/end', seq: SessionSeq(2), time: 2, data: { turn: 1, reason: { kind: 'completed' } } }, + { type: 'turn/start', seq: SessionSeq(3), time: 3, data: { turn: 2 } }, + ] + const run = async (followAll: boolean): Promise => { + const b = await bootRegistries() + b.events.register(turnProbe) + b.views.register(idsView) + await Promise.resolve() + const conversation = b.uiConversation.binding(b.binding) + conversation.activate('recovery-probe') + if (!followAll) b.retained.set(false) + for (const event of events) (b.binding.eventSource as MutableSessionEventSource).append({ type: 'event', event }) + b.retained.set(true) + return conversation.snapshot.getSnapshot().views.get('recovery-probe') + } + expect(await run(false)).toEqual(await run(true)) + }) + it('rejects duplicate Event Definitions and disposes an ordinary registration once', async () => { const { events } = await bootRegistries() const definition = eventDefinition('message') 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..a4b5b42620 --- /dev/null +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -0,0 +1,318 @@ +// @vitest-environment jsdom +// A draft with attachments holds its Session without the event connection, so leaving every view keeps the same +// composer and its attachments; 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 + /** Release the viewing reference, as leaving every view of the Session does. */ + const switchAway = async (): Promise => { + reference.release() + await runtime.flush() + } + /** Retain the Session for a view 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('holds the Session without its connection and keeps the same composer and attachments', 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.runtime.sessions.retainInfo(sessionId()).getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { draft: 1 } }) + const back = await b.switchBack() + expect(back).toBe(b.shell) + 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('releases the hold once the draft has no attachments', async () => { + const b = await bench() + try { + const [draft] = b.root.createDrafts(sessionId(), [new File([Uint8Array.of(9)], 'pic.png', { type: 'image/png' })], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.switchAway() + expect(b.runtime.sessions.binding(SESSION)).toBeDefined() + b.shell.removeAttachment(draft.id) + await b.runtime.flush() + expect(b.runtime.sessions.binding(SESSION)).toBeUndefined() + } 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 view holds it', 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() + await b.runtime.sessions.remove(SESSION) + await b.runtime.flush() + expect(b.runtime.sessions.binding(SESSION)).toBeUndefined() + expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) + + it('releases the draft attachments when the last view of a removed Session closes', 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.resolveDraftAttachments([draft.id])).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('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() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps working when browser storage refuses the marks', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const b = await bench(() => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + }) + 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')) + expect(b.shell.snapshot.attachmentIds).toEqual([draft.id]) + expect(errors).toHaveBeenCalledTimes(2) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('submitted attachments', () => { + it('does not hold or report attachments of an accepted message', 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.runtime.sessions.retainInfo(sessionId()).getSnapshot().retainedBy.draft).toBeUndefined() + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps a slash line adjudicating with its attachments while the Session is switched away', 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() + const back = await b.switchBack() + expect(back.snapshot.phase).toBe('adjudicating') + 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 e8c20dde27..41c2c9ea9a 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -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 @@ -351,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> }) => { @@ -377,7 +379,7 @@ function mount( renderSlot, renderSlotChain, renderFactorySlot, - selectWorkspace: retargetWorkspace, + moveDraft, t, } const useFactorySlot = ((name: string, fallback: (props: never) => ReactNode) => ( @@ -393,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), @@ -409,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, @@ -437,6 +441,13 @@ describe('Hero chrome', () => { expect(brandMarkOwner.className).toBeTypeOf('string') expect(renderSlot.mock.calls[0]?.[2]?.fallback).toBeTruthy() }) + + it('shows an owner headline instead of the default headline and preview badge', () => { + const view = render( null) as never} headline="Review demo #42" />) + expect(view.getByText('Review demo #42')).toBeTruthy() + expect(view.queryByText('Into the Unknown')).toBeNull() + expect(view.queryByText('Preview')).toBeNull() + }) }) describe('ConversationRoot resident composer', () => { @@ -611,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')) + expect(b.retargetWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.getByText('Selected Folder')).toBeTruthy() }) @@ -892,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 }), [ @@ -904,7 +915,7 @@ 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')) + expect(selectWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.queryByText('Selected Folder')).toBeNull() expect(b.view.getByText('one')).toBeTruthy() }) @@ -972,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-sequence.client.spec.ts b/packages/client/ui-conversation/tests/stop-sequence.client.spec.ts index 94bbb23916..de36f4798b 100644 --- a/packages/client/ui-conversation/tests/stop-sequence.client.spec.ts +++ b/packages/client/ui-conversation/tests/stop-sequence.client.spec.ts @@ -5,9 +5,9 @@ import { StopSequence, type StopTarget } from '../src/client/stop-sequence.ts' const id = (value: string): SessionId => value as SessionId const sequences: StopSequence[] = [] -function setup(interval = 500) { +function setup(interval: number | (() => number) = 500) { vi.useFakeTimers() - const sequence = new StopSequence(interval, () => {}) + const sequence = new StopSequence(typeof interval === 'number' ? () => interval : interval, () => {}) sequences.push(sequence) const cancel = vi.fn() const target: StopTarget = { sessionId: id('s1'), turn: 1, generation: {}, region: document.createElement('div'), cancel } @@ -45,6 +45,18 @@ describe('double Escape stop sequence', () => { expect(sequence.press(target)).toBe(true) }) + it('reads the current interval at each first press', () => { + let interval = 500 + const { sequence, target } = setup(() => interval) + sequence.press(target) + interval = 100 + vi.advanceTimersByTime(300) + expect(sequence.press(target)).toBe(true) + sequence.press(target) + vi.advanceTimersByTime(101) + expect(sequence.press(target)).toBe(false) + }) + it.each(['session', 'turn', 'region', 'generation'] as const)('does not combine presses across %s changes', (field) => { const { sequence, target, cancel } = setup() sequence.press(target) 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-deliverables/README.i18n.yaml b/packages/client/ui-deliverables/README.i18n.yaml index 675bcff105..21a04d23f1 100644 --- a/packages/client/ui-deliverables/README.i18n.yaml +++ b/packages/client/ui-deliverables/README.i18n.yaml @@ -21,8 +21,8 @@ en: 5fc6e2d7926f08c0 zh: 18cdb7450add873e /deepseek-ai-dsh-client-ui-deliverables/use-this-package/the-changed-files-card: - en: 4b279e2bddddc083 - zh: a3135393299c935b + en: 95d8ac2bddeaf524 + zh: 463f2c7826c8913d /deepseek-ai-dsh-client-ui-deliverables/use-this-package/the-review-tab: en: 231547659321f3a8 zh: bc5935cdd46ada56 diff --git a/packages/client/ui-deliverables/README.md b/packages/client/ui-deliverables/README.md index 0632574d83..b6b3a12538 100644 --- a/packages/client/ui-deliverables/README.md +++ b/packages/client/ui-deliverables/README.md @@ -42,7 +42,7 @@ The `present` tool row retains its document icon and recorded result across prog Coding Tools must be enabled to show this card or request its summary. Turning the preference off removes the card immediately while explicit delivery cards, inline file links, and recorded workspace changes remain available. -The card renders the summary the Host serves for the turn's latest `workspace/changes` announcement, read once per announcement through the authenticated summary route; while the read is pending, once the Host answers that the summary is gone, or when it lists no file, there is no card. A single changed file shows “Edited” and its basename with its file-type icon, without a file list; its header retains the counts or binary/oversized status and the file’s accessible full path. Multiple files use a code-file icon and a header naming the complete changed-file count and summed added and deleted lines; hovering or focusing it replaces the counts with “Preview in sidebar”. Each row shows one file's display path in the regular UI font with its own monospace counts, “binary” for a binary file, or “too large” for a file the Host did not capture. Rows appear in the recorded display order, so repository files above the working directory and files outside it sort first. Four rows show before a fold; the control reveals every recorded file and, once expanded, collapses the list again from the bottom. Each row opens the turn's review in the right Sidebar on that file, and the header opens it on the first file. Hovering a file row or the single-file header for 500ms opens a scrollable, single-column preview of the comparison, independent of the Sidebar’s view. Its full path uses muted monospace text and scrolls horizontally when needed. File-status notes accompanying code and hunk headers are hidden in the preview; comparisons without hunks retain their status text. Each row exposes the full path as its accessible description. The preview is 48px narrower than the card, inset 24px on each side, and at most 420px high, further constrained by the viewport. The whole preview fades in and out over 100ms. Moving into the preview keeps it open; leaving it, pressing Escape, or activating the row by pointer or keyboard dismisses it. Comparisons load only when the preview opens and share the review tab’s cache and retry states. +The card renders the summary the Host serves for the turn's latest `workspace/changes` announcement, read once per announcement through the authenticated summary route; while the read is pending, once the Host answers that the summary is gone, or when it lists no file, there is no card. The summary names the directory the turn started in; full paths and the review tab's Sidebar file addresses resolve against it, wherever the Session works when they are read. A single changed file shows “Edited” and its basename with its file-type icon, without a file list; its header retains the counts or binary/oversized status and the file’s accessible full path. Multiple files use a code-file icon and a header naming the complete changed-file count and summed added and deleted lines; hovering or focusing it replaces the counts with “Preview in sidebar”. Each row shows one file's display path in the regular UI font with its own monospace counts, “binary” for a binary file, or “too large” for a file the Host did not capture. Rows appear in the recorded display order, so repository files above the working directory and files outside it sort first. Four rows show before a fold; the control reveals every recorded file and, once expanded, collapses the list again from the bottom. Each row opens the turn's review in the right Sidebar on that file, and the header opens it on the first file. Hovering a file row or the single-file header for 500ms opens a scrollable, single-column preview of the comparison, independent of the Sidebar’s view. Its full path uses muted monospace text and scrolls horizontally when needed. File-status notes accompanying code and hunk headers are hidden in the preview; comparisons without hunks retain their status text. Each row exposes the full path as its accessible description. The preview is 48px narrower than the card, inset 24px on each side, and at most 420px high, further constrained by the viewport. The whole preview fades in and out over 100ms. Moving into the preview keeps it open; leaving it, pressing Escape, or activating the row by pointer or keyboard dismisses it. Comparisons load only when the preview opens and share the review tab’s cache and retry states. ### The review tab diff --git a/packages/client/ui-deliverables/README.zh.md b/packages/client/ui-deliverables/README.zh.md index 2951888e72..46a7e18f51 100644 --- a/packages/client/ui-deliverables/README.zh.md +++ b/packages/client/ui-deliverables/README.zh.md @@ -42,7 +42,7 @@ Web 的 `standard`、`ptc` 与 `cordis` preset 提供 `present`,用于声明 只有开启代码工作工具才展示此卡片并请求其摘要。关闭该偏好会立即隐藏卡片,同时保留显式交付卡片、行内文件链接和已记录的工作区改动。 -卡片渲染 Host 为本轮最新一条 `workspace/changes` 宣告提供的摘要,每条宣告通过经过认证的摘要路由读取一次;读取尚未完成、Host 答复摘要已不存在,或摘要没有列出任何文件时,没有卡片。仅改动一个文件时,标题显示“已编辑”和文件名,配合对应的文件类型图标,不展示文件列表;标题保留增删行数或二进制/过大状态,并通过无障碍描述提供完整路径。多个文件使用代码文件图标,标题给出改动文件总数与增删行数合计;鼠标悬停或键盘聚焦时,统计信息替换为“在侧边栏预览”。每一行使用普通界面字体显示文件路径,增删行数保留等宽字体,二进制文件显示“二进制”,Host 没有捕获的文件显示“过大”。行按记录的展示顺序排列,因此仓库内位于工作目录之上的文件与工作区外的文件排在最前。折叠前显示四行;控件展开全部记录文件,展开后从底部收起列表。每一行在右侧 Sidebar 中打开本轮的 review 并选中该文件,标题则在第一个文件上打开它。 在文件行或单文件标题上悬停 500ms 后,会出现可滚动的单列改动浮层,不受 Sidebar 视图设置影响。顶部完整路径使用较浅的等宽字体,超出宽度时可横向滚动。浮层不显示代码旁的文件状态说明和 hunk 头;没有 hunk 的对比仍显示状态文字。每行通过无障碍描述提供完整路径。浮层比卡片窄 48px,左右各内缩 24px,高度最多 420px,并受视口可用空间限制。整个浮层的淡入和淡出各持续 100ms。鼠标移入浮层后保持打开;移出、按 Escape 或通过鼠标和键盘激活文件行会关闭浮层。对比只在浮层打开时加载,与 review tab 共用缓存及重试状态。 +卡片渲染 Host 为本轮最新一条 `workspace/changes` 宣告提供的摘要,每条宣告通过经过认证的摘要路由读取一次;读取尚未完成、Host 答复摘要已不存在,或摘要没有列出任何文件时,没有卡片。摘要给出该轮开始时所在的目录;完整路径与 review tab 的 Sidebar 文件地址都相对它解析,与读取时 Session 所在的目录无关。仅改动一个文件时,标题显示“已编辑”和文件名,配合对应的文件类型图标,不展示文件列表;标题保留增删行数或二进制/过大状态,并通过无障碍描述提供完整路径。多个文件使用代码文件图标,标题给出改动文件总数与增删行数合计;鼠标悬停或键盘聚焦时,统计信息替换为“在侧边栏预览”。每一行使用普通界面字体显示文件路径,增删行数保留等宽字体,二进制文件显示“二进制”,Host 没有捕获的文件显示“过大”。行按记录的展示顺序排列,因此仓库内位于工作目录之上的文件与工作区外的文件排在最前。折叠前显示四行;控件展开全部记录文件,展开后从底部收起列表。每一行在右侧 Sidebar 中打开本轮的 review 并选中该文件,标题则在第一个文件上打开它。 在文件行或单文件标题上悬停 500ms 后,会出现可滚动的单列改动浮层,不受 Sidebar 视图设置影响。顶部完整路径使用较浅的等宽字体,超出宽度时可横向滚动。浮层不显示代码旁的文件状态说明和 hunk 头;没有 hunk 的对比仍显示状态文字。每行通过无障碍描述提供完整路径。浮层比卡片窄 48px,左右各内缩 24px,高度最多 420px,并受视口可用空间限制。整个浮层的淡入和淡出各持续 100ms。鼠标移入浮层后保持打开;移出、按 Escape 或通过鼠标和键盘激活文件行会关闭浮层。对比只在浮层打开时加载,与 review tab 共用缓存及重试状态。 ### review tab diff --git a/packages/client/ui-deliverables/package.json b/packages/client/ui-deliverables/package.json index b0c436ab89..3db67ca376 100644 --- a/packages/client/ui-deliverables/package.json +++ b/packages/client/ui-deliverables/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-deliverables", "description": "Changed-files card with per-file comparison tabs, delivery cards, and clickable final-response file references for Web", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-deliverables/src/changes.ts b/packages/client/ui-deliverables/src/changes.ts index 2124b41ff1..a7877149a3 100644 --- a/packages/client/ui-deliverables/src/changes.ts +++ b/packages/client/ui-deliverables/src/changes.ts @@ -26,8 +26,11 @@ export const CHANGES_OPEN_ROUTE = CHANGES_OPEN_PATH.slice(1) /** Resource-address prefix of a turn's review tab in the right Sidebar. */ export const CHANGES_REVIEW_ADDRESS = 'dsh-resource://changes-review/session/' -/** The summary fields the route serves; the Host keeps the working directory and snapshot ids to itself. */ -export type ChangesSummary = Pick +/** + * The summary fields the route serves; the Host keeps the snapshot ids to itself. `cwd` is the directory the + * turn started in, which the listed paths are relative to; the Session may work elsewhere by the time it is read. + */ +export type ChangesSummary = Pick /** The comparison the route serves, as the Host computed it. */ export type ChangesDiff = WorkspaceFileDiff @@ -60,12 +63,12 @@ export function isChangedFile(value: unknown): value is WorkspaceChangedFile { /** * Validate a summary read from the summary route. * @param value - decoded JSON. - * @returns whether the value identifies a turn, a complete file list, the total count, and the line totals. + * @returns whether the value identifies a turn, its directory, a complete file list, the total count, and the line totals. */ export function isChangesSummary(value: unknown): value is ChangesSummary { if (!isRecord(value)) return false - const { turn, files, total, added, deleted } = value - return Number.isSafeInteger(turn) && (turn as number) >= 1 && Number.isSafeInteger(total) + const { turn, cwd, files, total, added, deleted } = value + return Number.isSafeInteger(turn) && (turn as number) >= 1 && typeof cwd === 'string' && Number.isSafeInteger(total) && Number.isSafeInteger(added) && Number.isSafeInteger(deleted) && Array.isArray(files) && files.every(isChangedFile) } diff --git a/packages/client/ui-deliverables/src/client/ChangedFiles.tsx b/packages/client/ui-deliverables/src/client/ChangedFiles.tsx index e4500c4a52..3dbd4ad8ec 100644 --- a/packages/client/ui-deliverables/src/client/ChangedFiles.tsx +++ b/packages/client/ui-deliverables/src/client/ChangedFiles.tsx @@ -34,10 +34,9 @@ function Counts({ added, deleted, t }: { added: number; deleted: number } & Prop * @param props - the recorded summary, the review opener, and localized copy. * @returns the card. */ -export function ChangedFiles({ changes, cwd, openReview, t, sessionId, useChangesDiff, loadChangesDiff }: { - /** The served summary with the sequence of the event that announced it. */ - changes: Pick & { seq: number } - cwd: string | undefined +export function ChangedFiles({ changes, openReview, t, sessionId, useChangesDiff, loadChangesDiff }: { + /** The served summary with the sequence of the event that announced it; paths resolve against its `cwd`. */ + changes: Pick & { seq: number } /** Open the turn's review on the file at an original summary index. */ openReview: (index: number) => void } & PropsLocale & PreviewProps) { @@ -70,16 +69,17 @@ export function ChangedFiles({ changes, cwd, openReview, t, sessionId, useChange {singleFile === undefined ? header : <> } /> - + } {singleFile === undefined &&
    {rows.map((file, index) => (
  • } + display={resolveWorkspacePath(changes.cwd, file.path)} + useChangesDiff={useChangesDiff} loadChangesDiff={loadChangesDiff} t={t} />} anchor={} /> - +
  • ))}
} diff --git a/packages/client/ui-deliverables/src/client/Deliverables.tsx b/packages/client/ui-deliverables/src/client/Deliverables.tsx index 89cfa24afa..22013035ec 100644 --- a/packages/client/ui-deliverables/src/client/Deliverables.tsx +++ b/packages/client/ui-deliverables/src/client/Deliverables.tsx @@ -1,4 +1,5 @@ /** The changed-files card, shown only while the Host serves the turn's summary, and explicitly declared files for a closing turn. */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useEffect, useState } from 'react' import type { TurnTailOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client' import { Button, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' @@ -74,7 +75,7 @@ export function Deliverables({ const { getTriggerProps } = useContextMenu() const [expanded, setExpanded] = useState(false) const showCodeDiff = useShowCodeDiff(value => value) - const cwd = useSessions(state => state.byId[sessionId]?.cwd) + const cwd = useSessions(state => selectSessionDirectory(state, sessionId)) const states = usePresentedOpen(value => value) const host = usePresentedHost(value => value) const announced = showCodeDiff ? matched.changes : null @@ -93,7 +94,7 @@ export function Deliverables({ if (host === null) void reloadPresentedHost() }, [host, reloadPresentedHost]) return <> - {changes !== null && { openChangesReview({ sessionId, seq: changes.seq, turn: changes.turn }, index) }} />} {matched.presented.length > 0 &&
parseChangesReviewAddress(tab.contentId), [tab.contentId]) if (coordinates === undefined) throw new Error(`ui-deliverables: not a review address "${tab.contentId}"`) const { seq } = coordinates - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) const summary = useChangesSummary(value => value[changesSummaryUrl(sessionId, seq)]) const state = useStore(store => store.byTab[tab.id]) const host = usePresentedHost(value => value) @@ -95,6 +96,8 @@ export function ReviewTab({ if (host === null) void reloadPresentedHost() }, [host, reloadPresentedHost]) const files = typeof summary === 'object' ? summary.files : [] + // Listed paths are relative to the directory the turn started in, which the Session may have left since. + const turnCwd = typeof summary === 'object' ? summary.cwd : undefined // A navigated index the summary does not list falls back to the first file. const index = state !== undefined && files[state.index] !== undefined ? state.index : 0 const file = files[index] @@ -142,7 +145,9 @@ export function ReviewTab({ {file !== undefined && + onClick={() => { tab.actions.openResource(fileAddressFor(sessionId, cwd, resolveWorkspacePath(turnCwd, file.path))) }}> + + } {file !== undefined && renderSlot('deliverables.review.file.actions', { actionUrl: changedFileUrl(sessionId, seq, index), available: native, diff --git a/packages/client/ui-deliverables/src/present-open.ts b/packages/client/ui-deliverables/src/present-open.ts index 6023625644..4ad451db96 100644 --- a/packages/client/ui-deliverables/src/present-open.ts +++ b/packages/client/ui-deliverables/src/present-open.ts @@ -112,14 +112,13 @@ async function handlePresentOpen(ctx: Context, request: Request): Promise select(useSyncExternalStore(subscribe, getSnapshot))} />) return { view, diffs, loadChangesDiff, openReview, row: screen.getByRole('button', { name: 'View changes to main.ts' }) } diff --git a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts index 4e809d6289..f0295fa626 100644 --- a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts @@ -85,14 +85,14 @@ async function fixture() { } describe('change summary route', () => { - it('serves the Host-held summary without its working directory, and 404 once it is gone', async () => { - const { read, data, summary } = await fixture() + it('serves the Host-held summary with the directory its paths are relative to, and 404 once it is gone', async () => { + const { read, data, summary, cwd } = await fixture() expect(changesSummaryUrl(brandString('owner'), 9)).toBe('api/changes.summary?sessionId=owner&seq=9') const response = await read() expect(response.status).toBe(200) expect(response.headers.get('cache-control')).toBe('no-store') - // The working directory and snapshot ids stay on the Host. - expect(await response.json()).toEqual({ turn: 1, total: 3, added: 3, deleted: 0, files: data.files }) + // The snapshot ids stay on the Host. + expect(await response.json()).toEqual({ turn: 1, cwd, total: 3, added: 3, deleted: 0, files: data.files }) expect((await read('?sessionId=owner&seq=8')).status).toBe(404) expect((await read('?sessionId=other&seq=9')).status).toBe(404) for (const bad of ['', '?seq=9', '?sessionId=owner', '?sessionId=owner&seq=x', '?sessionId=owner&seq=1.5']) { @@ -193,14 +193,15 @@ describe('changed files native open route', () => { expect(isChangedFile({ path: 'a', display: '', added: 1, deleted: 2 })).toBe(false) expect(isChangedFile({ path: 'a', display: 'a', added: 1.5, deleted: 2 })).toBe(false) expect(isChangedFile([])).toBe(false) - expect(isChangesSummary({ turn: 1, total: 0, added: 0, deleted: 0, files: [] })).toBe(true) - expect(isChangesSummary({ turn: 1, total: 1, added: 1, deleted: 0, files: [{ path: 'a', display: 'a', added: 1, deleted: 0 }] })).toBe(true) - expect(isChangesSummary({ turn: '1', total: 0, added: 0, deleted: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 0, total: 0, added: 0, deleted: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 1.5, added: 0, deleted: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 0, added: 0, deleted: 'x', files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 1, added: 1, deleted: 0, files: [{ path: 'a' }] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 0, added: 0, deleted: 0, files: [] })).toBe(true) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 1, added: 1, deleted: 0, files: [{ path: 'a', display: 'a', added: 1, deleted: 0 }] })).toBe(true) + expect(isChangesSummary({ turn: '1', cwd: '/w', total: 0, added: 0, deleted: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 0, cwd: '/w', total: 0, added: 0, deleted: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 1.5, added: 0, deleted: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 0, added: 0, deleted: 'x', files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 1, added: 1, deleted: 0, files: [{ path: 'a' }] })).toBe(false) + expect(isChangesSummary({ turn: 1, total: 0, added: 0, deleted: 0, files: [] })).toBe(false) expect(isChangesSummary([])).toBe(false) expect(isChangesEvent({ turn: 1 })).toBe(true) expect(isChangesEvent({ turn: 1, extra: true })).toBe(true) diff --git a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx index b9a141b1b7..d30f484942 100644 --- a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx @@ -596,7 +596,7 @@ describe('ChangedFiles card', () => { changedFile('~/.zshrc', 0, 0, { binary: true, path: '/home/u/.zshrc' }), ] const changes = { seq: 5 } - const served: ChangesSummary = { turn: 1, files, total: 11, added: 1232, deleted: 326 } + const served: ChangesSummary = { turn: 1, cwd: '/workspace', files, total: 11, added: 1232, deleted: 326 } /** A store already holding the summary the Host served for the announced sequence. */ function servedStore(summary: ChangesSummary = served, seq = 5) { @@ -616,7 +616,7 @@ describe('ChangedFiles card', () => { } it.each([en, zh])('shows one edited filename without a list and opens its review', (locale) => { - const single = servedStore({ turn: 1, files: [changedFile('src/example.scss', 3, 1)], total: 1, added: 3, deleted: 1 }) + const single = servedStore({ turn: 1, cwd: '/workspace', files: [changedFile('src/example.scss', 3, 1)], total: 1, added: 3, deleted: 1 }) const { props, view } = renderCard(new PresentedOpenController(), locale, { changes, presented: [] }, single) const t = makeTranslate(locale) const card = view.container.querySelector('[data-changed-files]')! @@ -631,7 +631,7 @@ describe('ChangedFiles card', () => { }) it.each(['binary', 'oversized'] as const)('keeps the %s status in a single-file header', (flag) => { - const single = servedStore({ turn: 1, files: [changedFile('asset.bin', 0, 0, { [flag]: true })], total: 1, added: 0, deleted: 0 }) + const single = servedStore({ turn: 1, cwd: '/workspace', files: [changedFile('asset.bin', 0, 0, { [flag]: true })], total: 1, added: 0, deleted: 0 }) const { view } = renderCard(new PresentedOpenController(), en, { changes, presented: [] }, single) expect(view.getByText(en[`changes.${flag}`])).toBeTruthy() expect(view.queryByText('+0')).toBeNull() @@ -656,7 +656,7 @@ describe('ChangedFiles card', () => { const fetchMock = vi.fn(async (input: string | URL | Request) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url if (url.endsWith('seq=5')) return Response.json(served) - if (url.endsWith('seq=6')) return Response.json({ turn: 1, files: [], total: 0, added: 0, deleted: 0 }) + if (url.endsWith('seq=6')) return Response.json({ turn: 1, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 }) return new Response('gone', { status: 404 }) }) vi.stubGlobal('fetch', fetchMock) @@ -690,7 +690,7 @@ describe('ChangedFiles card', () => { }) it('sums the header from the Host totals, not from the capped list', () => { - const capped = servedStore({ turn: 1, files: files.slice(0, 1), total: 2, added: 50, deleted: 20 }) + const capped = servedStore({ turn: 1, cwd: '/workspace', files: files.slice(0, 1), total: 2, added: 50, deleted: 20 }) const { view } = renderCard(new PresentedOpenController(), en, { changes, presented: [] as never[] }, capped) expect(view.getByText('Edited 2 files')).toBeTruthy() expect(view.getByText('+50')).toBeTruthy() @@ -809,7 +809,7 @@ describe('ChangedFiles card', () => { }) it('renders without a fold for three files or fewer and beside delivery cards', () => { - const short = servedStore({ turn: 1, files: [...files.slice(0, 1), changedFile('huge.bin', 0, 0, { oversized: true })], total: 2, added: 185, deleted: 43 }) + const short = servedStore({ turn: 1, cwd: '/workspace', files: [...files.slice(0, 1), changedFile('huge.bin', 0, 0, { oversized: true })], total: 2, added: 185, deleted: 43 }) const { view } = renderCard(new PresentedOpenController(), en, { changes, presented: [{ path: 'report.pdf', seq: 6, index: 0 }] as never[] }, short) expect(view.getByText('Edited 2 files')).toBeTruthy() expect(view.getByText('too large')).toBeTruthy() @@ -964,9 +964,9 @@ describe('plugin registration', () => { fetcher.mockResolvedValueOnce(Response.json({ name: 'desktop', available: true, fileManager: 'finder' })) await face.reloadPresentedHost() expect(face.hooks.presentedHost.getSnapshot()).toMatchObject({ name: 'desktop' }) - fetcher.mockResolvedValueOnce(Response.json({ turn: 1, files: [], total: 0, added: 0, deleted: 0 })) + fetcher.mockResolvedValueOnce(Response.json({ turn: 1, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 })) await face.loadChangesSummary(brandString('child-session'), 5) - expect(face.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=5']).toEqual({ turn: 1, files: [], total: 0, added: 0, deleted: 0 }) + expect(face.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=5']).toEqual({ turn: 1, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 }) ctx.emit('connection/reset') expect(face.hooks.presentedHost.getSnapshot()).toBeNull() // The replaced connection may reach a Host that no longer serves the summaries read so far. @@ -979,9 +979,9 @@ describe('plugin registration', () => { expect(openResource).toHaveBeenCalledWith('dsh-resource://changes-review/session/child-session/5/3', { params: { index: 1 } }) expect((registered as { title(address: string): string }).title('dsh-resource://changes-review/session/child-session/5/3')).toBe('Review · turn 3') const tabFace: ReviewInjected = tabEntry!.inject!(brandString('child-session') as never) as Record & ReviewInjected - fetcher.mockResolvedValueOnce(Response.json({ turn: 3, files: [], total: 0, added: 0, deleted: 0 })) + fetcher.mockResolvedValueOnce(Response.json({ turn: 3, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 })) await tabFace.loadChangesSummary(brandString('child-session'), 6) - expect(tabFace.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=6']).toEqual({ turn: 3, files: [], total: 0, added: 0, deleted: 0 }) + expect(tabFace.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=6']).toEqual({ turn: 3, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 }) fetcher.mockResolvedValueOnce(Response.json({ kind: 'binary', path: 'src/a.ts', display: 'src/a.ts' })) await face.loadChangesDiff(brandString('child-session'), 5, 1) expect(face.hooks.changesDiff).toBe(tabFace.hooks.changesDiff) @@ -1098,7 +1098,7 @@ it.each([{}, { turn: '1', callId: 'bad', files: [] }, const owner = tailOwner(deliverablesOf(value), 6) const matched = selectDeliverables(owner)! const summaries = new ChangesSummaryStore() - summaries.state.set({ [changesSummaryUrl(brandString('session'), 5)]: { turn: 1, files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 0 }], total: 1, added: 1, deleted: 0 } }) + summaries.state.set({ [changesSummaryUrl(brandString('session'), 5)]: { turn: 1, cwd: '/workspace', files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 0 }], total: 1, added: 1, deleted: 0 } }) const view = render(('session')} t={makeTranslate(en)} />) expect(view.getByText('Edited a.txt')).toBeTruthy() expect(view.queryByText('Deliverables')).toBeNull() diff --git a/packages/client/ui-deliverables/tests/present-open.host.spec.ts b/packages/client/ui-deliverables/tests/present-open.host.spec.ts index e30c18936b..3e94bc81a2 100644 --- a/packages/client/ui-deliverables/tests/present-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/present-open.host.spec.ts @@ -33,7 +33,9 @@ async function fixture() { cleanups.push(() => ctx.fiber.dispose()) const session: { cwd?: string } = { cwd } await ctx.plugin(LocalFileSystem, { cwd }) - ctx.provide('sandboxPolicy', { workspaceRoot: cwd } as never) + // The workspace scope asks the policy for a live Session's root; this one applies the header directory, then the deployment root. + const resolvePolicy = ({ session: live }: { session: { header: { cwd?: string } } }) => ({ mode: 'read-only', workspaceRoot: live.header.cwd ?? cwd }) + ctx.provide('sandboxPolicy', { workspaceRoot: cwd, resolve: resolvePolicy } as never) await ctx.plugin({ inject: ['fs', 'sandboxPolicy'], apply: (scope) => { @@ -53,6 +55,9 @@ async function fixture() { return { session, target: { type: 'deliverables/presented', data: { turn: 1, callId: 'present-call', files: [file] } } as SessionEvent } }) ctx.provide('sessionQuery', { readEvent } as never) + // Every viewed Session is live with that header, so the workspace scope reads its original project without an Agent. + const live = vi.fn((id: SessionId) => ({ id, header: session })) + ctx.provide('sessions', { get: live } as never) const opener = vi.fn(async (_request: { path: string; action?: 'reveal' }, _signal: AbortSignal) => ({ opened: true as const })) const applications = vi.fn(async () => [{ id: 'player', name: 'Player', default: true, icon: null }]) ctx.provide('sessionController', { workspacePathApplications: applications, resolveAgent, openWorkspacePath: opener, workspaceDesktop: () => ({ name: 'desktop', available: true, fileManager: 'finder' }) } as never) @@ -65,7 +70,8 @@ async function fixture() { `http://localhost${PRESENT_OPEN_PATH}${query}`, { method: 'POST', signal: signal ?? null }, ), connection.browserPeer) return { - browserPeer: connection.browserPeer, applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, resolveAgent, + browserPeer: connection.browserPeer, applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, + resolveAgent, live, } } @@ -239,6 +245,14 @@ it('opens a viewed child Session without activating an Agent', async () => { expect(resolveAgent).not.toHaveBeenCalled() }) +it('refuses a presented file whose Session is neither live nor stored once its event was read', async () => { + const { session, readEvent, live, open, opener } = await fixture() + readEvent.mockResolvedValueOnce({ session, target: { type: 'deliverables/presented', data: { turn: 1, callId: 'gone', files: [{ path: '日记模板.docx' }] } } as SessionEvent }) + live.mockReturnValueOnce(undefined as never) + expect((await open('?sessionId=gone&seq=7&index=0')).status).toBe(404) + expect(opener).not.toHaveBeenCalled() +}) + it('uses the deployment workspace root when the viewed Session has no cwd', async () => { const { session, open, cwd, file, opener } = await fixture() delete session.cwd diff --git a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx index 04543c2a6f..bbc5514a7f 100644 --- a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx @@ -38,7 +38,7 @@ const ADDRESS = changesReviewAddress(COORDINATES) const SUMMARY_URL = changesSummaryUrl(SESSION, 5) const summary: ChangesSummary = { - turn: 2, total: 4, added: 4, deleted: 2, + turn: 2, cwd: '/work/app', total: 4, added: 4, deleted: 2, files: [ { path: 'src/app/main.ts', display: 'src/app/main.ts', added: 3, deleted: 1 }, { path: '/tmp/out/big.bin', display: '~/out/big.bin', added: 0, deleted: 0, oversized: true }, @@ -331,6 +331,23 @@ describe('ReviewTab', () => { expect(view.getByText('after')).toBeTruthy() }) + it('opens a file against the directory its turn started in after the Session moved', () => { + const summaries = new ChangesSummaryStore() + summaries.state.set({ [SUMMARY_URL]: { ...summary, files: [ + { path: 'notes.txt', display: 'notes.txt', added: 1, deleted: 1 }, + { path: '.agents/worktrees/topic/src/a.ts', display: '.agents/worktrees/topic/src/a.ts', added: 1, deleted: 0 }, + ] } }) + const moved = '/work/app/.agents/worktrees/topic' + const outside = mount({ summaries, cwd: moved, params: { index: 0 } }) + fireEvent.click(outside.view.getByRole('button', { name: 'Open notes.txt in sidebar' })) + // The Session's directory no longer contains the file, so its address carries the absolute path. + expect(outside.tabActions.openResource).toHaveBeenCalledWith(fileAddressFor(SESSION, moved, '/work/app/notes.txt')) + outside.view.unmount() + const inside = mount({ summaries, cwd: moved, params: { index: 1 } }) + fireEvent.click(inside.view.getByRole('button', { name: 'Open .agents/worktrees/topic/src/a.ts in sidebar' })) + expect(inside.tabActions.openResource).toHaveBeenCalledWith(fileAddressFor(SESSION, moved, 'src/a.ts')) + }) + it('opens the whole file in the sidebar and the native open only with a desktop', () => { const summaries = new ChangesSummaryStore() summaries.state.set({ [SUMMARY_URL]: summary }) diff --git a/packages/client/ui-directory-picker-browse/README.i18n.yaml b/packages/client/ui-directory-picker-browse/README.i18n.yaml index 744d1fd82d..ff5ed702f1 100644 --- a/packages/client/ui-directory-picker-browse/README.i18n.yaml +++ b/packages/client/ui-directory-picker-browse/README.i18n.yaml @@ -9,8 +9,8 @@ en: d866390164091176 zh: a6272e2f828456ec /deepseek-ai-dsh-client-ui-directory-picker-browse/summary: - en: bc47bb4e84459d7f - zh: 321afd2438ac00e0 + en: 58204bf8518dd318 + zh: d1b5a7cdbf69770f /deepseek-ai-dsh-client-ui-directory-picker-browse/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -21,8 +21,8 @@ en: 18e10884b02f288f zh: 06debd0a4a88bdac /deepseek-ai-dsh-client-ui-directory-picker-browse/understand-the-implementation: - en: 66780e5a328376eb - zh: 7c58a39492a70967 + en: 41e55122b7c432a5 + zh: 631a91054544010e /deepseek-ai-dsh-client-ui-directory-picker-browse/further-exploration: en: 1aa7d7ba154532ed zh: 5bda0ac2de26758c diff --git a/packages/client/ui-directory-picker-browse/README.md b/packages/client/ui-directory-picker-browse/README.md index 10f6789571..435eb52cc9 100644 --- a/packages/client/ui-directory-picker-browse/README.md +++ b/packages/client/ui-directory-picker-browse/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package provides the in-app directory-browsing surface for the Web GUI: a Select Workspace Directory dialog that lists, navigates, and creates folders through the local Host, with no operating-system chooser involved. It fills the two directory-flow slots declared by `ui-workspace`, composing the client side of the browse picking interaction in one cordis.yml row. Choose it when the browser is remote or in-process and no local OS chooser exists; local deployments may prefer the [`-native`](../ui-directory-picker-native/README.md) surface. +This package provides the in-app directory-browsing surface for the Web GUI: a Select Workspace Directory dialog that lists, navigates, and creates folders through the local Host, with no operating-system chooser involved. It fills the three directory-flow slots declared by `ui-workspace`, composing the client side of the browse picking interaction in one cordis.yml row. Choose it when the browser is remote or in-process and no local OS chooser exists; local deployments may prefer the [`-native`](../ui-directory-picker-native/README.md) surface. ## Table of Contents @@ -39,7 +39,7 @@ Step through folders, edit the path directly, or filter the last pane by prefix;
Implementation internals — click to expand -The dialog is a 680×500 Miller-column view (clamped on short or narrow viewports), driven by the host `listDirectory` and `createDirectory` primitives through `ctx.workspaces`. Both registrations install as one transactional effect through nested `ctx.slots.inject()` calls, because either declaring entry may activate later or replace its declaration; the dialog's copy lives in this package's own locale namespace so the two dictionaries land as a unit. Browse failures stay inside the dialog's own alert surfaces, so this occupant never drives the owner's `onError` arm. The node half is an empty `apply` that keeps the plugin on the host roster. +The dialog is a 680×500 Miller-column view (clamped on short or narrow viewports), driven by the host `listDirectory` and `createDirectory` primitives through `ctx.workspaces`. The three registrations install as one transactional effect through nested `ctx.slots.inject()` calls, because each declaring entry or Factory may activate later or replace its declaration; the dialog's copy lives in this package's own locale namespace so the two dictionaries land as a unit. Browse failures stay inside the dialog's own alert surfaces, so this occupant never drives the owner's `onError` arm. The node half is an empty `apply` that keeps the plugin on the host roster. The New folder and Cancel actions use the shared [Button](../ui-primitives/README.md)'s inset hairline, which preserves their layout border and keeps the stroke complete at fractional button widths. diff --git a/packages/client/ui-directory-picker-browse/README.zh.md b/packages/client/ui-directory-picker-browse/README.zh.md index 489a2005bd..00549d631a 100644 --- a/packages/client/ui-directory-picker-browse/README.zh.md +++ b/packages/client/ui-directory-picker-browse/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -本包提供 Web GUI 的应用内目录浏览表面:一个「选择工作区目录」对话框,通过本地宿主列出、导航并创建文件夹,不涉及任何操作系统选择框。它填充 `ui-workspace` 声明的两个目录流程槽位,用一行 cordis.yml 组合出浏览拾取交互的客户端一侧。当浏览器为远程或进程内、没有本地操作系统选择器时选择它;本地部署可优先选择 [`-native`](../ui-directory-picker-native/README.zh.md) 表面。 +本包提供 Web GUI 的应用内目录浏览表面:一个「选择工作区目录」对话框,通过本地宿主列出、导航并创建文件夹,不涉及任何操作系统选择框。它填充 `ui-workspace` 声明的三个目录流程槽位,用一行 cordis.yml 组合出浏览拾取交互的客户端一侧。当浏览器为远程或进程内、没有本地操作系统选择器时选择它;本地部署可优先选择 [`-native`](../ui-directory-picker-native/README.zh.md) 表面。 ## 目录 @@ -39,7 +39,7 @@ kind: "package-reference"
实现细节——点击展开 -对话框是 680×500 的 Miller 分栏视图(在较矮或较窄的视口中限制尺寸),经 `ctx.workspaces` 驱动宿主的 `listDirectory` 与 `createDirectory` 原语。两处注册经嵌套的 `ctx.slots.inject()` 调用作为一次事务性效果安装,因为任一声明条目都可能晚些激活或替换其声明;对话框文案注册在本包自己的 locale 命名空间下,让两份字典作为一个单元落地。浏览类失败留在对话框自己的提示区内,因此本填充从不驱动持有方的 `onError` 分支。node 半部是一个空 `apply`,让插件留在宿主名单上。 +对话框是 680×500 的 Miller 分栏视图(在较矮或较窄的视口中限制尺寸),经 `ctx.workspaces` 驱动宿主的 `listDirectory` 与 `createDirectory` 原语。三处注册经嵌套的 `ctx.slots.inject()` 调用作为一次事务性效果安装,因为每个声明条目或 Factory 都可能晚些激活或替换其声明;对话框文案注册在本包自己的 locale 命名空间下,让两份字典作为一个单元落地。浏览类失败留在对话框自己的提示区内,因此本填充从不驱动持有方的 `onError` 分支。node 半部是一个空 `apply`,让插件留在宿主名单上。 New folder 和 Cancel 操作使用共享 [Button](../ui-primitives/README.zh.md) 的内侧细描边,保留布局边框,并使小数宽度的按钮保持完整描边。 diff --git a/packages/client/ui-directory-picker-browse/package.json b/packages/client/ui-directory-picker-browse/package.json index 4fe0384054..0ac768e2f1 100644 --- a/packages/client/ui-directory-picker-browse/package.json +++ b/packages/client/ui-directory-picker-browse/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-browse", "description": "In-app directory browsing surface: the workspace directory-flow owner rendering the host's listing and creation primitives", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-directory-picker-browse/src/client/index.ts b/packages/client/ui-directory-picker-browse/src/client/index.ts index d3cff16b31..e0c73830b1 100644 --- a/packages/client/ui-directory-picker-browse/src/client/index.ts +++ b/packages/client/ui-directory-picker-browse/src/client/index.ts @@ -1,6 +1,6 @@ /** * Browser half of the browse directory-picker backend: fills ui-workspace's - * two directory-flow holes with the in-app Select Workspace Directory dialog + * three directory-flow holes with the in-app Select Workspace Directory dialog * (figma `Harness` 813-23126 family), driving the node half's * `directoryPicker/list`/`directoryPicker/createDirectory` primitives. * Mounting this package therefore composes both sides of the browse @@ -24,8 +24,8 @@ export const inject = ['slots', 'uiWorkspace', 'locale'] /** * Client plugin body: register the dialog's dictionaries and the browse flow - * into both directory-flow holes through `slots.inject()` because the - * ui-workspace entries may activate later or replace their declarations. + * into all three directory-flow holes through `slots.inject()` because the + * ui-workspace declarations may activate later or be replaced. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { @@ -170,16 +170,20 @@ export function apply(ctx: ClientContext): void { createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name), t: ctx.locale.bind(LOCALE_NS), }) - // Both declaration lifetimes must be live before the pair installs; the - // generator makes the two registrations one transactional effect. The - // outer/inner nesting order is arbitrary; neither hole has precedence. + // Every declaration lifetime must be live before the set installs; the + // generator makes the three registrations one transactional effect. The + // nesting order is arbitrary; no hole has precedence. ctx.slots.inject('conversation.hero.workspace.directoryFlow', () => - ctx.slots.inject('sidebar.workspaces.directoryFlow', function* () { - yield ctx.slots.register({ - name: 'conversation.hero.workspace.directoryFlow', inject: injected, - }, BrowseDirectoryFlow) - yield ctx.slots.register({ - name: 'sidebar.workspaces.directoryFlow', inject: injected, - }, BrowseDirectoryFlow) - })) + ctx.slots.inject('sidebar.workspaces.directoryFlow', () => + ctx.slots.inject('workspace.picker.directoryFlow', function* () { + yield ctx.slots.register({ + name: 'conversation.hero.workspace.directoryFlow', inject: injected, + }, BrowseDirectoryFlow) + yield ctx.slots.register({ + name: 'sidebar.workspaces.directoryFlow', inject: injected, + }, BrowseDirectoryFlow) + yield ctx.slots.register({ + name: 'workspace.picker.directoryFlow', inject: injected, + }, BrowseDirectoryFlow) + }))) } diff --git a/packages/client/ui-directory-picker-browse/tests/client-flow.client.spec.tsx b/packages/client/ui-directory-picker-browse/tests/client-flow.client.spec.tsx index 782ae4d533..b5b87b3190 100644 --- a/packages/client/ui-directory-picker-browse/tests/client-flow.client.spec.tsx +++ b/packages/client/ui-directory-picker-browse/tests/client-flow.client.spec.tsx @@ -17,7 +17,9 @@ usePinnedBrowserLanguages('zh-CN') afterEach(cleanup) -const HOLES = ['conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow'] as const +const HOLES = [ + 'conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow', 'workspace.picker.directoryFlow', +] as const const HOME = '/home/u' const homeListing: DirectoryListing = { @@ -56,7 +58,7 @@ describe('directory-picker-browse client half', () => { expect(inject).toEqual(['slots', 'uiWorkspace', 'locale']) }) - it('fills both directory-flow holes for declarations before or after apply, and leaves with its fiber', async () => { + it('fills all three directory-flow holes for declarations before or after apply, and leaves with its fiber', async () => { const before = await bench() before.declare() const fiber = before.ctx.plugin({ inject: [...inject], apply }) @@ -74,6 +76,27 @@ describe('directory-picker-browse client half', () => { for (const hole of HOLES) expect(after.slots.entries(hole)).toHaveLength(1) }) + it('rolls back the earlier registrations when the Factory hole is already occupied', async () => { + const b = await bench() + b.declare() + // Foreign occupant in the LAST registered hole: the hero and sidebar + // registrations already landed when the third one throws. + b.slots.register({ name: HOLES[2] } as never, () => null) + const rejections: unknown[] = [] + const onUnhandled = (reason: unknown): void => { rejections.push(reason) } + process.on('unhandledRejection', onUnhandled) + try { + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await expect(fiber.await()).rejects.toThrow(/already has a registration/) + expect(b.slots.entries(HOLES[0])).toHaveLength(0) + expect(b.slots.entries(HOLES[1])).toHaveLength(0) + expect(b.slots.entries(HOLES[2])).toHaveLength(1) + } finally { + await new Promise(resolve => setTimeout(resolve, 0)) + process.off('unhandledRejection', onUnhandled) + } + }) + it('rolls back the outer injection when the second hole is already occupied', async () => { const b = await bench() b.declare() @@ -107,15 +130,14 @@ describe('directory-picker-browse client half', () => { process.on('uncaughtException', onUnhandled) try { // The rival subscribes first, so synchronous declaration notifications - // let it occupy the pair before this provider's waiting injection runs. - b.slots.inject(HOLES[0], () => b.slots.inject(HOLES[1], function* () { - yield b.slots.register({ name: HOLES[0] } as never, () => null) - yield b.slots.register({ name: HOLES[1] } as never, () => null) - })) + // let it occupy the set before this provider's waiting injection runs. + b.slots.inject(HOLES[0], () => b.slots.inject(HOLES[1], () => b.slots.inject(HOLES[2], function* () { + for (const hole of HOLES) yield b.slots.register({ name: hole } as never, () => null) + }))) await b.ctx.plugin({ inject: [...inject], apply }).await() b.declare() await new Promise(resolve => setTimeout(resolve, 20)) - // The rival keeps both holes; this provider rolled back wholesale and + // The rival keeps every hole; this provider rolled back wholesale and // surfaced the conflict on the fail-loud channel — no partial mix. for (const hole of HOLES) expect(b.slots.entries(hole)).toHaveLength(1) expect(rejections.map(String).join('\n')).toContain('already has a registration') diff --git a/packages/client/ui-directory-picker-browse/tsconfig.json b/packages/client/ui-directory-picker-browse/tsconfig.json index 291b7c6137..5672d1c28a 100644 --- a/packages/client/ui-directory-picker-browse/tsconfig.json +++ b/packages/client/ui-directory-picker-browse/tsconfig.json @@ -27,7 +27,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" } ] } diff --git a/packages/client/ui-directory-picker-native/README.i18n.yaml b/packages/client/ui-directory-picker-native/README.i18n.yaml index d7fe01a1f6..e793449ffc 100644 --- a/packages/client/ui-directory-picker-native/README.i18n.yaml +++ b/packages/client/ui-directory-picker-native/README.i18n.yaml @@ -9,8 +9,8 @@ en: dd00fd3c4c22a356 zh: 070b3db2cce5ecc3 /deepseek-ai-dsh-client-ui-directory-picker-native/summary: - en: e039fd6b8a89ef2e - zh: dd4b40cfc0bc4fd5 + en: 0a49bc4656f68f42 + zh: f60488c2bcda9267 /deepseek-ai-dsh-client-ui-directory-picker-native/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -18,11 +18,11 @@ en: 1e2172c756246031 zh: f33dc7b40b14cceb /deepseek-ai-dsh-client-ui-directory-picker-native/use-this-package/when-to-choose-it: - en: f30bb7c6aae98fec - zh: 1d28613c86531119 + en: ebf01aaeec5ae0ff + zh: 413ee218854973bf /deepseek-ai-dsh-client-ui-directory-picker-native/understand-the-implementation: - en: f7a287740b4b08f9 - zh: 3347375c4e486b22 + en: 595181b115b5e66a + zh: db174d924f29ad45 /deepseek-ai-dsh-client-ui-directory-picker-native/further-exploration: en: e775e2ad37a55005 zh: 1d420301c12bc4a1 diff --git a/packages/client/ui-directory-picker-native/README.md b/packages/client/ui-directory-picker-native/README.md index 7a77767050..0d2b972955 100644 --- a/packages/client/ui-directory-picker-native/README.md +++ b/packages/client/ui-directory-picker-native/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package provides the native directory-picking surface for the Web GUI: when a workspace flow asks for a directory, a renderless browser occupant opens the operating system's own chooser on the local machine and reports the single outcome — a picked path, a cancellation, or a failure. It fills the two directory-flow slots declared by `ui-workspace`, composing the client side of the native picking interaction in one `cordis.yml` row. Choose it when the browser runs on the same machine as the Host; in-process and remote-browser deployments need the [`-browse`](../ui-directory-picker-browse/README.md) surface instead. +This package provides the native directory-picking surface for the Web GUI: when a workspace flow asks for a directory, a renderless browser occupant opens the operating system's own chooser on the local machine and reports the single outcome — a picked path, a cancellation, or a failure. It fills the three directory-flow slots declared by `ui-workspace`, composing the client side of the native picking interaction in one `cordis.yml` row. Choose it when the browser runs on the same machine as the Host; in-process and remote-browser deployments need the [`-browse`](../ui-directory-picker-browse/README.md) surface instead. ## Table of Contents @@ -33,7 +33,7 @@ In the local Electron application, this flow uses the narrow preload directory-p Choose this surface when the browser runs on the same machine as the Host, so an OS dialog can open there. Choose the [`-browse`](../ui-directory-picker-browse/README.md) surface when the browser is remote or in-process and no local chooser exists. The two surfaces fill the same slots, so switching is a composition change, not a code change. -Access: both directory flows are registered only while the current Peer may call `directoryPicker/pick`. The owner always has access. +Access: all three directory flows are registered only while the current Peer may call `directoryPicker/pick`. The owner always has access. ----- @@ -43,7 +43,7 @@ Access: both directory flows are registered only while the current Peer may call
Implementation internals — click to expand -Both slot registrations install as one transactional effect through nested `ctx.slots.inject()` calls, because either declaring entry may activate later or replace its declaration. The occupant arms once per rising `open` edge, so re-renders never launch a second chooser; settlements ride a ref so the answer reaches the owner's latest handlers. An unmount (HMR replacing the occupant) discards the settlement wholesale: the wire carries no per-request abort, so the native chooser survives until answered and its answer lands nowhere. The node half is an empty `apply` that keeps the plugin on the host roster. +The three slot registrations install as one transactional effect through nested `ctx.slots.inject()` calls, because each declaring entry or Factory may activate later or replace its declaration. The occupant arms once per rising `open` edge, so re-renders never launch a second chooser; settlements ride a ref so the answer reaches the owner's latest handlers. An unmount (HMR replacing the occupant) discards the settlement wholesale: the wire carries no per-request abort, so the native chooser survives until answered and its answer lands nowhere. The node half is an empty `apply` that keeps the plugin on the host roster.
diff --git a/packages/client/ui-directory-picker-native/README.zh.md b/packages/client/ui-directory-picker-native/README.zh.md index 0bb78f28d1..ca330a692e 100644 --- a/packages/client/ui-directory-picker-native/README.zh.md +++ b/packages/client/ui-directory-picker-native/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -本包提供 Web GUI 的原生目录拾取表面:当工作区流程请求一个目录时,一个无渲染的浏览器填充会在本地机器上打开操作系统自带的选择器,并回报唯一结果——拾取的路径、取消或失败。它填充 `ui-workspace` 声明的两个目录流程 slot,用一行 `cordis.yml` 组合出原生拾取交互的客户端一侧。当浏览器与 Host 运行在同一台机器上时选择它;进程内与远程浏览器部署则需要 [`-browse`](../ui-directory-picker-browse/README.zh.md) 表面。 +本包提供 Web GUI 的原生目录拾取表面:当工作区流程请求一个目录时,一个无渲染的浏览器填充会在本地机器上打开操作系统自带的选择器,并回报唯一结果——拾取的路径、取消或失败。它填充 `ui-workspace` 声明的三个目录流程 slot,用一行 `cordis.yml` 组合出原生拾取交互的客户端一侧。当浏览器与 Host 运行在同一台机器上时选择它;进程内与远程浏览器部署则需要 [`-browse`](../ui-directory-picker-browse/README.zh.md) 表面。 ## 目录 @@ -33,7 +33,7 @@ kind: "package-reference" 当浏览器与 Host 运行在同一台机器上、操作系统对话框可以在那里打开时,选择此表面。当浏览器为远程或进程内、没有本地选择器时,选择 [`-browse`](../ui-directory-picker-browse/README.zh.md) 表面。两个表面填充相同的 slot,因此切换只是组合改动,而非代码改动。 -访问控制:两个目录选择流程只在当前 Peer 可以调用 `directoryPicker/pick` 时注册。owner 始终有权限。 +访问控制:三个目录选择流程只在当前 Peer 可以调用 `directoryPicker/pick` 时注册。owner 始终有权限。 ----- @@ -43,7 +43,7 @@ kind: "package-reference"
实现细节——点击展开 -两个 slot 注册经嵌套的 `ctx.slots.inject()` 调用作为一个事务性 effect 安装,因为任一声明条目都可能晚些激活或替换其声明。填充在每个上升沿 `open` 时只武装一次,因此重渲染永远不会再拉起一个选择器;结算结果挂在 ref 上,让答复到达持有方最新的处理器。HMR(热模块替换)导致填充被替换时,卸载会整体丢弃结算:wire 没有按请求中止的机制,因此 Host 侧选择器会一直存活到被答复,而它的答复无处落地。node 半部是一个空 `apply`,让插件留在 Host 名单上。 +三个 slot 注册经嵌套的 `ctx.slots.inject()` 调用作为一个事务性 effect 安装,因为每个声明条目或 Factory 都可能晚些激活或替换其声明。填充在每个上升沿 `open` 时只武装一次,因此重渲染永远不会再拉起一个选择器;结算结果挂在 ref 上,让答复到达持有方最新的处理器。HMR(热模块替换)导致填充被替换时,卸载会整体丢弃结算:wire 没有按请求中止的机制,因此 Host 侧选择器会一直存活到被答复,而它的答复无处落地。node 半部是一个空 `apply`,让插件留在 Host 名单上。
diff --git a/packages/client/ui-directory-picker-native/package.json b/packages/client/ui-directory-picker-native/package.json index 4ad554e0b3..9008103bf8 100644 --- a/packages/client/ui-directory-picker-native/package.json +++ b/packages/client/ui-directory-picker-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-native", "description": "Native directory-picker surface: the renderless workspace directory-flow occupant driving the local Desktop or Host OS chooser", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-directory-picker-native/src/client/index.ts b/packages/client/ui-directory-picker-native/src/client/index.ts index 1bdcafecdd..ea2f29d00c 100644 --- a/packages/client/ui-directory-picker-native/src/client/index.ts +++ b/packages/client/ui-directory-picker-native/src/client/index.ts @@ -15,9 +15,9 @@ export const inject = ['slots', 'uiWorkspace', 'remoteAccess'] /** * Client plugin body: while the current Peer may open the Host's directory - * chooser, register the renderless native flow into both directory-flow holes - * through `slots.inject()` because the ui-workspace entries may activate later - * or replace their declarations. + * chooser, register the renderless native flow into all three directory-flow + * holes through `slots.inject()` because the ui-workspace declarations may + * activate later or be replaced. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { @@ -26,17 +26,21 @@ export function apply(ctx: ClientContext): void { }).__DSH_DIRECTORY_PICKER__ const pick = desktop === undefined ? () => ctx.uiWorkspace.pickDirectory() : () => desktop.pick() const injected = (): NativeFlowInjected => ({ pick }) - // Both declaration lifetimes must be live before the pair installs; the - // generator makes the two registrations one transactional effect. The - // outer/inner nesting order is arbitrary; neither hole has precedence. + // Every declaration lifetime must be live before the set installs; the + // generator makes the three registrations one transactional effect. The + // nesting order is arbitrary; no hole has precedence. ctx.remoteAccess.whenAccess('directoryPicker/pick', () => ctx.slots.inject('conversation.hero.workspace.directoryFlow', () => - ctx.slots.inject('sidebar.workspaces.directoryFlow', function* () { - yield ctx.slots.register({ - name: 'conversation.hero.workspace.directoryFlow', inject: injected, - }, NativeDirectoryFlow) - yield ctx.slots.register({ - name: 'sidebar.workspaces.directoryFlow', inject: injected, - }, NativeDirectoryFlow) - }))) + ctx.slots.inject('sidebar.workspaces.directoryFlow', () => + ctx.slots.inject('workspace.picker.directoryFlow', function* () { + yield ctx.slots.register({ + name: 'conversation.hero.workspace.directoryFlow', inject: injected, + }, NativeDirectoryFlow) + yield ctx.slots.register({ + name: 'sidebar.workspaces.directoryFlow', inject: injected, + }, NativeDirectoryFlow) + yield ctx.slots.register({ + name: 'workspace.picker.directoryFlow', inject: injected, + }, NativeDirectoryFlow) + })))) } diff --git a/packages/client/ui-directory-picker-native/tests/client-flow.client.spec.tsx b/packages/client/ui-directory-picker-native/tests/client-flow.client.spec.tsx index fd3b22d315..9966b719eb 100644 --- a/packages/client/ui-directory-picker-native/tests/client-flow.client.spec.tsx +++ b/packages/client/ui-directory-picker-native/tests/client-flow.client.spec.tsx @@ -28,7 +28,9 @@ vi.mock('../../../../apps/desktop/src/preload-mandatory-overlay.ts', () => ({ in afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); desktopIpc.invoke.mockReset(); desktopIpc.on.mockReset() }) -const HOLES = ['conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow'] as const +const HOLES = [ + 'conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow', 'workspace.picker.directoryFlow', +] as const async function bench(allows: (action: string) => boolean = () => true) { const ctx = new Context() @@ -69,7 +71,7 @@ describe('directory-picker-native client half', () => { await b.ctx.fiber.dispose() }) - it('fills both directory-flow holes for declarations before or after apply, and leaves with its fiber', async () => { + it('fills all three directory-flow holes for declarations before or after apply, and leaves with its fiber', async () => { const before = await bench() before.declare() const fiber = before.ctx.plugin({ inject: [...inject], apply }) @@ -105,15 +107,14 @@ describe('directory-picker-native client half', () => { process.on('uncaughtException', onUnhandled) try { // The rival subscribes first, so synchronous declaration notifications - // let it occupy the pair before this provider's waiting injection runs. - b.slots.inject(HOLES[0], () => b.slots.inject(HOLES[1], function* () { - yield b.slots.register({ name: HOLES[0] } as never, () => null) - yield b.slots.register({ name: HOLES[1] } as never, () => null) - })) + // let it occupy the set before this provider's waiting injection runs. + b.slots.inject(HOLES[0], () => b.slots.inject(HOLES[1], () => b.slots.inject(HOLES[2], function* () { + for (const hole of HOLES) yield b.slots.register({ name: hole } as never, () => null) + }))) await b.ctx.plugin({ inject: [...inject], apply }).await() b.declare() await new Promise(resolve => setTimeout(resolve, 20)) - // The rival keeps both holes; this provider rolled back wholesale and + // The rival keeps every hole; this provider rolled back wholesale and // surfaced the conflict on the fail-loud channel — no partial mix. for (const hole of HOLES) expect(b.slots.entries(hole)).toHaveLength(1) expect(rejections.map(String).join('\n')).toContain('already has a registration') @@ -136,6 +137,27 @@ describe('directory-picker-native client half', () => { } }) + it('rolls back the earlier registrations when the Factory hole is already occupied', async () => { + const b = await bench() + b.declare() + // Foreign occupant in the LAST registered hole: the hero and sidebar + // registrations already landed when the third one throws. + b.slots.register({ name: HOLES[2] } as never, () => null) + const rejections: unknown[] = [] + const onUnhandled = (reason: unknown): void => { rejections.push(reason) } + process.on('unhandledRejection', onUnhandled) + try { + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await expect(fiber.await()).rejects.toThrow(/already has a registration/) + expect(b.slots.entries(HOLES[0])).toHaveLength(0) + expect(b.slots.entries(HOLES[1])).toHaveLength(0) + expect(b.slots.entries(HOLES[2])).toHaveLength(1) + } finally { + await new Promise(resolve => setTimeout(resolve, 0)) + process.off('unhandledRejection', onUnhandled) + } + }) + it('rolls back the outer injection when the second hole is already occupied', async () => { const b = await bench() b.declare() diff --git a/packages/client/ui-directory-picker-native/tsconfig.json b/packages/client/ui-directory-picker-native/tsconfig.json index c57a21a081..5c183fdfb0 100644 --- a/packages/client/ui-directory-picker-native/tsconfig.json +++ b/packages/client/ui-directory-picker-native/tsconfig.json @@ -18,7 +18,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" } ] } 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/package.json b/packages/client/ui-dockkit/package.json index c96df661ab..0748e9a937 100644 --- a/packages/client/ui-dockkit/package.json +++ b/packages/client/ui-dockkit/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-dockkit", "description": "Docking layout kit: split-tree engine with invertible operations, and the React components that render and drive it (zero cordis)", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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-layout/package.json b/packages/client/ui-layout/package.json index d00ca63a52..4e65d01264 100644 --- a/packages/client/ui-layout/package.json +++ b/packages/client/ui-layout/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-layout", "description": "Shell plugin: three-column AppFrame with drag handles, ctx.layout viewing-state service (navigation + panels)", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-layout/tests/apply.client.spec.ts b/packages/client/ui-layout/tests/apply.client.spec.ts index 7ab8585886..0d98293f43 100644 --- a/packages/client/ui-layout/tests/apply.client.spec.ts +++ b/packages/client/ui-layout/tests/apply.client.spec.ts @@ -3,7 +3,7 @@ import ShortcutsService from '../../shortcuts/src/client/index.ts' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { Context, type Fiber } from '@deepseek-ai/cordis' -import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { stubConfigForm, syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { HostObservable, SlotRendererHost } from '@deepseek-ai/dsh-client-ui-slots' @@ -58,7 +58,7 @@ async function bench() { if (ctx === undefined) throw new Error('the fixture owner did not activate') const slotsFiber = ctx.plugin(SlotRegistry) ctx.provide('locale', new LocaleRuntime(ctx)) - await ctx.plugin(ShortcutsService).await() + await ctx.plugin(ShortcutsService, syncedConfig({})).await() // ui-theme's Appearance row binds a durable scope through these two. ctx.provide('remote', { $on: () => () => {} } as never) ctx.provide('configForms', { developerTools: { enabled: createSnapshotStore(true) }, get: () => stubConfigForm().scope } as never) 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/package.json b/packages/client/ui-message-feedback/package.json index 9963c064fa..82e50698b1 100644 --- a/packages/client/ui-message-feedback/package.json +++ b/packages/client/ui-message-feedback/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-message-feedback", "description": "The Web feedback surface: per-message Like/Dislike in the assistant-message action strip and the feedback dialog behind both ratings and /feedback, backed by the messageFeedback and sessionFeedback Host Remotes", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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 67ffdadf02..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 @@ -30,8 +30,8 @@ en: b4c2e8c1f7ab4de5 zh: 5dd0e14aa5f9d334 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: - en: c1d14a925c92950f - zh: f80f8169bc283c60 + en: a11207241d0606e8 + zh: 6e4f3fb27527f5b6 /deepseek-ai-dsh-client-ui-model-selection/further-exploration: en: 14acd4692e923480 zh: ff89aed852aa0da8 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 3303f8bbae..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. @@ -73,7 +73,7 @@ Menus use the shared `MenuSurface` material, including the macOS backing for bac
    Implementation internals — click to expand -The composer `ModelSelect` and `/model` option builder share [provider ordering](src/client/provider-order.ts), while both searches use `rankByName` within each provider. The command supplies optional groups and `searchMode: 'fuzzy-label'` through the [popupSelect API](../ui-commands/README.md#use-this-package); both entries use `MenuGroup` and rebuild its sticky observer when the rendered groups change. The command popup fills the composer overlay, while the button retains its compact menu. +The composer `ModelSelect` and `/model` option builder share [provider ordering](src/client/provider-order.ts), while both searches use the shared [text search](../../util/text-search/README.md) within each provider. The command supplies optional groups through the [popupSelect API](../ui-commands/README.md#use-this-package); both entries use `MenuGroup` and rebuild its sticky observer when the rendered groups change. The command popup fills the composer overlay, while the button retains its compact menu. Two entries over ONE per-session directory owned by `ModelDirectoryResolver` (`ctx.modelDirectories`): the `/model` popupSelect contribution (registered through `ctx.commandUi`) and the composer's named `conversation.input.model` seat both load the session's available directory through `session.models` and submit through `session.selectModel` via the same `ModelDirectory` instance, so a switch made in either entry is what the other shows next. Directory loads and selections share a generation counter so an older response never overwrites a newer one. The directory publishes the latest submitted selection as `pending` until it settles or a connection reset invalidates it; a connection reset drops every resident projection and repulls the Host-restored selection before display. Directories are per-session, resolved lazily, and disposed with the session scope; addressed subagent sessions expose neither entry. Every resident directory refetches directly on forwarded `llm/adapters-updated`, `llm/models-updated`, `settings/document-updated`, and credential update events. diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 1abd873ddd..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 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 @@ -73,7 +73,7 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重
    实现细节——点击展开 -composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](src/client/provider-order.ts),两个搜索框均在每个提供方内使用 `rankByName`。命令通过 [popupSelect API](../ui-commands/README.zh.md#use-this-package) 提供可选分组与 `searchMode: 'fuzzy-label'`;两个入口均使用 `MenuGroup`,并在渲染分组变化时重建其吸顶观察器。命令弹窗撑满 composer 浮层,按钮则保留紧凑菜单。 +composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](src/client/provider-order.ts),两个搜索框均在每个提供方内使用共享的[文本搜索](../../util/text-search/README.zh.md)。命令通过 [popupSelect API](../ui-commands/README.zh.md#use-this-package) 提供可选分组;两个入口均使用 `MenuGroup`,并在渲染分组变化时重建其吸顶观察器。命令弹窗撑满 composer 浮层,按钮则保留紧凑菜单。 两个入口共用一份由 `ModelDirectoryResolver`(`ctx.modelDirectories`)持有的会话级目录:`/model` popupSelect 贡献项(经 `ctx.commandUi` 注册)与 composer 的具名 `conversation.input.model` 位都经 `session.models` 加载会话的可用目录、经 `session.selectModel` 通过同一个 `ModelDirectory` 实例提交,因此任一入口所做的切换正是另一个入口接下来显示的。目录加载与选择共享一个代次计数器,旧响应不会覆盖新结果。目录把最近一次提交的选择发布为 `pending`,直到它完成或被连接重置作废;连接重置丢弃所有常驻投影,并在显示前重新拉取 Host 恢复的选择。目录按会话惰性解析,随会话作用域一并 dispose(资源释放);已寻址 subagent 会话不公开任一入口。每份常驻目录都会直接在转发的 `llm/adapters-updated`、`llm/models-updated`、`settings/document-updated` 与凭据更新事件上重拉。 diff --git a/packages/client/ui-model-selection/package.json b/packages/client/ui-model-selection/package.json index 1b5c4fcc98..84dcf1e19b 100644 --- a/packages/client/ui-model-selection/package.json +++ b/packages/client/ui-model-selection/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-model-selection", "description": "Model selection over the shared model catalog, Session projection, and session.selectModel", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -67,7 +67,8 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", "clsx": "^2.1.1", - "@deepseek-ai/dsh-client-product-analytics": "workspace:*" + "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-util-text-search": "workspace:*" }, "files": [ "locale/*.json", 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-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index a1510d832b..6cd67bdcc4 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -37,11 +37,12 @@ import clsx from 'clsx' import type { ModelReasoningEffort, ModelSelection } from '@deepseek-ai/dsh-api-remotes/client' import { IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconCloseFillRegular, - IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, + IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { ModelLabelOwner, ModelMenuControls, ModelMenuPaneRef, ModelSelectInjected } from './slots.ts' import css from './ModelSelect.module.css' +import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' import { orderModelProviders } from './provider-order.ts' /** Which pane the dropdown shows: the root menu, one drilled-in list, or a plugin-owned detail pane. */ @@ -124,9 +125,12 @@ export function ModelSelect( } satisfies ModelSelection, }))), [groups]) const showSearch = choices.length > 4 - const filteredGroups = useMemo(() => groups.map(group => ({ - ...group, models: rankByName(group.models, showSearch ? query.trim() : ''), - })).filter(group => group.models.length > 0), [groups, query, showSearch]) + const groupIndexes = useMemo(() => groups.map(group => ({ + group, index: new TextSearchIndex(group.models, model => ({ fuzzy: [model.name, model.id], substring: [model.description] })), + })), [groups]) + const filteredGroups = useMemo(() => groupIndexes.map(({ group, index }) => ({ + ...group, models: index.search(showSearch ? query : ''), + })).filter(group => group.models.length > 0), [groupIndexes, query, showSearch]) const visibleModels = useMemo(() => filteredGroups.flatMap(group => group.models.map(model => ({ provider: group.id, model: model.id, }))), [filteredGroups]) diff --git a/packages/client/ui-model-selection/src/client/index.ts b/packages/client/ui-model-selection/src/client/index.ts index 1c37307902..a446dafbd2 100644 --- a/packages/client/ui-model-selection/src/client/index.ts +++ b/packages/client/ui-model-selection/src/client/index.ts @@ -134,7 +134,6 @@ export function apply(ctx: ClientContext): void { available: session => sessions.subagentAddress(session.sessionId) === undefined, ui: { kind: 'popupSelect', - searchMode: 'fuzzy-label', searchLabels: () => ({ placeholder: t('search.placeholder'), empty: t('empty.models'), diff --git a/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts b/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts index 275a4d2ec9..02d2d42087 100644 --- a/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts @@ -245,7 +245,6 @@ describe('ui-model-selection dual entry', () => { ]) expect(options.map(option => option.group?.label)).toEqual(['DeepSeek', 'DeepSeek', 'External Provider']) expect(options.every(option => option.detail === undefined)).toBe(true) - expect(b.popup().searchMode).toBe('fuzzy-label') expect(options[0]?.active).toBe(true) expect(options[1]?.active).toBeUndefined() expect(b.popup().searchLabels?.()).toEqual(locale === 'zh' diff --git a/packages/client/ui-model-selection/tsconfig.json b/packages/client/ui-model-selection/tsconfig.json index 862648d622..453d472231 100644 --- a/packages/client/ui-model-selection/tsconfig.json +++ b/packages/client/ui-model-selection/tsconfig.json @@ -11,6 +11,9 @@ { "path": "../../core/agent" }, + { + "path": "../../util/text-search" + }, { "path": "../../api/remotes/tsconfig.client.json" }, 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/package.json b/packages/client/ui-open-in-app/package.json index 40974b3f24..9d7f228a14 100644 --- a/packages/client/ui-open-in-app/package.json +++ b/packages/client/ui-open-in-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-open-in-app", "description": "Session application submenus and native opening controls for directories and previewed files", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index aa69108391..7b8ec935dd 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -11,6 +11,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppController } from './controller.ts' +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import type { OpenInAppPathController } from './open-path.ts' import type { OpenInAppKey } from './locales.ts' @@ -89,7 +90,7 @@ export function registerContextMenus( id: 'open-in-app.directory', target: 'directory', order: 100, resolve: async ({ sessionId, path }, signal) => { await paths.load() - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) const absolutePath = resolveWorkspacePath(cwd, path) signal.throwIfAborted() return [ @@ -114,7 +115,7 @@ export function registerContextMenus( : apps === undefined ? () => open(absolutePath, 'open') : undefined // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. const openIn = (destination: 'sidebar' | 'float') => () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { destination, ...(line === undefined ? {} : { params: { line } }), }) @@ -129,7 +130,7 @@ export function registerContextMenus( disabled: openApplication === undefined, ...openApplication === undefined ? {} : { run: openApplication } }, { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), run: async () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) ctx.contextMenus.notify(t('menu.copied'), true) } }, 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/index.ts b/packages/client/ui-open-in-app/src/client/index.ts index 84bdc9168e..c857f48779 100644 --- a/packages/client/ui-open-in-app/src/client/index.ts +++ b/packages/client/ui-open-in-app/src/client/index.ts @@ -18,6 +18,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-files/client' import type {} from '@deepseek-ai/dsh-api-gateway/client' import type {} from '@deepseek-ai/dsh-api-remotes/client' +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type {} from '@deepseek-ai/dsh-api-session-controller/remote' import { OPEN_IN_APP_ICON_PREFIX_ROUTE } from '@deepseek-ai/dsh-host-open-in-app/shared' import { OpenInAppController } from './controller.ts' @@ -76,10 +77,11 @@ export function apply(ctx: ClientContext): void { }, OpenInAppToast)) const target = () => { if (ctx.layout.panelInfo.getSnapshot().activePanelId !== null) return undefined - const session = Object.values(ctx.sessions.list.getSnapshot().byId) - .find(row => (row.retainedBy.mainView ?? 0) > 0) + const list = ctx.sessions.list.getSnapshot() + const session = Object.values(list.byId).find(row => (row.retainedBy.mainView ?? 0) > 0) + const root = session === undefined ? undefined : selectSessionDirectory(list, session.id) const appId = controller.currentApp() - return session?.cwd && appId !== undefined ? { appId, path: session.cwd } : undefined + return root && appId !== undefined ? { appId, path: root } : undefined } ctx.effect(() => ctx.shortcuts.register({ id: 'workspace.openLocal' as ShortcutCommandId, label: () => t('open.tooltip'), aliases: ['open workspace locally', 'open in app'], 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-open-in-app/src/client/session-open-with.ts b/packages/client/ui-open-in-app/src/client/session-open-with.ts index 7119958e9e..854ce2a523 100644 --- a/packages/client/ui-open-in-app/src/client/session-open-with.ts +++ b/packages/client/ui-open-in-app/src/client/session-open-with.ts @@ -2,6 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ContextMenuTargetMap, MenuAction } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { OPEN_IN_APP_ICON_PREFIX_ROUTE } from '@deepseek-ai/dsh-host-open-in-app/shared' import { APP_LABEL_KEY } from './applications.ts' import type { OpenInAppController } from './controller.ts' @@ -21,7 +22,8 @@ export function registerSessionOpenWith( report: OpenInAppToastSource['report'], ): void { const resolve = ({ sessionId }: ContextMenuTargetMap['sessionHeader']): readonly MenuAction[] => { - const directory = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + // The Session menu opens the checkout the Session works in, not the directory it was created in. + const directory = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) const applications = (controller.apps.getSnapshot() ?? []).flatMap((id) => { const key = APP_LABEL_KEY[id] return key === undefined ? [] : [{ id, name: t(key) }] diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index dabe99a530..a0adda272b 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -47,7 +47,7 @@ async function boot() { .mockResolvedValue({ status: 'saved', path: '/downloads/file.svg' }) const copyImage = vi.fn<(source: FileActionSource) => Promise>().mockResolvedValue() const fileActions = { save, copyImage, canSaveAs: true } - const sessions = createSnapshotStore({ byId: { [sessionId]: { cwd: '/workspace' } } }) + const sessions = createSnapshotStore({ byId: { [sessionId]: { cwd: '/workspace' } }, projectionsBySession: {} }) const sidebar = { openResourceIn: vi.fn(), openTabIn: vi.fn() } const browserTab = vi.fn(() => ({})) const directoryFetch = vi.fn(async () => new Response(JSON.stringify({ apps: ['vscode', 'finder'] }))) @@ -406,10 +406,10 @@ it('offers only folder reveal and path copy, retaining the captured directory', const menu = await h.resolve(target) expect(menu.source.getSnapshot().map(item => item.id)).toEqual(['open-in-app.directory/reveal', 'open-in-app.directory/copyPath']) expect(h.remote.workspaceFiles.stat).not.toHaveBeenCalled() - h.sessions.set({ byId: { [sessionId]: { cwd: '/changed' } } }) + h.sessions.set({ byId: { [sessionId]: { cwd: '/changed' } }, projectionsBySession: {} }) menu.select('open-in-app.directory/reveal') await vi.waitFor(() => { expect(h.remote.session.openWorkspacePath).toHaveBeenCalledWith({ path: '/workspace/src', action: 'reveal' }) }) - h.sessions.set({ byId: { [sessionId]: { cwd: '/workspace' } } }) + h.sessions.set({ byId: { [sessionId]: { cwd: '/workspace' } }, projectionsBySession: {} }) await h.choose(target, 'open-in-app.directory/copyPath') expect(h.writeText).toHaveBeenLastCalledWith('/workspace/src') h.paths.desktop.set(false) diff --git a/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts index 1f2a1a2704..0bd58224cd 100644 --- a/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts @@ -35,7 +35,7 @@ it('offers image actions on file targets, copies absolute paths, and keeps save } } ctx.provide('remote', remote as never) ctx.provide('contextMenus', { register: registry.register.bind(registry), notify } as never) - ctx.provide('sessions', { list: createSnapshotStore({ byId: { [id]: { cwd: '/workspace' } } }) } as never) + ctx.provide('sessions', { list: createSnapshotStore({ byId: { [id]: { cwd: '/workspace' } }, projectionsBySession: {} }) } as never) ctx.provide('fileActions', { save, copyImage: copy, canSaveAs: true } as never) const paths = new OpenInAppPathController(remote) const directories = new OpenInAppController() diff --git a/packages/client/ui-open-in-app/tsconfig.json b/packages/client/ui-open-in-app/tsconfig.json index 9e6a381554..cd08a5b44c 100644 --- a/packages/client/ui-open-in-app/tsconfig.json +++ b/packages/client/ui-open-in-app/tsconfig.json @@ -78,7 +78,7 @@ "path": "../ui-sidebar-browser/tsconfig.client.json" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" } ] } 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/package.json b/packages/client/ui-permission-presets/package.json index 7a0cc0b15a..43647850f1 100644 --- a/packages/client/ui-permission-presets/package.json +++ b/packages/client/ui-permission-presets/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-permission-presets", "description": "Permission surfaces: a new-session default in General settings and a current-session /permission popup over the permissions projection", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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-plan/package.json b/packages/client/ui-plan/package.json index 0c94f46c61..4c225e9ad4 100644 --- a/packages/client/ui-plan/package.json +++ b/packages/client/ui-plan/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plan", "description": "Plan mode controls, persistent transcript plan cards, and sidebar Markdown previews", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index af4f1664fd..f196cffcd5 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -9,14 +9,14 @@ en: 719d90bd71d7b957 zh: 492767e7ea9f88f8 /deepseek-ai-dsh-client-ui-plugin-manager/summary: - en: 0dc67850ca5358de - zh: 4ff1bb5bdc184e3e + en: 3c168fb38c18d523 + zh: 13c37617819af3fe /deepseek-ai-dsh-client-ui-plugin-manager/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package: - en: c38847d0d4d5a7b6 - zh: b83f29416199098a + en: ee6b2fa96adc6fdb + zh: ef9a0371db1b78a7 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/installing-a-bundle: en: 1fc6c5c2a54d8db4 zh: 9e53f5164e2b7161 @@ -24,14 +24,14 @@ en: 2a44a378364912db zh: 8c514ce17469747f /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-a-bundle: - en: 188ebf6f1590bad1 - zh: e6d41e8586190fa0 + en: 76b0e8af85db92f7 + zh: 3bb566e8f3c6c80b /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-one-row-of-a-bundle: - en: d3627d4dba5e6cc2 - zh: e0d0eada4c20331f + en: 2c338faf806bd469 + zh: fe947a1b27382e5d /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/configuration-pages: - en: e9da90f03691101b - zh: 902cda935a4ce3c8 + en: 501cc3aaee34ea6c + zh: 36599c3a716fb4f2 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/detail-page-extension-points: en: 16dbfb0ab558c951 zh: adf098c0751a7144 @@ -48,8 +48,8 @@ en: ef7ab41b4119c7b9 zh: 3166661bf84415e5 /deepseek-ai-dsh-client-ui-plugin-manager/understand-the-implementation/configuration-slots: - en: 45e324f5663be635 - zh: 674ddf55c1581569 + en: a8efaca9e2f9616b + zh: cb42a9279f723bc2 /deepseek-ai-dsh-client-ui-plugin-manager/further-exploration: en: f9a42dfed0360d6a zh: 455a70bcb6c69624 diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index 155ef55105..0b4fe9f29f 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -11,7 +11,7 @@ Desktop product events use the optional [product analytics service](../product-a ## Summary -Use the **Plugins** entry in the Web sidebar to manage the profile's installed bundles and the official bundles the installation ships switched off. Switch bundles and their rows on and off, install a bundle after the Host has read what the spec names, watch pnpm's output, stop a run, and enable what it added. Uninstalling asks for confirmation. A plugin that registers a configuration page is edited here, on its own page; Settings keeps the read-only inventory. +Use the **Plugins** entry in the Web sidebar to manage the profile's installed bundles and the official bundles the installation ships switched off. Switch bundles and their rows on and off, install a bundle after the Host has read what the spec names, watch pnpm's output, stop a run, and enable what it added. Uninstalling asks for confirmation. A plugin that registers a configuration page is edited here, on its own page; **Settings → Plugins** opens this page. ## Table of Contents @@ -31,7 +31,9 @@ Below 768px, the page uses 20px horizontal insets to align with the conversation [Ralph loops](../../experimental/ralph-bundle/README.md) and [Session search](../../experimental/session-search/README.md) remain bundled but are hidden from both plugin lists unless the profile enables or separately installs them. Existing selections remain manageable; switching off an installation-carried copy hides it again. Enter either exact package name in **Add plugin**, then choose **Enable now** to use the shipped copy without downloading it again. Sidebar session search is independent. LiveShare declares the same default-hidden intent in its bundle manifest (`dsh.bundle.listedByDefault: false`), so it stays out of both lists, including **More**, until a declared row runs or it is enabled. The page's manifest rule is generic: a bundle whose manifest does not declare `listedByDefault: false` is listed; one that does is listed only when the profile enables it, the installation carries it selected, or one of its declared rows runs; a hidden bundle is not opened by its ID either. -Select **Plugins** in the sidebar. The information button uses an 11px caption-colored icon in a 20px square hover area, with a 4px gap after the subtitle. It explains that this page configures official plugins and installs or manages other plugins, while **Settings → Built-in plugins** shows the built-in inventory and runtime status. Hover or focus shows the shared tooltip; clicking keeps it open until another click, Escape, Tab, or an outside click. The page reads the inventory and the bundles through `api-remotes` when first opened; a Host without a managed profile shows the page as unavailable. **Built-in plugin settings** lists official configuration pages by their configured order: Subagent, web search and fetch, agent loop, then shell. **Experimental plugins** shows the primary optional bundles, with **More** beside its heading opening a separate page of the same title. That page lists the official bundles eligible for display, including those on the main list, with Codex and Claude Code subagents last. Its back button returns to the main list, where **Installed plugins** remains below Experimental plugins. Bundle details return to the list they were opened from. Catalog entries keep their position after installation or removal. **Installed plugins** lists other profile bundles. Installation-carried optional bundles have no uninstall action. Experimental packages retain the **Experimental** marker on both lists. Switching on a bundle that page holds back adds it to the main list in the position that page shows it, and switching it off leaves it on that page alone unless its manifest hides unselected bundles; other bundles keep their place on both. A dependency without a bundle patch is not a plugin and is not listed unless the profile selects it, in which case it carries a problem tag. Global configuration remains in the Settings **Built-in plugins** section. +Select **Plugins** in the sidebar. The information button uses an 11px caption-colored icon in a 20px square hover area, with a 4px gap after the subtitle. It explains that this page configures official plugins, and installs, manages, and configures other plugins. Hover or focus shows the shared tooltip; clicking keeps it open until another click, Escape, Tab, or an outside click. The page reads the inventory and the bundles through `api-remotes` when first opened; a Host without a managed profile shows the page as unavailable. **Built-in plugin settings** lists official configuration pages by their configured order: Subagent, web search and fetch, agent loop, then shell. **Experimental plugins** shows the primary optional bundles, with **More** beside its heading opening a separate page of the same title. That page lists the official bundles eligible for display, including those on the main list, with Codex and Claude Code subagents last. Its back button returns to the main list, where **Installed plugins** remains below Experimental plugins. Bundle details return to the list they were opened from. Catalog entries keep their position after installation or removal. **Installed plugins** lists other profile bundles. Installation-carried optional bundles have no uninstall action. Experimental packages retain the **Experimental** marker on both lists. Switching on a bundle that page holds back adds it to the main list in the position that page shows it, and switching it off leaves it on that page alone unless its manifest hides unselected bundles; other bundles keep their place on both. A dependency without a bundle patch is not a plugin and is not listed unless the profile selects it, in which case it carries a problem tag. + +Every view of the page, whether or not the bundle list is available, shows this browser page's client plugin synchronization state at the top of the page body, below any header; the state comes from `ctx.modules.entries.state`. While synchronization runs, a status line reads **Syncing plugins on this page…**. When entries fail, a notice (`data-client-sync-failure`) says that some plugins could not sync on this page and that Host enablement is unchanged, lists each failure as `id: message`, and offers **Retry this page**, which calls `ctx.modules.entries.retry()` and is disabled while synchronization runs. As available header width decreases, Refresh and Add plugin first become icon-only controls with accessible names and tooltips; the tabs then shrink from their usual minimum width to fit their labels, and the action group wraps only when necessary. The information button follows the subtitle text. The main page header and list share one scroll container. Header controls move with the scroll position until they reach their compact positions; scrolling back follows the same coordinates. The header wrapper retains its resting flow height to preserve the list's scroll range, while the draggable head's box matches its painted height so native drag geometry cannot extend into the list. A barely scrolling list can stop before the header is fully compact. The More list's back-and-title row stays fixed, and detail pages scroll their head row with the content. The Installed/Discover tabs use the compact 34px control with a 2px inset around the selection indicator. The subtitle scrolls out of view; with tabs present, the title also scrolls out, and the tabs settle beside Refresh and Add plugin where space permits. On narrow pages, the tabs and icon actions share a row beneath the heading where they fit; otherwise the tabs stay above the actions. Their relative order stays the same throughout scrolling. The resting and compact layouts retain their 28px and 16px page-top insets respectively, with 16px below the compact controls. macOS adds the frame's titlebar clearance while resting; its compact bar keeps 16px above and below with the sidebar expanded, and with the sidebar collapsed it also clears the frame's top strip so the controls stay below the native window controls. Only on macOS, when the sidebar is collapsed, the compact controls keep 8px rather than 16px above them in addition to the unchanged frame clearance, at every width. The resting layout and compact bottom spacing stay unchanged. Windows relies on the frame's caption offset without adding it again. The divider spans the page at the bottom of the compact header; the list's initial top spacing scrolls with its content. Hover styling applies only where the pointer can hover, so a tap leaves no card, row, or menu option in its hover state; cards and icon actions answer a touch-down with the pressed fill instead. The install, registry, and filter fields take a 16px face under a coarse pointer, which keeps iOS Safari from zooming a focused field. @@ -78,12 +80,13 @@ After the checks, the list toolbar says how many plugins can be updated, that al ### Switching a bundle -A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. A selected bundle whose layer the Host skipped, reported as an error with none of its rows carrying a live entry, keeps its switch on and carries a not-running tag instead, and its card states the reason without the requirement list. A bundle's page omits the component list when the Host reports an error and no rows, since the Host may not have read its patch. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes built-in profile bundles and the persistent-terminal bundle from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete; the Settings Plugins section's Plugin list tab inspects their plugins. +A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. A selected bundle whose layer the Host skipped, reported as an error with none of its rows carrying a live entry, keeps its switch on and carries a not-running tag instead, and its card states the reason without the requirement list. A bundle's page omits the component list when the Host reports an error and no rows, since the Host may not have read its patch. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes bundles in [`HIDDEN_BUNDLES`](../../util/official-bundles/README.md#plugin-manager-lists) from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete. ### Switching one row of a bundle -A row's switch on the bundle's page calls `pluginManager.setPluginEnabled`, which records the row's enablement in the profile's `cordis.patch.yml` under the [toggle rules](../../boot/plugin-manager/README.md#use-this-package). The tree recomposes at once on a profile with HMR, so the row's host half unmounts or mounts while the rest of the bundle keeps running, and the page follows the client module graph without reloading. Rows use the shared status marker for their Host fiber phase: pending and disabled are idle, loading and unloading are ongoing, active is done, and failed is error. The switch appears only on a bundle that is on; a row without a live entry, or one the Host will not address through the profile patch, is locked with the Host's reason. A list longer than ten rows gets a filter over localized titles, descriptions, row ids, and module names. +A row's switch on the bundle's page calls `pluginManager.setPluginEnabled`, which records the row's enablement in the profile's `cordis.patch.yml` under the [toggle rules](../../boot/plugin-manager/README.md#use-this-package). The tree recomposes at once on a profile with HMR, so the row's host half unmounts or mounts while the rest of the bundle keeps running, and the page follows the client module graph without reloading. Rows use the shared status marker for their Host fiber phase: pending and disabled are idle, loading and unloading are ongoing, active is done, and failed is error. The switch appears only on a bundle that is on; a row without a live entry, or one the Host will not address through the profile patch, is locked with the Host's reason. A list longer than ten rows gets a filter through the shared [text search](../../util/text-search/README.md): row ids, module names, and every declared language of titles match fuzzily, and every language of descriptions matches as a substring; rows display in the current language. + ### Configuration pages A plugin that carries its own configuration renders it on this page rather than in Settings, through three slots the page declares: `plugins.item` (list) for an official plugin, listed in Built-in plugin settings by its `label`; `plugins.bundle.config` (keyed by the bundle's package name) for a bundle's own configuration, shown on the bundle's page between its description and its rows; and `plugins.row.config` (keyed by `#`) for one row's configuration, which gives that row a **Configure** control opening the row's page. The page renders `view: 'page'` for forms with their own save controls. Official plugin cards also render `view: 'summary'` under the title; a row's detail page uses that view only when its package description is absent. Only a save writes: the page draws the title, icon, and crumb, and the entry's form drops its staged edits when the page is left. The four host-plane pages the installation ships — the shell executor, the agent loop, Subagent, and the DeepSeek search provider — come from one companion package each, [ui-settings-shell](../ui-settings-shell/README.md), [ui-settings-agent-loop](../ui-settings-agent-loop/README.md), [ui-settings-subagent](../ui-settings-subagent/README.md), and [ui-settings-web-search](../ui-settings-web-search/README.md), registered while the Host serves their namespaces. A bundle's browser half registers the same way: @@ -98,6 +101,8 @@ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({ The bundle's patch must declare the row under that id, and the registration exists while the bundle is on, so a bundle that is off shows no configure control. +A plugin's own settings page is a `settings.section` entry, whose type lives in [ui-settings](../ui-settings/README.md#filling-the-settings-slots); Settings lists every entry, and this page also renders an entry, through the same `settings.section.view` Component Factory, where a listed bundle claims it. The listed bundle row whose module name equals the package that registered the entry claims it when that row has no `plugins.row.config` entry: that row gets a **Configure** control, and the row's page renders the entry with a `close` prop that returns to the bundle's page. When the registering package is a listed bundle's own package name, no listed row has that module, and the bundle has no `plugins.bundle.config` entry, the bundle's page renders the entry with a `close` that returns to the view the bundle's page was opened from. An entry that no listed row or bundle claims, or whose registering package is unknown, appears only in Settings. Settings' **Plugins** entry, a `settings.section` registration with id `plugins` and order 15, closes Settings and opens this page's main list. + ### Detail page extension points A plugin with something to say about a bundle, a row, or an official plugin it does not own contributes to that object's page through three list slots the page declares: `plugins.detail.actions` for a control at the head of the page, before the page's own switch and uninstall; `plugins.detail.badge` for a tag beside the title, after the version, experimental, and problem or not-running tags; and `plugins.detail.section` for a section under the page's own content — after the source on a bundle's page, after the configuration on a row's or an official plugin's page. Every entry is rendered with the page's `subject`: `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }`, where `pkg` and `row` carry the name, version, installed and enabled facts, and the row list a contribution decides on. An entry renders null for a subject it has nothing for and draws its own section chrome; the page orders entries by `order`. @@ -148,7 +153,7 @@ While the Plugins page has access, other Client plugins can read `pluginNavigati Custom item pages use the Host entry id as their registration id; row pages use the bundle package and row id. The page owner supplies `form.state` and `form.mutate(operations, expectedRevision)` when the entry exposes editable Config fields. A custom page owns its draft and validation display, and may reuse `ConfigField` from ui-primitives. Bundle-wide pages can contain several entries and have no single form. -The page's `main` registration declares `plugins.item`, `plugins.bundle.config`, and `plugins.row.config` as its children, so the slots exist while the page does and a registrant's `ctx.slots.inject` waits for them. `configLedgerSource` projects the three ledgers into one observable — the official items in ledger order with their labels resolved in the active locale, and the bundle and row keys — cached until a ledger or the locale moves; the page binds it as `useConfigLedger` beside the store and never names a configurable plugin itself. The registration-owned navigation store selects the main list, the full experimental plugin list, a bundle, an official plugin, or a bundle row; switching away from the Plugins panel resets it to the list, while React remounts preserve the selected target. A fresh registration starts on the main list. Installation highlighting scrolls to a card only when it is on the current page; it does not change the selected page. Other Client plugins read `pluginNavigation` optionally, through `ctx.get` or `ctx.inject`, and call its `openBundle(packageName)` to open bundle details without changing the current Session; listing it in a plugin's `inject` keeps that plugin pending on a page without access. The target survives the initial inventory load; an absent bundle displays the list. A registration lives with the browser half that made it. `dsh-client-modules` attaches a package's browser half to the Loader row whose specifier is the bare package name, so every page a bundle registers, for itself or for any of its rows, goes away when that row is switched off; a sub-plugin whose page must outlive the other rows ships as its own package. Cards and detail pages show the Experimental marker only for packages in `EXPERIMENTAL_BUNDLES` in [`dsh-official-bundles`](../../util/official-bundles/README.md#plugin-manager-lists); package-name prefixes do not select the marker. +The page's `main` registration declares `plugins.item`, `plugins.bundle.config`, and `plugins.row.config` as its children, so the slots exist while the page does and a registrant's `ctx.slots.inject` waits for them. `configLedgerSource` projects the four ledgers into one observable — the official items and the `settings.section` entries in ledger order with their labels resolved in the active locale, each section with its registering module when known, and the bundle and row keys — cached until a ledger or the locale moves; the page binds it as `useConfigLedger` beside the store and never names a configurable plugin itself. The registration-owned navigation store selects the main list, the full experimental plugin list, a bundle, an official plugin, or a bundle row; switching away from the Plugins panel resets it to the list, while React remounts preserve the selected target. A fresh registration starts on the main list. Installation highlighting scrolls to a card only when it is on the current page; it does not change the selected page. Other Client plugins read `pluginNavigation` optionally, through `ctx.get` or `ctx.inject`, and call its `openBundle(packageName)` to open bundle details without changing the current Session; listing it in a plugin's `inject` keeps that plugin pending on a page without access. The target survives the initial inventory load; an absent bundle displays the list. A registration lives with the browser half that made it. `dsh-client-modules` attaches a package's browser half to the Loader row whose specifier is the bare package name, so every page a bundle registers, for itself or for any of its rows, goes away when that row is switched off; a sub-plugin whose page must outlive the other rows ships as its own package. Cards and detail pages show the Experimental marker only for packages in `EXPERIMENTAL_BUNDLES` in [`dsh-official-bundles`](../../util/official-bundles/README.md#plugin-manager-lists); package-name prefixes do not select the marker. `plugins.bundle.config` supplies bundle detail configuration, keyed by npm package name. Client plugins can subscribe to the read-only `ctx.pluginChanges.bundle(packageName)` source to pause their queries while a bundle or one of its rows is being changed. Notifications precede the management request and continue when the page closes; subscribers release their observation on disposal. `plugins.bundle.activation` offers bundle-owned guidance after explicit enablement from either the list or detail page, with callbacks to dismiss it or open the bundle details. It does not appear merely because an enabled bundle was listed. diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index 586d8adadf..ca9e0b4fb3 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" ## 概述 -使用 Web 侧栏的**插件**入口管理 profile 已安装的组合包,以及安装随附、默认关闭的官方组合包。可以启停组合包及其行、在 Host 读出 spec 指向什么之后安装组合包、查看 pnpm 输出、停止一次运行,并启用它新增的包。卸载会要求确认。注册了配置页的插件在这里、在它自己的页面上编辑;设置里只保留只读的插件列表。 +使用 Web 侧栏的**插件**入口管理 profile 已安装的组合包,以及安装随附、默认关闭的官方组合包。可以启停组合包及其行、在 Host 读出 spec 指向什么之后安装组合包、查看 pnpm 输出、停止一次运行,并启用它新增的包。卸载会要求确认。注册了配置页的插件在这里、在它自己的页面上编辑;「设置 → 插件管理」打开本页。 ## 目录 @@ -31,7 +31,9 @@ kind: "package-reference" [Ralph 循环](../../experimental/ralph-bundle/README.zh.md)和[会话搜索](../../experimental/session-search/README.zh.md)仍随包提供,但默认不在两个插件列表中展示,只有 profile 启用或另行安装后才显示。已有的启用状态仍可管理;关闭随安装提供的版本后,它会再次隐藏。在**添加插件**中输入准确包名,再选择**立即启用**,即可使用随包提供的版本,无需再次下载。侧栏会话搜索独立于此功能。LiveShare 在其 bundle manifest 中声明相同的默认隐藏意图(`dsh.bundle.listedByDefault: false`),因此在自身声明的行开始运行或被启用前,它不会出现在两个列表(含**更多**页)中。页面的 manifest 规则是通用的:未声明 `listedByDefault: false` 的组合包会列出;声明了的,只有在 profile 启用、安装随附版本被选中,或它声明的某一行开始运行时才列出;隐藏的组合包也不能通过 ID 打开详情。 -在侧栏选择**插件**。信息按钮使用 11px 的 caption 色图标和 20px 方形悬停区域,与副标题间隔 4px。它说明当前页用于配置官方插件、安装和管理其他插件,**设置 → 内置插件**则展示内置插件列表及运行状态。悬停或聚焦显示共享 tooltip;点击后保持展开,直至再次点击、Escape、Tab 或外部点击。页面首次打开时通过 `api-remotes` 读取清单与组合包;没有受管 profile 的 Host 上页面显示为不可用。**内置插件配置**按配置的顺序列出官方配置页:子智能体、网页搜索与获取、Agent 循环、终端。**实验性插件**展示主要的可选组合包,标题旁的**更多**打开同名的独立页面。该页列出符合展示条件的官方组合包,也包含主列表已有的条目,Codex 和 Claude Code 子智能体排在最后。返回按钮回到主列表,**已安装插件**保持在实验性插件下方。组合包详情返回打开它的列表。目录条目在安装或移除后保持原位置。**已安装插件**列出其他 profile 组合包。安装随附的可选组合包没有卸载操作。实验性包在两个列表中均保留**实验性**标签。开启仅在该页列出的组合包会按该页中的位置把它加入主列表,关闭后它只留在该页,但 manifest 声明默认隐藏的组合包会从该页消失;其他组合包在两个列表中均保持原位。没有组合包 patch 的依赖不是插件,除非 profile 选中了它才会带异常标签列出。全局配置仍在设置的**内置插件**分区中编辑。 +在侧栏选择**插件**。信息按钮使用 11px 的 caption 色图标和 20px 方形悬停区域,与副标题间隔 4px。它说明当前页用于配置官方插件,以及安装、管理和配置其他插件。悬停或聚焦显示共享 tooltip;点击后保持展开,直至再次点击、Escape、Tab 或外部点击。页面首次打开时通过 `api-remotes` 读取清单与组合包;没有受管 profile 的 Host 上页面显示为不可用。**内置插件配置**按配置的顺序列出官方配置页:子智能体、网页搜索与获取、Agent 循环、终端。**实验性插件**展示主要的可选组合包,标题旁的**更多**打开同名的独立页面。该页列出符合展示条件的官方组合包,也包含主列表已有的条目,Codex 和 Claude Code 子智能体排在最后。返回按钮回到主列表,**已安装插件**保持在实验性插件下方。组合包详情返回打开它的列表。目录条目在安装或移除后保持原位置。**已安装插件**列出其他 profile 组合包。安装随附的可选组合包没有卸载操作。实验性包在两个列表中均保留**实验性**标签。开启仅在该页列出的组合包会按该页中的位置把它加入主列表,关闭后它只留在该页,但 manifest 声明默认隐藏的组合包会从该页消失;其他组合包在两个列表中均保持原位。没有组合包 patch 的依赖不是插件,除非 profile 选中了它才会带异常标签列出。 + +页面的每个视图(无论组合包列表是否可用)都在页面正文顶部(任何页头之下)显示本浏览器页面的客户端插件同步状态,该状态来自 `ctx.modules.entries.state`。同步进行时,状态行显示**正在同步本页面的插件…**。有条目失败时,提示(`data-client-sync-failure`)说明本页面的插件未能完成同步、服务端的启用状态保持不变,把每个失败列为 `id: message`,并提供**重试本页面同步**;该按钮调用 `ctx.modules.entries.retry()`,同步进行时禁用。 页头可用宽度缩小时,“刷新”和“添加插件”先变为保留可访问名称与 tooltip 的图标按钮;标签再从常规最小宽度收紧为文案所需宽度,仍不足时操作组才换行。信息按钮紧随副标题文字。主页面的页头和列表共用一个滚动容器。页头控件随滚动位置移动,到达紧凑态位置后停住;反向滚动沿同样的坐标返回。页头外层容器保留静止态的文档流高度,以保持列表滚动范围;可拖动页头的矩形与其绘制高度一致,使原生拖动区域不会延伸到列表中。只能滚动少量距离的列表可能在页头完全收拢前到达底部。“更多”列表的返回与标题行固定,详情页的页头随内容滚动。“已安装/发现”标签使用总高 34px 的紧凑控件,选中指示块与外框之间留 2px。副标题随滚动离开视口;有标签时标题也随之滚出,标签在空间足够时停靠到“刷新”“添加插件”旁边。窄页面中,标签与图标操作优先在标题下方共用一行;放不下时,标签始终在操作组上方。滚动过程中两组控件的相对顺序保持不变。静止态与紧凑态分别保留 28px 和 16px 的页面顶部留白,紧凑态控件下方保留 16px。macOS 静止态保留框架的标题栏安全区;折叠态在侧栏展开时上下各留 16px,侧栏收起时再避让框架顶部安全区,使控件位于原生窗口控件下方。仅在 macOS 侧栏收起时,紧凑态控件在原有框架安全区之外的顶部留白统一由 16px 减为 8px,不受窗口宽度影响;静止态布局与紧凑态底部留白均不变。Windows 使用框架已有的标题栏偏移,不重复叠加。分隔线在紧凑页头底部横跨页面,列表初始的顶部留白随内容滚动。悬停样式只在可悬停的指针下生效,点按不会让卡片、行或菜单项停留在悬停态;卡片与图标操作改以按下填充回馈触摸。安装、注册表与筛选输入框在粗指针下使用 16px 字号,iOS Safari 不会因聚焦而放大页面。 @@ -78,12 +80,13 @@ Host 将网络失败或超时归因于 GitHub 地址,且提供 npmmirror 时 ### 切换一个组合包 -组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。已选中组合包的层被 Host 跳过时(Host 将其报告为错误,且该组合包没有带存活条目的行),该组合包的开关保持打开,改带未运行标签,其卡片给出原因,但不列出未满足的版本要求。Host 报告错误且没有报告任何行时,组合包页面不显示组件列表,因为 Host 可能未读取其 patch。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除内置 profile 组合包和持久终端组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据;设置中「插件」分区的「插件列表」标签页负责查看它们的插件。 +组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。已选中组合包的层被 Host 跳过时(Host 将其报告为错误,且该组合包没有带存活条目的行),该组合包的开关保持打开,改带未运行标签,其卡片给出原因,但不列出未满足的版本要求。Host 报告错误且没有报告任何行时,组合包页面不显示组件列表,因为 Host 可能未读取其 patch。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除 [`HIDDEN_BUNDLES`](../../util/official-bundles/README.zh.md#plugin-manager-lists) 中的组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据。 ### 切换组合包里的一行 -组合包页面上行的开关调用 `pluginManager.setPluginEnabled`,按[开关规则](../../boot/plugin-manager/README.zh.md#use-this-package)在 profile 的 `cordis.patch.yml` 中记录该行的启用状态。启用了 HMR 的 profile 的树随即重组,该行的宿主半区卸下或挂上,组合包其余部分照常运行,页面无需重载即跟随客户端模块图。行使用共享状态标记表示 Host fiber 阶段:pending 与 disabled 为 idle,loading 与 unloading 为 ongoing,active 为 done,failed 为 error。开关只出现在已打开的组合包上;没有存活条目的行,以及 Host 不通过 profile patch 寻址的行,带着 Host 的原因锁定。超过十行的列表带一个按本地化标题、描述、行 id 和模块名筛选的输入框。 +组合包页面上行的开关调用 `pluginManager.setPluginEnabled`,按[开关规则](../../boot/plugin-manager/README.zh.md#use-this-package)在 profile 的 `cordis.patch.yml` 中记录该行的启用状态。启用了 HMR 的 profile 的树随即重组,该行的宿主半区卸下或挂上,组合包其余部分照常运行,页面无需重载即跟随客户端模块图。行使用共享状态标记表示 Host fiber 阶段:pending 与 disabled 为 idle,loading 与 unloading 为 ongoing,active 为 done,failed 为 error。开关只出现在已打开的组合包上;没有存活条目的行,以及 Host 不通过 profile patch 寻址的行,带着 Host 的原因锁定。超过十行的列表带一个筛选框,使用共享的[文本搜索](../../util/text-search/README.zh.md):行 id、模块名和标题的所有声明语言模糊匹配,描述的所有语言按子串匹配;各行以当前语言显示。 + ### 配置页 自带配置的插件把配置渲染在本页而不是设置里,通过本页声明的三个 slot:`plugins.item`(list)用于官方插件,按其 `label` 列在内置插件配置分组里;`plugins.bundle.config`(以组合包的包名为键)用于组合包自己的配置,显示在组合包页面的描述与行之间;`plugins.row.config`(以 `<包名>#<行 id>` 为键)用于某一行的配置,这一行由此多出一个**配置**控件,打开该行自己的页面。页面用 `view: 'page'` 渲染带自己保存控件的表单。官方插件卡片还在标题下渲染 `view: 'summary'`;行详情页只在缺少包描述时使用该视图。只有保存才写入:页面负责画标题、图标与面包屑,条目的表单在离开页面时丢弃暂存的修改。安装随附的四个宿主平面配置页——shell 执行器、agent loop、子智能体、DeepSeek 搜索提供方——各来自一个伴生包:[ui-settings-shell](../ui-settings-shell/README.zh.md)、[ui-settings-agent-loop](../ui-settings-agent-loop/README.zh.md)、[ui-settings-subagent](../ui-settings-subagent/README.zh.md) 与 [ui-settings-web-search](../ui-settings-web-search/README.zh.md),在 Host 服务其命名空间期间注册。组合包的浏览器半侧用同样的方式注册: @@ -98,6 +101,8 @@ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({ 组合包的 patch 必须以该 id 声明这一行;注册只在组合包开启期间存在,因此关闭的组合包不显示配置控件。 +插件自己的设置页面是一个 `settings.section` 条目,其类型位于 [ui-settings](../ui-settings/README.zh.md#filling-the-settings-slots);设置列出全部条目,本页也在已列出的组合包认领某个条目时,经同一个 `settings.section.view` Component Factory 渲染它。模块名等于注册该条目的包、且没有 `plugins.row.config` 条目的已列出组合包行认领该条目:该行多出一个**配置**控件,行页面渲染该条目,并传入返回组合包页面的 `close` prop。注册包是某个已列出组合包自身的包名、没有已列出的行使用该模块、且该组合包没有 `plugins.bundle.config` 条目时,组合包页面渲染该条目,其 `close` 返回打开该组合包页面的视图。没有已列出的行或组合包认领、或注册包未知的条目只出现在设置中。设置中的**插件管理**条目是 id 为 `plugins`、order 为 15 的 `settings.section` 注册,选择它会关闭设置并打开本页主列表。 + ### 详情页扩展点 对某个不属于自己的组合包、行或官方插件有话要说的插件,通过本页声明的三个 list slot 向该对象的页面贡献内容:`plugins.detail.actions` 在页头放一个控件,位于页面自己的开关和卸载之前;`plugins.detail.badge` 在标题旁放一个标签,位于版本、实验性和异常或未运行标签之后;`plugins.detail.section` 在页面自身内容之下放一个区块——组合包页在来源信息之后,行页和官方插件页在配置之后。每个条目都以页面的 `subject` 渲染:`{ kind: 'bundle', pkg }`、`{ kind: 'row', pkg, row }` 或 `{ kind: 'item', id }`,其中 `pkg` 与 `row` 携带包名、版本、是否已安装、是否启用以及行列表这些供贡献者判断的事实。条目对无话可说的 subject 返回 null,自绘区块外观;页面按 `order` 排列条目。 @@ -148,7 +153,7 @@ Host 入口通过生成的 Remote 接口暴露 `pluginRegistryProbe.fastest()` 自定义条目页以 Host 条目 id 作为注册 id;行页面使用 bundle 包名和行 id。当条目提供可编辑 Config 字段时,页面宿主传入 `form.state` 和 `form.mutate(operations, expectedRevision)`。自定义页面负责草稿和校验提示,并可复用 ui-primitives 的 `ConfigField`。整个 bundle 的页面可以包含多个条目,因此没有单一表单。 -页面的 `main` 注册把 `plugins.item`、`plugins.bundle.config` 与 `plugins.row.config` 声明为子 slot,因此它们与页面同生,注册方的 `ctx.slots.inject` 会等到它们出现。`configLedgerSource` 把三份账本投影成一个可观察对象——按账本顺序排列、标签按当前语言解析的官方条目,以及组合包与行的键——在账本或语言变化前保持缓存;页面把它作为 `useConfigLedger` 绑在 store 旁边,自身从不点名任何可配置插件。注册拥有的导航 store 选择主列表、完整的实验性插件列表、某个组合包、某个官方插件或组合包的某一行;切换离开插件面板时重置为列表,React 重新挂载则保留所选目标。新的注册从主列表开始。安装后的高亮仅在当前页面有对应卡片时滚动定位,不改变所选页面。其他 Client 插件经 `ctx.get` 或 `ctx.inject` 以可选方式读取 `pluginNavigation`,调用其 `openBundle(packageName)` 即可打开组合包详情,不改变当前 Session;把它写进插件的 `inject` 会让该插件在无权限的页面上一直等待。首次读取清单期间保留导航目标;组合包不存在时显示列表。注册与做出它的浏览器半侧同生共死。`dsh-client-modules` 只把一个包的浏览器半侧挂在说明符恰为包名的那一行 Loader 行上,所以组合包为自己或任一行注册的页面,都会在那一行被关闭时一起消失;需要在其他行关闭时仍保留页面的子插件,应作为独立的包发布。 卡片和详情页仅为 [`dsh-official-bundles`](../../util/official-bundles/README.zh.md#plugin-manager-lists) 中 `EXPERIMENTAL_BUNDLES` 名单内的包显示实验性标签,包名前缀不决定标签。 +页面的 `main` 注册把 `plugins.item`、`plugins.bundle.config` 与 `plugins.row.config` 声明为子 slot,因此它们与页面同生,注册方的 `ctx.slots.inject` 会等到它们出现。`configLedgerSource` 把四份账本投影成一个可观察对象——按账本顺序排列、标签按当前语言解析的官方条目与 `settings.section` 条目(每个条目在已知时带注册它的模块),以及组合包与行的键——在账本或语言变化前保持缓存;页面把它作为 `useConfigLedger` 绑在 store 旁边,自身从不点名任何可配置插件。注册拥有的导航 store 选择主列表、完整的实验性插件列表、某个组合包、某个官方插件或组合包的某一行;切换离开插件面板时重置为列表,React 重新挂载则保留所选目标。新的注册从主列表开始。安装后的高亮仅在当前页面有对应卡片时滚动定位,不改变所选页面。其他 Client 插件经 `ctx.get` 或 `ctx.inject` 以可选方式读取 `pluginNavigation`,调用其 `openBundle(packageName)` 即可打开组合包详情,不改变当前 Session;把它写进插件的 `inject` 会让该插件在无权限的页面上一直等待。首次读取清单期间保留导航目标;组合包不存在时显示列表。注册与做出它的浏览器半侧同生共死。`dsh-client-modules` 只把一个包的浏览器半侧挂在说明符恰为包名的那一行 Loader 行上,所以组合包为自己或任一行注册的页面,都会在那一行被关闭时一起消失;需要在其他行关闭时仍保留页面的子插件,应作为独立的包发布。 卡片和详情页仅为 [`dsh-official-bundles`](../../util/official-bundles/README.zh.md#plugin-manager-lists) 中 `EXPERIMENTAL_BUNDLES` 名单内的包显示实验性标签,包名前缀不决定标签。 `plugins.bundle.config` 以 npm 包名为 key,提供 Bundle 详情配置。Client 插件可订阅只读的 `ctx.pluginChanges.bundle(packageName)`,在组合包或其组件行变更期间暂停查询。通知先于管理请求发出,页面关闭后仍会更新;订阅方在卸载时释放观察。`plugins.bundle.activation` 在用户从列表或详情页显式启用后提供 Bundle 自有引导,并传入关闭引导和打开详情的回调。仅列出已启用的 Bundle 不会触发引导。 diff --git a/packages/client/ui-plugin-manager/package.json b/packages/client/ui-plugin-manager/package.json index 5f6a0ec16d..73c728f858 100644 --- a/packages/client/ui-plugin-manager/package.json +++ b/packages/client/ui-plugin-manager/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plugin-manager", "description": "Plugin management for the dsh web client: the sidebar Plugins panel installs, enables, disables, retries, and composes installed plugin packages", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -39,6 +39,7 @@ "inject": [ "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-modules", "@deepseek-ai/dsh-client-ui-layout", "@deepseek-ai/dsh-client-ui-sidebar" ], @@ -58,6 +59,7 @@ "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-modules": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-layout": "workspace:*", @@ -74,7 +76,8 @@ "@deepseek-ai/dsh-util-crypto": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-plugin-manager": "workspace:*", - "@deepseek-ai/dsh-client-product-analytics": "workspace:*" + "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-util-text-search": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-plugin-manager/src/client/ClientSyncNotice.tsx b/packages/client/ui-plugin-manager/src/client/ClientSyncNotice.tsx new file mode 100644 index 0000000000..d654d90c9a --- /dev/null +++ b/packages/client/ui-plugin-manager/src/client/ClientSyncNotice.tsx @@ -0,0 +1,30 @@ +/** This page's client plugin synchronization: an ongoing line while it runs, and the failures with a retry. */ +import type { ReactNode } from 'react' +import { Button, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ClientEntryState } from '@deepseek-ai/dsh-client-modules/client' +import type { Translate } from './presentation.ts' +import css from './PluginManagerPage.module.css' + +/** + * Show what the page's module system reports; it is independent of the Host's bundle list. + * @param props - the latest synchronization state, the page copy, and the retry. + * @returns the status line, the failure notice, both, or nothing. + */ +export function ClientSyncNotice({ sync, t, retry }: { + readonly sync: ClientEntryState + readonly t: Translate + readonly retry: () => void +}): ReactNode { + return ( + <> + {sync.syncing ?

    {t('clientSyncing')}

    : null} + {sync.failures.length === 0 ? null : ( +
    +

    {t('clientSyncFailed')}

    +
      {sync.failures.map(failure =>
    • {failure.id}: {failure.message}
    • )}
    + +
    + )} + + ) +} diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css index f7fac78f91..4aeeb7cb4a 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css @@ -269,6 +269,13 @@ color: var(--dsw-alias-state-error-primary); } +.failure ul { + margin: 0; + padding-left: 16px; + font-size: 13px; + line-height: 20px; +} + .statusWithDot { display: inline-flex; align-items: center; diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx index 53f0b7d67b..85235c8671 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx @@ -8,7 +8,7 @@ * the page declares. */ -import { useEffect, useId, useRef, useState, type ReactNode } from 'react' +import { Fragment, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react' import { createPortal } from 'react-dom' import type { PluginInstallFailureKind, Registry } from '@deepseek-ai/dsh-api-remotes/client' import { @@ -20,11 +20,14 @@ import { SegmentedTabs, StateDot, Switch, Tag, TerminalBlock, Toast, Tooltip, useDismissOnOutsidePointer, type IconProps, type StateDotState, type TerminalBlockLabels, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type { ClientEntryState } from '@deepseek-ai/dsh-client-modules/client' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' import { EXTENSION_BUNDLES, HIDDEN_BUNDLES, MORE_BUNDLES } from '@deepseek-ai/dsh-official-bundles' +import { localizedValues, TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' import type { createNavigationStore } from './navigation-store.ts' import type { PluginHeaderLayoutFace } from './header-scroll.ts' -import { rowConfigKey, type OfficialItem } from './config-ledger.ts' +import { rowConfigKey, type OfficialItem, type SettingsSectionItem } from './config-ledger.ts' import { INSTALL_GIT_EXAMPLE, INSTALL_PATH_EXAMPLE, type PluginManagerLocaleKey } from './locales.ts' import { bundleBusy, asksMirror, githubRecoveryRegistry, isInstallPending, offeredRegistries, rowKey, updateCandidate, @@ -36,6 +39,7 @@ import type { PluginPackageRef, PluginRowRef, PluginsSubject } from './slot-cont import type { ConfigPageForm } from './slot-contract.ts' import { UpdateDialog, VersionSection } from './versions.tsx' import { BundleDetailSection } from './BundleDetailSection.tsx' +import { ClientSyncNotice } from './ClientSyncNotice.tsx' import css from './PluginManagerPage.module.css' /** Full component props assembled by the main slot renderer. */ @@ -47,12 +51,22 @@ export type PluginManagerPageProps = | 'plugins.add.actions' | 'plugins.tab' | 'plugins.detail.actions' | 'plugins.detail.badge' | 'plugins.detail.section' > + & PropsRenderFactories & InjectFace + & InjectFace & PropsStore> +/** This page's client plugin synchronization, read from the page's module system. */ +export interface ClientSyncFace { + readonly hooks: { readonly clientSync: ObservableSnapshot } + /** Retry the latest client graph without changing the Host composition. */ + readonly retryClient: () => void +} + /** The page's slot renderer, narrowed to the configuration slots. */ type RenderConfig = PluginManagerPageProps['renderSlot'] type ResolveText = PluginManagerFace['resolveText'] +type RenderFactory = PluginManagerPageProps['renderFactorySlot'] type RowPhase = NonNullable @@ -282,10 +296,12 @@ function RowsSection({ rows, t, resolveText, toggle, configure }: { readonly configure?: RowConfigure | undefined }): ReactNode { const [filter, setFilter] = useState('') - const query = filter.trim().toLowerCase() - const localized = rows.map(row => ({ row, ...rowText(row, resolveText) })) - const shown = query === '' ? localized : localized.filter(({ row, title, description }) => - [title, description, row.rowId, row.moduleName].some(value => value?.toLowerCase().includes(query))) + // Rows display one language; matching covers every language a value carries. + const rowIndex = useMemo(() => new TextSearchIndex(rows, row => ({ + fuzzy: [row.rowId, row.moduleName, ...localizedValues(row.meta?.title)], + substring: localizedValues(row.meta?.description), + })), [rows]) + const shown = rowIndex.search(filter).map(row => ({ row, ...rowText(row, resolveText) })) return (
    @@ -674,14 +690,17 @@ function ItemDetail({ item, t, onBack, renderSlot, form }: { * A row's configuration page keeps its technical identity beside local package * text and the form supplied by its configuration entry. */ -function RowDetail({ pkg, row, t, resolveText, onBack, renderSlot, form }: { +function RowDetail({ pkg, row, t, resolveText, onBack, renderSlot, renderFactory, form, sections }: { readonly pkg: PackageView readonly row: PackageRow readonly t: Translate readonly resolveText: ResolveText readonly onBack: () => void readonly renderSlot: RenderConfig + readonly renderFactory: RenderFactory readonly form: ConfigPageForm | undefined + /** The settings pages the row's module registered, shown when the row registers no configuration of its own. */ + readonly sections: readonly SettingsSectionItem[] }): ReactNode { const { title } = packageText(pkg, resolveText) const { title: rowTitle, description } = rowText(row, resolveText) @@ -709,6 +728,7 @@ function RowDetail({ pkg, row, t, resolveText, onBack, renderSlot, form }: {
    {renderSlot('plugins.row.config', { view: 'page', form }, { entryKey: key })} + {sections.map(section => {renderFactory('settings.section.view', { id: section.id, close: onBack })})} {renderSlot('plugins.detail.section', { subject })}
    @@ -724,7 +744,7 @@ function RowDetail({ pkg, row, t, resolveText, onBack, renderSlot, form }: { * and configure controls, unless the Host reports an error and no rows; and where it comes from. */ function PackageDetail({ - pkg, t, resolveText, busy, rowBusy, configured, configure, renderSlot, inMore, versions, detail, + pkg, t, resolveText, busy, rowBusy, configured, configure, sections, renderSlot, renderFactory, inMore, versions, detail, onBack, onSetEnabled, onUninstall, onUpdate, onSetRowEnabled, onEnsureVersions, onCheckVersions, onUpdateVersion, }: { readonly pkg: PackageView @@ -740,7 +760,13 @@ function PackageDetail({ /** Whether the bundle registered a configuration of its own. */ readonly configured: boolean readonly configure: RowConfigure + /** + * The settings pages the bundle's own package registered, shown when the bundle has no configuration and no listed + * row's module is that package. + */ + readonly sections: readonly SettingsSectionItem[] readonly renderSlot: RenderConfig + readonly renderFactory: RenderFactory readonly inMore: boolean readonly onBack: () => void readonly onSetEnabled: (enabled: boolean) => void @@ -823,6 +849,11 @@ function PackageDetail({
    ) : null} + {sections.map(section => ( +
    + {renderFactory('settings.section.view', { id: section.id, close: onBack })} +
    + ))} {/* A Host error with no rows can mean the Host never read the patch, so the page does not claim the bundle has no components. */} {pkg.availability === 'missing' || (pkg.error !== undefined && pkg.rows.length === 0) ? null : ( !HIDDEN_BUNDLES.has(pkg.name) && (pkg.listedByDefault !== false || pkg.enabled || pkg.installed || rowsRunning(pkg)) && (pkg.installed || pkg.official || pkg.error !== undefined)) @@ -1613,6 +1642,14 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { ? listed.find(pkg => pkg.name === view.name) : undefined const openItem = view.kind === 'item' ? ledger.items.find(item => item.id === view.id) : undefined + // A plugin's settings page also shows on the listed row whose module registered it, or else on the bundle whose + // package registered it, when that row or bundle registers no configuration of its own; Settings shows it either way. + const rowModules = new Set(listed.flatMap(pkg => pkg.rows.map(row => row.moduleName))) + const sectionsOf = (pkg: PackageView, row: PackageRow): readonly SettingsSectionItem[] => + ledger.rows.has(rowConfigKey(pkg.name, row.rowId)) ? [] : ledger.sections.filter(section => section.module === row.moduleName) + const bundleSections = (pkg: PackageView): readonly SettingsSectionItem[] => ledger.bundles.has(pkg.name) || rowModules.has(pkg.name) + ? [] + : ledger.sections.filter(section => section.module === pkg.name) const openRow = view.kind === 'row' && openPkg !== undefined ? openPkg.rows.find(row => row.rowId === view.rowId) : undefined const onInstalled = tab === INSTALLED_TAB const showsCards = !onInstalled || (openPkg === undefined && openItem === undefined) @@ -1639,7 +1676,7 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { if (row.entryId !== undefined) props.setRowEnabled(row.entryId, enabled) } const configure = (pkg: PackageView): RowConfigure => ({ - has: row => ledger.rows.has(rowConfigKey(pkg.name, row.rowId)), + has: row => ledger.rows.has(rowConfigKey(pkg.name, row.rowId)) || sectionsOf(pkg, row).length > 0, open: (row) => { setView({ kind: 'row', name: pkg.name, rowId: row.rowId, ...pkgOrigin }) }, }) const updates = updatesNote(mine, state.versions, t) @@ -1750,7 +1787,7 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode {
    ) : null} - + snapshot)} t={t} retry={props.retryClient} /> {!onInstalled ? (
    @@ -1799,6 +1836,8 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { pkg={openPkg} row={openRow} form={formFor(openRow.rowId)} + sections={sectionsOf(openPkg, openRow)} + renderFactory={props.renderFactorySlot} t={t} resolveText={resolveText} renderSlot={renderSlot} @@ -1816,6 +1855,8 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { rowBusy={row => row.entryId !== undefined && state.busy.includes(rowKey(row.entryId))} configured={ledger.bundles.has(openPkg.name)} configure={configure(openPkg)} + sections={bundleSections(openPkg)} + renderFactory={props.renderFactorySlot} renderSlot={renderSlot} inMore={backToMore} detail={( diff --git a/packages/client/ui-plugin-manager/src/client/PluginsSettingsLink.tsx b/packages/client/ui-plugin-manager/src/client/PluginsSettingsLink.tsx new file mode 100644 index 0000000000..e91c04eb74 --- /dev/null +++ b/packages/client/ui-plugin-manager/src/client/PluginsSettingsLink.tsx @@ -0,0 +1,28 @@ +/** The Settings navigation entry that leaves Settings for the Plugins page. */ +import { useEffect, type ReactNode } from 'react' +import type { InjectFace, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only: the `settings.section` declaration this entry registers into. +import type {} from '@deepseek-ai/dsh-client-ui-settings/client' + +/** What the entry receives from the plugin manager. */ +export interface PluginsSettingsLinkInjected { + /** Show the Plugins page's main list. */ + readonly openPlugins: () => void +} + +/** Full component props assembled by the settings shell. */ +export type PluginsSettingsLinkProps = PropsRuntime<'settings.section'> & InjectFace + +/** + * Selecting the entry closes Settings and opens the Plugins page; the entry has no page of its own. + * @param props - the shell's close action and the injected navigation. + * @returns nothing; the entry renders no content. + */ +export function PluginsSettingsLink({ close, openPlugins }: PluginsSettingsLinkProps): ReactNode { + // Mounting is the selection: the shell mounts a page only when its navigation entry is chosen. + useEffect(() => { + close() + openPlugins() + }, [close, openPlugins]) + return null +} diff --git a/packages/client/ui-plugin-manager/src/client/config-ledger.ts b/packages/client/ui-plugin-manager/src/client/config-ledger.ts index 21f6d3d746..8ea49e75a7 100644 --- a/packages/client/ui-plugin-manager/src/client/config-ledger.ts +++ b/packages/client/ui-plugin-manager/src/client/config-ledger.ts @@ -1,14 +1,17 @@ /** * Which plugins bring their own configuration to the Plugins page, read from - * the three slots the page declares: the official plugins listed beside the - * official bundles, the bundles with a form on their page, and the rows with a - * page of their own. The projection follows the slot ledgers and the active - * locale and keeps its snapshot until one of them moves. + * the three slots the page declares (the official plugins listed beside the + * official bundles, the bundles with a form on their page, the rows with a + * page of their own) and from the Factory-declared `settings.section` (the + * plugins' settings pages). The projection follows the slot ledgers and the + * active locale and keeps its snapshot until one of them moves. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' import { resolveSlotLabel, type HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type {} from './slot-contract.ts' +// Type-only: the `settings.section` declaration whose entries this page lists. +import type {} from '@deepseek-ai/dsh-client-ui-settings/client' /** One official plugin as the page lists it: its registration id and its title in the active locale. */ export interface OfficialItem { @@ -16,15 +19,24 @@ export interface OfficialItem { readonly label: string } +/** One `settings.section` entry: its id, its title in the active locale, and the package that registered it, when known. */ +export interface SettingsSectionItem { + readonly id: string + readonly label: string + readonly module?: string +} + /** * The plugins carrying configuration: the official plugins in ledger order, - * the package names of the bundles with a page-level form, and the keys - * ({@link rowConfigKey}) of the rows with a page. + * the package names of the bundles with a page-level form, the keys + * ({@link rowConfigKey}) of the rows with a page, and the plugins' settings + * pages in ledger order. */ export interface ConfigLedger { readonly items: readonly OfficialItem[] readonly bundles: ReadonlySet readonly rows: ReadonlySet + readonly sections: readonly SettingsSectionItem[] } /** @@ -37,7 +49,7 @@ export function rowConfigKey(bundle: string, rowId: string): string { return `${bundle}#${rowId}` } -const SLOTS = ['plugins.item', 'plugins.bundle.config', 'plugins.row.config'] as const +const SLOTS = ['plugins.item', 'plugins.bundle.config', 'plugins.row.config', 'settings.section'] as const /** * Project the configuration ledgers as one observable the page binds. @@ -47,7 +59,7 @@ const SLOTS = ['plugins.item', 'plugins.bundle.config', 'plugins.row.config'] as export function configLedgerSource(ctx: ClientContext): HostObservable { let versions: readonly number[] = [] let revision = -1 - let ledger: ConfigLedger = { items: [], bundles: new Set(), rows: new Set() } + let ledger: ConfigLedger = { items: [], bundles: new Set(), rows: new Set(), sections: [] } const keysOf = (name: 'plugins.bundle.config' | 'plugins.row.config'): ReadonlySet => new Set(ctx.slots.entries(name).flatMap(entry => entry.options.key === undefined ? [] : [entry.options.key])) return { @@ -65,6 +77,15 @@ export function configLedgerSource(ctx: ClientContext): HostObservable { + /* v8 ignore next -- list-slot registration requires id */ + const id = entry.options.id ?? '' + return { + id, + label: resolveSlotLabel(entry.options.label) ?? id, + ...entry.module === undefined ? {} : { module: entry.module }, + } + }), } } return ledger diff --git a/packages/client/ui-plugin-manager/src/client/index.ts b/packages/client/ui-plugin-manager/src/client/index.ts index eadd359408..74dbb1d5f9 100644 --- a/packages/client/ui-plugin-manager/src/client/index.ts +++ b/packages/client/ui-plugin-manager/src/client/index.ts @@ -8,6 +8,8 @@ */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type {} from '@deepseek-ai/dsh-client-locale/client' +// Type-only: the ctx.modules Context merge. +import type {} from '@deepseek-ai/dsh-client-modules/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' // Type-only: the root `main` keyed slot the page registers into, declared by // ui-layout with the panel id brand, and the `sidebar.panellist` list the @@ -27,6 +29,7 @@ import { PluginManagerPage } from './PluginManagerPage.tsx' import { createPluginHeaderRef } from './header-scroll.ts' import { PluginRefreshToast, type PluginRefreshToastFace } from './PluginRefreshToast.tsx' import { PluginsPanelIcon } from './PluginsPanelIcon.tsx' +import { PluginsSettingsLink, type PluginsSettingsLinkInjected } from './PluginsSettingsLink.tsx' import { configLedgerSource } from './config-ledger.ts' import { tabLedgerSource } from './tab-ledger.ts' import { PluginManagerController } from './manager-store.ts' @@ -61,7 +64,7 @@ declare module '@deepseek-ai/cordis' { } export type { PluginManagerPageProps } from './PluginManagerPage.tsx' -export type { ConfigLedger, OfficialItem } from './config-ledger.ts' +export type { ConfigLedger, OfficialItem, SettingsSectionItem } from './config-ledger.ts' export type { PluginManagerFace } from './manager-store.ts' export type { PluginManagerLocaleKey } from './locales.ts' export type { @@ -83,7 +86,7 @@ export const NS = 'pluginManager' export const PANEL_ID = 'plugins' as MainPanelId /** Services required by the sidebar registration, the Remote methods, and access; the inventory says whether the Host manages a profile. */ -export const inject = ['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginRegistryProbe', 'configForms', 'layout', 'remoteAccess'] +export const inject = ['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginRegistryProbe', 'configForms', 'layout', 'remoteAccess', 'modules'] /** * Contribute the Plugins entry to the sidebar with the management page it @@ -134,7 +137,12 @@ export function apply(ctx: ClientContext): void { key: PANEL_ID, locale: NS, store, - inject: () => ({ ...face, createHeaderRef: createPluginHeaderRef }), + inject: () => ({ + ...face, + createHeaderRef: createPluginHeaderRef, + hooks: { ...face.hooks, clientSync: ctx.modules.entries.state }, + retryClient: () => { void ctx.modules.entries.retry().catch((error: unknown) => { ctx.logger.error(error) }) }, + }), children: { 'plugins.add.actions': { kind: 'list', scope: 'root' }, 'plugins.tab': { kind: 'list', scope: 'root' }, @@ -150,12 +158,13 @@ export function apply(ctx: ClientContext): void { yield ctx.layout.panelInfo.subscribe(() => { if (ctx.layout.panelInfo.getSnapshot().activePanelId !== PANEL_ID) instance.actions.setView({ kind: 'list' }) }) + const openList = (): void => { + ctx.layout.selectPanel(PANEL_ID) + instance.actions.setTab('installed') + instance.actions.setView({ kind: 'list' }) + } const disposeNavigation = ctx.reflect.provide('pluginNavigation', { - openList: () => { - ctx.layout.selectPanel(PANEL_ID) - instance.actions.setTab('installed') - instance.actions.setView({ kind: 'list' }) - }, + openList, openBundle: (packageName: string) => { ctx.layout.selectPanel(PANEL_ID) instance.actions.setTab('installed') @@ -163,6 +172,14 @@ export function apply(ctx: ClientContext): void { }, }) yield () => { void disposeNavigation() } + // Settings lists one entry that leads here. + yield ctx.slots.inject('settings.section', () => ctx.slots.register({ + name: 'settings.section', + id: PANEL_ID, + order: 15, + label: () => t('settingsEntry'), + inject: (): PluginsSettingsLinkInjected => ({ openPlugins: openList }), + }, PluginsSettingsLink)) }) yield ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', diff --git a/packages/client/ui-plugin-manager/src/client/locales.ts b/packages/client/ui-plugin-manager/src/client/locales.ts index c70c32549f..3301b8b68b 100644 --- a/packages/client/ui-plugin-manager/src/client/locales.ts +++ b/packages/client/ui-plugin-manager/src/client/locales.ts @@ -8,10 +8,14 @@ export const INSTALL_PATH_EXAMPLE = '/Users/name/my-plugin' /** Simplified Chinese dictionary and key source of truth. */ export const zh = { panel: '插件', + settingsEntry: '插件管理', + clientSyncing: '正在同步本页面的插件…', + clientSyncFailed: '本页面的插件未能完成同步;服务端的启用状态保持不变。', + clientSyncRetry: '重试本页面同步', title: '插件', intro: '安装、启用和配置插件', infoLabel: '插件说明', - infoDescription: '在这里配置官方插件,安装和管理其他插件。内置插件列表及运行状态可在「设置 → 内置插件」中查看', + infoDescription: '在这里配置官方插件,安装、管理和配置其他插件。', loading: '正在读取插件…', error: '可能由于网络问题,无法读取全部插件', unavailable: '本部署没有可管理的 profile,无法安装或启停插件。', @@ -308,10 +312,14 @@ export type PluginManagerLocaleKey = keyof typeof zh /** English dictionary checked against the Chinese key set. */ export const en = { panel: 'Plugins', + settingsEntry: 'Plugins', + clientSyncing: 'Syncing plugins on this page…', + clientSyncFailed: 'Some plugins could not sync on this page. Host enablement is unchanged.', + clientSyncRetry: 'Retry this page', title: 'Plugins', intro: 'Install, enable, and configure plugins', infoLabel: 'About plugins', - infoDescription: 'Configure official plugins and install or manage other plugins here. View the built-in plugin list and runtime status in Settings → Built-in plugins.', + infoDescription: 'Configure official plugins, and install, manage, and configure other plugins here.', loading: 'Reading plugins…', error: 'Could not read all plugins, possibly due to a network problem', unavailable: 'This deployment runs without a manageable profile, so plugins cannot be installed or switched here.', @@ -606,10 +614,14 @@ export const en = { export const ja = { 'reasonUnsupportedPlatform': 'このプラグインはDSHを実行しているホストOSに対応していません。', 'panel': 'プラグイン', + 'settingsEntry': 'プラグイン管理', + 'clientSyncing': 'このページでプラグインを同期中…', + 'clientSyncFailed': '一部のプラグインをこのページで同期できませんでした。ホスト側の有効化状態は変更されていません。', + 'clientSyncRetry': 'このページを再試行', 'title': 'プラグイン', 'intro': 'プラグインのインストール、有効化、設定', 'infoLabel': 'プラグインについて', - 'infoDescription': '公式プラグインの設定や、その他のプラグインのインストール・管理はここで行えます。組み込みプラグインの一覧と実行状態は「設定 → 組み込みプラグイン」で確認できます。', + 'infoDescription': '公式プラグインの設定や、その他のプラグインのインストール・管理・設定はここで行えます。', 'loading': 'プラグインを読み込み中…', 'error': '一部のプラグインを読み込めませんでした。ネットワークの問題が考えられます', 'unavailable': 'このデプロイでは管理可能なプロファイルが実行されていないため、ここでプラグインのインストールや切り替えはできません。', @@ -903,10 +915,14 @@ export const ja = { export const es = { reasonUnsupportedPlatform: 'Este complemento no es compatible con el sistema operativo que ejecuta DSH.', panel: 'Complementos', + settingsEntry: 'Complementos', + clientSyncing: 'Sincronizando complementos en esta página…', + clientSyncFailed: 'Algunos complementos no se pudieron sincronizar en esta página. La habilitación del host no ha cambiado.', + clientSyncRetry: 'Reintentar esta página', title: 'Complementos', intro: 'Instalar, habilitar y configurar complementos', infoLabel: 'Acerca de los complementos', - infoDescription: 'Configure complementos oficiales e instale o administre otros complementos aquí. Vea la lista de complementos integrados y el estado del tiempo de ejecución en Configuración → Complementos integrados.', + infoDescription: 'Configure aquí los complementos oficiales e instale, administre y configure otros complementos.', loading: 'Leyendo complementos…', error: 'No se pudieron leer todos los complementos, posiblemente debido a un problema de red', unavailable: 'Esta implementación se ejecuta sin un perfil manejable, por lo que los complementos no se pueden instalar ni cambiar aquí.', @@ -1200,10 +1216,14 @@ export const es = { export const fr = { reasonUnsupportedPlatform: 'Ce plugin ne prend pas en charge le système d’exploitation sur lequel DSH s’exécute.', panel: 'Plugins', + settingsEntry: 'Plugins', + clientSyncing: 'Synchronisation des plugins sur cette page…', + clientSyncFailed: "Certains plugins n'ont pas pu se synchroniser sur cette page. L'activation de l'hôte est inchangée.", + clientSyncRetry: 'Réessayez cette page', title: 'Plugins', intro: 'Installer, activer et configurer les plugins', infoLabel: 'À propos des plugins', - infoDescription: "Configurez les plugins officiels et installez ou gérez d'autres plugins ici. Affichez la liste des plugins intégrés et l'état d'exécution dans Paramètres → Plugins intégrés.", + infoDescription: "Configurez ici les plugins officiels, et installez, gérez et configurez d'autres plugins.", loading: 'Plugins de lecture…', error: "Impossible de lire tous les plugins, probablement à cause d'un problème de réseau", unavailable: "Ce déploiement s'exécute sans profil gérable, les plugins ne peuvent donc pas être installés ou commutés ici.", @@ -1497,10 +1517,14 @@ export const fr = { export const de = { reasonUnsupportedPlatform: 'Dieses Plugin unterstützt das Betriebssystem, auf dem DSH läuft, nicht.', panel: 'Plugins', + settingsEntry: 'Plugins', + clientSyncing: 'Plugins auf dieser Seite werden synchronisiert…', + clientSyncFailed: 'Einige Plugins konnten auf dieser Seite nicht synchronisiert werden. Die Host-Aktivierung bleibt unverändert.', + clientSyncRetry: 'Versuchen Sie es erneut mit dieser Seite', title: 'Plugins', intro: 'Plugins installieren, aktivieren und konfigurieren', infoLabel: 'Über Plugins', - infoDescription: 'Konfigurieren Sie hier offizielle Plugins und installieren oder verwalten Sie andere Plugins. Sehen Sie sich die Liste der integrierten Plugins und den Laufzeitstatus unter Einstellungen → Integrierte Plugins an.', + infoDescription: 'Konfigurieren Sie hier offizielle Plugins und installieren, verwalten und konfigurieren Sie andere Plugins.', loading: 'Plugins lesen…', error: 'Es konnten nicht alle Plugins gelesen werden, möglicherweise aufgrund eines Netzwerkproblems', unavailable: 'Diese Bereitstellung läuft ohne verwaltbares Profil, daher können hier keine Plugins installiert oder gewechselt werden.', @@ -1794,10 +1818,14 @@ export const de = { export const ru = { reasonUnsupportedPlatform: 'Этот плагин не поддерживает операционную систему, в которой работает DSH.', panel: 'Плагины', + settingsEntry: 'Плагины', + clientSyncing: 'Синхронизация плагинов на этой странице…', + clientSyncFailed: 'Некоторые плагины не смогли синхронизироваться на этой странице. Включение хоста не изменилось.', + clientSyncRetry: 'Повторить эту страницу', title: 'Плагины', intro: 'Установите, включите и настройте плагины', infoLabel: 'О плагинах', - infoDescription: 'Настройте официальные плагины, а также установите или управляйте другими плагинами здесь. Посмотреть список встроенных плагинов и статус выполнения можно в разделе «Настройки» → «Встроенные плагины».', + infoDescription: 'Здесь можно настраивать официальные плагины, а также устанавливать и настраивать другие плагины и управлять ими.', loading: 'Чтение плагинов…', error: 'Не удалось прочитать все плагины, возможно, из-за проблем с сетью.', unavailable: 'Это развертывание выполняется без управляемого профиля, поэтому здесь нельзя устанавливать или переключать плагины.', @@ -2091,10 +2119,14 @@ export const ru = { export const pt = { reasonUnsupportedPlatform: 'Este plugin não oferece suporte ao sistema operacional em que o DSH está sendo executado.', panel: 'Plug-ins', + settingsEntry: 'Plug-ins', + clientSyncing: 'Sincronizando plug-ins nesta página…', + clientSyncFailed: 'Alguns plug-ins não puderam ser sincronizados nesta página. A ativação do host permanece inalterada.', + clientSyncRetry: 'Tente esta página novamente', title: 'Plug-ins', intro: 'Instalar, habilitar e configurar plug-ins', infoLabel: 'Sobre plug-ins', - infoDescription: 'Configure plugins oficiais e instale ou gerencie outros plugins aqui. Veja a lista de plug-ins integrados e o status do tempo de execução em Configurações → Plug-ins integrados.', + infoDescription: 'Configure aqui os plug-ins oficiais e instale, gerencie e configure outros plug-ins.', loading: 'Lendo plug-ins…', error: 'Não foi possível ler todos os plugins, possivelmente devido a um problema de rede', unavailable: 'Esta implantação é executada sem um perfil gerenciável, portanto, os plug-ins não podem ser instalados ou trocados aqui.', diff --git a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx index 9069ce355b..66cd778fd9 100644 --- a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx @@ -17,6 +17,8 @@ import { PluginRefreshToast, type PluginRefreshToastFace } from '../src/client/P import { PluginsPanelIcon } from '../src/client/PluginsPanelIcon.tsx' import type { PluginManagerFace } from '../src/client/manager-store.ts' import type { createNavigationStore } from '../src/client/navigation-store.ts' +import type { PluginsSettingsLinkInjected } from '../src/client/PluginsSettingsLink.tsx' +import type { ClientSyncFace } from '../src/client/PluginManagerPage.tsx' usePinnedBrowserLanguages('zh-CN') beforeEach(() => { localStorage.clear() }) @@ -91,10 +93,13 @@ async function bench(allows: ((action: string) => boolean) | 'switchable' = () = }) const panelInfo = createSnapshotStore({ activePanelId: null }) const selectPanel = vi.fn((activePanelId) => { panelInfo.set({ activePanelId }) }) + const clientSync = createSnapshotStore({ syncing: false, failures: [] as { id: string; message: string }[] }) + const retryClient = vi.fn(() => Promise.resolve()) + ctx.provide('modules', { entries: { state: clientSync, retry: retryClient } }) ctx.provide('layout', { panelInfo, selectPanel, beginNavigation: () => new AbortController().signal, toggleSidebar: vi.fn(), openRightbar: vi.fn(), closeRightbar: vi.fn() }) await ctx.plugin(settings).await() - return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, list, remote, selectPanel, panelInfo, access } + return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, list, remote, selectPanel, panelInfo, access, clientSync, retryClient } } function declare(slots: SlotRegistry): () => void { @@ -160,6 +165,42 @@ describe('ui-plugin-manager browser plugin', () => { expect(b.list).not.toHaveBeenCalled() }) + it('keeps a Settings entry that opens the Plugins list while the page is registered', async () => { + const b = await bench() + const removeRoot = b.slots.register({ + name: 'root', + children: { + 'main': { kind: 'keyed', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + 'sidebar.panellist': { kind: 'list', scope: 'root' }, + 'settings.section': { kind: 'list', scope: 'root' }, + }, + } as never, () => null) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const link = b.slots.entries('settings.section')[0]! + expect(link.options).toMatchObject({ id: PANEL_ID, order: 15 }) + expect(resolveSlotLabel(link.options.label)).toBe('插件管理') + const navigation = (b.slots.entries('main')[0]!.store as ReturnType).create() + navigation.actions.setView({ kind: 'more' }) + const linkInjected: object = link.inject!() + ;(linkInjected as PluginsSettingsLinkInjected).openPlugins() + expect(b.panelInfo.getSnapshot().activePanelId).toBe(PANEL_ID) + expect(navigation.getSnapshot()).toEqual({ tab: 'installed', view: { kind: 'list' } }) + // The page reads this page's client synchronization from the module system and retries through it. + const pageInjected: object = b.slots.entries('main')[0]!.inject!() + const sync = pageInjected as ClientSyncFace + expect(sync.hooks.clientSync).toBe(b.clientSync) + sync.retryClient() + expect(b.retryClient).toHaveBeenCalledOnce() + const logged = vi.spyOn(b.ctx.logger('ui-plugin-manager'), 'error') + b.retryClient.mockRejectedValueOnce(new Error('retry failed')) + sync.retryClient() + await vi.waitFor(() => { expect(b.retryClient).toHaveBeenCalledTimes(2) }) + removeRoot() + expect(b.slots.entries('settings.section')).toEqual([]) + logged.mockRestore() + }) + it('shares refresh failures with the overlay after navigation and releases both registrations across reloads', async () => { const b = await bench() const fiber = b.ctx.plugin({ inject: [...inject], apply }) @@ -197,7 +238,7 @@ describe('ui-plugin-manager browser plugin', () => { }) it('declares only the services the page and its Remote methods use', () => { - expect(inject).toEqual(['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginRegistryProbe', 'configForms', 'layout', 'remoteAccess']) + expect(inject).toEqual(['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginRegistryProbe', 'configForms', 'layout', 'remoteAccess', 'modules']) }) it('reads the Host again on a later grant after showing the page, and not while access is withdrawn', async () => { @@ -284,7 +325,7 @@ describe('ui-plugin-manager browser plugin', () => { b.locale.setLocale('en') expect(face.resolveText(text)).toBe('Local tools') b.locale.setLocale('zh') - expect(face.hooks.configLedger.getSnapshot()).toEqual({ items: [], bundles: new Set(), rows: new Set() }) + expect(face.hooks.configLedger.getSnapshot()).toEqual({ items: [], bundles: new Set(), rows: new Set(), sections: [] }) // A Host change before the first render is not a reason to read. b.remote.emit('plugin-manager/changed', [{ reason: 'install' }]) b.ctx.emit('connection/reset') diff --git a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx index bb45a3f07d..babc8e04ff 100644 --- a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx @@ -7,8 +7,9 @@ import { Context } from '@deepseek-ai/cordis' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { ChangeResult, PluginEntryId, PluginInstallRequestId, PluginUpdateResult, PluginVersion, RegistryAttempt } from '@deepseek-ai/dsh-api-remotes/client' import { allowAllAccess, bindSnapshotSelector, stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' -import type { ConfigForm, ConfigFormSnapshot, SettingsMirrorSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client' +import type { ConfigForm, ConfigFormSnapshot, SettingsMirrorSnapshot, SettingsSectionOwnerProps, SettingsSectionViewProps } from '@deepseek-ai/dsh-client-ui-settings/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ClientEntryState } from '@deepseek-ai/dsh-client-modules/client' import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' import { StrictMode, type ReactNode } from 'react' import type { LocaleSnapshot } from '@deepseek-ai/dsh-client-locale/client' @@ -99,7 +100,7 @@ function subjectOf(owner: unknown): PluginsSubject | undefined { return typeof owner === 'object' && owner !== null && 'subject' in owner ? (owner as PluginDetailProps).subject : undefined } -const NO_CONFIG: ConfigLedger = { items: [], bundles: new Set(), rows: new Set() } +const NO_CONFIG: ConfigLedger = { items: [], bundles: new Set(), rows: new Set(), sections: [] } function renderTab( state: Partial = {}, config: Partial = {}, @@ -114,6 +115,8 @@ function renderTab( const ledger = createSnapshotStore({ ...NO_CONFIG, ...config }) const tabLedger = createSnapshotStore(tabs) const bundleDetails = createSnapshotStore({}) + const clientSync = createSnapshotStore({ syncing: false, failures: [] }) + const retryClient = vi.fn() const actions = { ensure: vi.fn(), refresh: vi.fn(), @@ -170,6 +173,8 @@ function renderTab( t, resolveText, ...actions, + useClientSync: bindSnapshotSelector(clientSync), + retryClient, usePluginManager: bindSnapshotSelector(store), useConfigLedger: bindSnapshotSelector(ledger), usePluginTabs: bindSnapshotSelector(tabLedger), @@ -186,6 +191,10 @@ function renderTab( stub.publish(forms[id]!.state as ConfigFormSnapshot) return { ...stub.scope, mutate: forms[id]!.mutate } }, + renderFactorySlot: ((name: string, factoryProps: SettingsSectionViewProps) => { + if (name !== 'settings.section.view') throw new Error(`Plugin manager fixture renders no Factory ${name}`) + return bodies[`settings.section:${factoryProps.id}`]?.('page', { close: factoryProps.close }) ?? null + }) as PluginManagerPageProps['renderFactorySlot'], renderSlot: (name, owner, opts) => { const body = bodies[`${name}:${opts?.only ?? opts?.entryKey ?? ''}`] if (body === undefined) return null @@ -219,6 +228,8 @@ function renderTab( actions, set: (next: Partial) => { act(() => { store.set({ ...store.getSnapshot(), ...next }) }) }, setDetails: (next: BundleDetailsState) => { act(() => { bundleDetails.set(next) }) }, + setClientSync: (next: ClientEntryState) => { act(() => { clientSync.set(next) }) }, + retryClient, setLanguage: (dict: typeof en) => { locale.setLocale(dict === zh ? 'zh' : 'en') currentT = translate(dict) @@ -228,6 +239,23 @@ function renderTab( } describe('PluginManagerPage', () => { + it('reports this page\'s client plugin synchronization on every view and retries it', () => { + const { setClientSync, retryClient } = renderTab({ status: 'unavailable', packages: [] }) + expect(document.querySelector('[data-client-sync-failure]')).toBeNull() + expect(screen.queryByText(en.clientSyncing)).toBeNull() + setClientSync({ syncing: true, failures: [{ id: '@fixture/live', message: 'download failed' }] }) + expect(screen.getByText(en.clientSyncing).getAttribute('role')).toBe('status') + const notice = document.querySelector('[data-client-sync-failure]') as HTMLElement + expect(within(notice).getByRole('alert').textContent).toBe(en.clientSyncFailed) + expect(within(notice).getByText('@fixture/live: download failed')).toBeTruthy() + const retry = within(notice).getByRole('button', { name: en.clientSyncRetry }) + expect((retry as HTMLButtonElement).disabled).toBe(true) + setClientSync({ syncing: false, failures: [{ id: '@fixture/live', message: 'download failed' }] }) + fireEvent.click(retry) + expect(retryClient).toHaveBeenCalledOnce() + expect(screen.queryByText(en.clientSyncing)).toBeNull() + }) + it('shows no tabs without contributions, and switches between Installed and a contributed tab', () => { const { actions, navigation, setTabs } = renderTab({ packages: [pkg()] }, {}, { 'plugins.tab:discover': (_view, owner) => { @@ -766,7 +794,7 @@ describe('PluginManagerPage', () => { expect(locked.getAttribute('title')).toBe(en.reasonManagementRequired) }) - it('omits profile and persistent-terminal bundles while retaining other optional and third-party bundles', () => { + it('omits hidden bundles while retaining other optional and third-party bundles', () => { renderTab({ packages: [ ...[ @@ -776,7 +804,7 @@ describe('PluginManagerPage', () => { '@deepseek-ai/dsh-sdk-app', '@deepseek-ai/dsh-acp-app', '@deepseek-ai/dsh-sdk-minimal', - '@deepseek-ai/dsh-experimental-terminal-bundle', + '@deepseek-ai/dsh-experimental-tool-worktree', ].map(name => pkg({ name })), pkg({ name: '@acme/dsh-base', readOnlyReason: 'management-required' }), pkg({ name: 'dsh-better-sidebar' }), @@ -789,22 +817,31 @@ describe('PluginManagerPage', () => { expect(document.querySelector('[data-plugin-count]')).toBeNull() }) - it.each([false, true])('hides persistent terminals from both lists and direct navigation without changing enabled=%s', (enabled) => { + it.each([false, true])('offers persistent terminals after Timeline with enabled=%s', (enabled) => { const name = '@deepseek-ai/dsh-experimental-terminal-bundle' const b = renderTab({ packages: [ - pkg({ name, official: true, enabled, rows: [row()] }), + pkg({ name, optional: true, installed: false, removable: false, enabled, rows: [row()] }), + pkg({ name: '@deepseek-ai/dsh-timeline', optional: true, installed: false, removable: false, enabled: false }), pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', official: true }), ] }) - expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + expect(document.querySelector(`[data-plugin-package="${name}"]`) !== null).toBe(enabled) fireEvent.click(screen.getByRole('button', { name: en.moreAction })) expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() - expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + expect(Array.from(document.querySelectorAll('[data-plugin-package]'), card => card.getAttribute('data-plugin-package'))).toEqual([ + '@deepseek-ai/dsh-experimental-voice-input-bundle', '@deepseek-ai/dsh-timeline', name, + ]) + const card = document.querySelector(`[data-plugin-package="${name}"]`) as HTMLElement + expect(within(card).getByText(en.statusBeta)).toBeTruthy() + expect(within(card).getByRole('switch').getAttribute('aria-checked')).toBe(String(enabled)) + fireEvent.click(within(card).getByRole('button', { name: en.openDetail.replace('{name}', name) })) + const detail = document.querySelector(`[data-plugin-detail="${name}"]`) as HTMLElement + expect(within(detail).getByText(en.statusBeta)).toBeTruthy() + fireEvent.click(within(detail).getByRole('switch', { name: en.enableToggle.replace('{name}', name) })) + expect(b.actions.setEnabled).toHaveBeenCalledExactlyOnceWith(name, !enabled) act(() => { b.navigation.actions.setView({ kind: 'package', name }) }) - expect(document.querySelector('[data-plugin-detail]')).toBeNull() + expect(document.querySelector(`[data-plugin-detail="${name}"]`)).not.toBeNull() act(() => { b.navigation.actions.setView({ kind: 'row', name, rowId: 'sidebar' }) }) - expect(document.querySelector('[data-plugin-row-detail]')).toBeNull() - expect(screen.queryByRole('switch', { name: en.enableToggle.replace('{name}', name) })).toBeNull() - expect(b.actions.setEnabled).not.toHaveBeenCalled() + expect(document.querySelector('[data-plugin-row-detail]')).not.toBeNull() expect(b.actions.setRowEnabled).not.toHaveBeenCalled() expect(b.actions.uninstall).not.toHaveBeenCalled() }) @@ -865,7 +902,7 @@ describe('PluginManagerPage', () => { it.each([false, true])('shows an empty list for hidden bundles with errors and installed=%s', (installed) => { renderTab({ - packages: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@deepseek-ai/dsh-experimental-terminal-bundle'].map(name => pkg({ + packages: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@deepseek-ai/dsh-experimental-tool-worktree'].map(name => pkg({ name, installed, error: { code: 'operation-error', diagnostic: 'Unreadable bundle' }, })), }) @@ -1219,8 +1256,12 @@ describe('PluginManagerPage', () => { fireEvent.click(toggle) expect(actions.setRowEnabled).toHaveBeenCalledExactlyOnceWith('include:sidebar', false) + // The Chinese page still finds the row by its English title. fireEvent.change(search, { target: { value: 'Sidebar component' } }) + expect(document.querySelectorAll('[data-plugin-row]')).toHaveLength(1) + fireEvent.change(search, { target: { value: 'no such row' } }) expect(screen.getByText(zh.partsFilterEmpty)).toBeTruthy() + fireEvent.change(search, { target: { value: 'Sidebar component' } }) setLanguage(en) expect(screen.getByRole('button', { name: en.configureRow.replace('{name}', 'Sidebar component') })).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: en.configureRow.replace('{name}', 'Sidebar component') })) @@ -1239,6 +1280,77 @@ describe('PluginManagerPage', () => { expect(screen.getByRole('heading', { level: 3 }).textContent).toBe('个人工具') }) + describe('plugin settings pages', () => { + it('shows a settings page on the row whose module registered it, and its close returns to the bundle', () => { + renderTab( + { packages: [pkg({ rows: [row(), row({ rowId: 'other', entryId: 'include:other' as PluginEntryId, moduleName: 'dsh-other' })] })] }, + { sections: [{ id: 'sidebar-settings', label: 'Sidebar settings', module: 'dsh-better-sidebar' }] }, + { 'settings.section:sidebar-settings': (_view, owner) => ( + + ) }, + ) + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })) + expect(screen.queryByRole('button', { name: en.configureRow.replace('{name}', 'dsh-other') })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.configureRow.replace('{name}', 'dsh-better-sidebar') })) + const detail = document.querySelector('[data-plugin-row-detail="dsh-better-sidebar#sidebar"]') as HTMLElement + fireEvent.click(within(detail).getByRole('button', { name: 'Leave settings' })) + expect(document.querySelector('[data-plugin-row-detail]')).toBeNull() + expect(screen.getByRole('button', { name: en.configureRow.replace('{name}', 'dsh-better-sidebar') })).toBeTruthy() + }) + + it('keeps a row\'s own configuration instead of its settings page, and lists no unclaimed page', () => { + renderTab( + { packages: [pkg({ rows: [row()] })] }, + { + rows: new Set(['dsh-better-sidebar#sidebar']), + sections: [ + { id: 'sidebar-settings', label: 'Sidebar settings', module: 'dsh-better-sidebar' }, + { id: 'loose', label: 'Loose settings', module: '@acme/loose' }, + ], + }, + { + 'plugins.row.config:dsh-better-sidebar#sidebar': view => view === 'page' ?
    : null, + 'settings.section:sidebar-settings': () => , + 'settings.section:loose': () => , + }, + ) + expect(screen.queryByText('Loose settings')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })) + fireEvent.click(screen.getByRole('button', { name: en.configureRow.replace('{name}', 'dsh-better-sidebar') })) + expect(screen.getByRole('form', { name: 'own form' })).toBeTruthy() + expect(screen.queryByRole('form', { name: 'mirrored form' })).toBeNull() + expect(screen.queryByRole('form', { name: 'loose form' })).toBeNull() + }) + + it('shows a settings page the bundle package registered on the bundle page when no row is that package', () => { + renderTab( + { packages: [pkg({ rows: [row({ moduleName: 'dsh-other' })] })] }, + { sections: [{ id: 'bundle-settings', label: 'Bundle settings', module: 'dsh-better-sidebar' }] }, + { 'settings.section:bundle-settings': (_view, owner) => ( + + ) }, + ) + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })) + expect(screen.queryByRole('button', { name: en.configureRow.replace('{name}', 'dsh-other') })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Leave bundle settings' })) + expect(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })).toBeTruthy() + }) + + it('keeps a bundle\'s own configuration instead of the settings page its package registered', () => { + renderTab( + { packages: [pkg({ rows: [row({ moduleName: 'dsh-other' })] })] }, + { bundles: new Set(['dsh-better-sidebar']), sections: [{ id: 'bundle-settings', label: 'Bundle settings', module: 'dsh-better-sidebar' }] }, + { + 'plugins.bundle.config:dsh-better-sidebar': () => , + 'settings.section:bundle-settings': () => , + }, + ) + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })) + expect(screen.getByRole('form', { name: 'bundle form' })).toBeTruthy() + expect(screen.queryByRole('form', { name: 'mirrored bundle form' })).toBeNull() + }) + }) + describe('configuration pages', () => { const bodies: SlotBodies = { 'plugins.item:bash': view => view === 'summary' ? 'Limits every command.' : , diff --git a/packages/client/ui-plugin-manager/tests/config-ledger.client.spec.ts b/packages/client/ui-plugin-manager/tests/config-ledger.client.spec.ts index 025fe9c16c..9caaa8e955 100644 --- a/packages/client/ui-plugin-manager/tests/config-ledger.client.spec.ts +++ b/packages/client/ui-plugin-manager/tests/config-ledger.client.spec.ts @@ -6,12 +6,13 @@ import { tabLedgerSource } from '../src/client/tab-ledger.ts' interface Registration { options: { id?: string; key?: string; label?: string | (() => string) } + module?: string } /** A slot registry and locale stand-in: ledgers by slot, versions that move on registration, and a locale revision. */ function bench() { - const entries: Record = { 'plugins.item': [], 'plugins.bundle.config': [], 'plugins.row.config': [], 'plugins.tab': [] } - const versions: Record = { 'plugins.item': 0, 'plugins.bundle.config': 0, 'plugins.row.config': 0, 'plugins.tab': 0 } + const entries: Record = { 'plugins.item': [], 'plugins.bundle.config': [], 'plugins.row.config': [], 'plugins.tab': [], 'settings.section': [] } + const versions: Record = { 'plugins.item': 0, 'plugins.bundle.config': 0, 'plugins.row.config': 0, 'plugins.tab': 0, 'settings.section': 0 } const listeners = new Map void>>() const localeListeners = new Set<() => void>() let revision = 0 @@ -36,8 +37,8 @@ function bench() { } return { ctx: ctx as never, - register: (name: string, options: Registration['options']): void => { - entries[name]?.push({ options }) + register: (name: string, options: Registration['options'], module?: string): void => { + entries[name]?.push(module === undefined ? { options } : { options, module }) versions[name] = (versions[name] ?? 0) + 1 for (const listener of listeners.get(name) ?? []) listener() }, @@ -53,18 +54,21 @@ describe('configLedgerSource', () => { it('projects the official items in ledger order with locale-following labels, and the bundle and row keys', () => { const b = bench() const source = configLedgerSource(b.ctx) - expect(source.getSnapshot()).toEqual({ items: [], bundles: new Set(), rows: new Set() }) + expect(source.getSnapshot()).toEqual({ items: [], bundles: new Set(), rows: new Set(), sections: [] }) let title = 'Shell' b.register('plugins.item', { id: 'bash', label: () => title }) b.register('plugins.item', { id: 'loop', label: 'Agent loop' }) b.register('plugins.bundle.config', { key: 'dsh-x' }) b.register('plugins.row.config', { key: rowConfigKey('dsh-x', 'row') }) + b.register('settings.section', { id: 'timeline', label: () => title }, '@scope/dsh-timeline') + b.register('settings.section', { id: 'loose', label: 'Loose' }) expect(source.getSnapshot()).toEqual({ items: [{ id: 'bash', label: 'Shell' }, { id: 'loop', label: 'Agent loop' }], bundles: new Set(['dsh-x']), rows: new Set(['dsh-x#row']), + sections: [{ id: 'timeline', label: 'Shell', module: '@scope/dsh-timeline' }, { id: 'loose', label: 'Loose' }], }) // A label thunk is re-read when the locale moves, not before. title = '终端' @@ -78,8 +82,11 @@ describe('configLedgerSource', () => { const source = configLedgerSource(b.ctx) b.register('plugins.item', { id: 'bare' }) b.register('plugins.bundle.config', {}) + b.register('settings.section', { id: 'unlabelled' }) - expect(source.getSnapshot()).toEqual({ items: [{ id: 'bare', label: '' }], bundles: new Set(), rows: new Set() }) + expect(source.getSnapshot()).toEqual({ + items: [{ id: 'bare', label: '' }], bundles: new Set(), rows: new Set(), sections: [{ id: 'unlabelled', label: 'unlabelled' }], + }) }) it('keeps its snapshot until a ledger or the locale moves, and follows every source while subscribed', () => { diff --git a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts index eb44f8eeb5..9a1a095633 100644 --- a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts +++ b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts @@ -73,7 +73,7 @@ function deferred() { /** A configuration ledger with nothing registered, as the page binds it beside the store. */ const NO_CONFIG: HostObservable = { - getSnapshot: () => ({ items: [], bundles: new Set(), rows: new Set() }), + getSnapshot: () => ({ items: [], bundles: new Set(), rows: new Set(), sections: [] }), subscribe: () => () => {}, } diff --git a/packages/client/ui-plugin-manager/tests/settings-link.client.spec.tsx b/packages/client/ui-plugin-manager/tests/settings-link.client.spec.tsx new file mode 100644 index 0000000000..f33b6f093a --- /dev/null +++ b/packages/client/ui-plugin-manager/tests/settings-link.client.spec.tsx @@ -0,0 +1,21 @@ +// @vitest-environment jsdom +/** The Settings entry that leaves Settings for the Plugins page. */ +import { cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PluginsSettingsLink, type PluginsSettingsLinkProps } from '../src/client/PluginsSettingsLink.tsx' + +afterEach(cleanup) + +describe('PluginsSettingsLink', () => { + it('closes Settings and opens the Plugins page when selected, rendering nothing', () => { + const calls: string[] = [] + const props = { + close: vi.fn(() => { calls.push('close') }), + openPlugins: vi.fn(() => { calls.push('open') }), + } satisfies Pick + // The entry reads only its owner and injected members; the standard seats stay unused. + const { container } = render() + expect(calls).toEqual(['close', 'open']) + expect(container.childElementCount).toBe(0) + }) +}) diff --git a/packages/client/ui-plugin-manager/tsconfig.client.json b/packages/client/ui-plugin-manager/tsconfig.client.json index eefbe67b00..e50ea12aeb 100644 --- a/packages/client/ui-plugin-manager/tsconfig.client.json +++ b/packages/client/ui-plugin-manager/tsconfig.client.json @@ -6,6 +6,9 @@ "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" }, "references": [ + { + "path": "../../util/text-search" + }, { "path": "../../util/package-manifest" }, @@ -36,6 +39,9 @@ { "path": "../ui-primitives" }, + { + "path": "../modules" + }, { "path": "../ui-renderer" }, diff --git a/packages/client/ui-plugin-market/README.i18n.yaml b/packages/client/ui-plugin-market/README.i18n.yaml index 64bebd3d61..1f3929d080 100644 --- a/packages/client/ui-plugin-market/README.i18n.yaml +++ b/packages/client/ui-plugin-market/README.i18n.yaml @@ -15,8 +15,8 @@ en: 76368b6b1da79c80 zh: 52384aee991ac542 /deepseek-ai-dsh-client-ui-plugin-market/use-this-package: - en: d633d36f830d052c - zh: 07de610c0b1bb34c + en: 93d2e945c62b429f + zh: e6be9e6255922304 /deepseek-ai-dsh-client-ui-plugin-market/understand-the-implementation: en: 66cef49ded72a290 zh: c89a13fa5e5fb965 diff --git a/packages/client/ui-plugin-market/README.md b/packages/client/ui-plugin-market/README.md index b4d70f233b..665893e3d1 100644 --- a/packages/client/ui-plugin-market/README.md +++ b/packages/client/ui-plugin-market/README.md @@ -24,9 +24,11 @@ Discover is the second tab of the **Plugins** page, after **Installed**. It list ## Use this package -Open **Plugins** and select **Discover**. With no index source, the tab shows an empty state whose **Add index source** button opens the **Index sources** dialog. The dialog lists each source by index title, or by host before the first read, with its URL, the error of its last failed read, and a remove button, and keeps a notice that indexes come from third parties. A refused URL keeps the draft and says why: an unsupported scheme, credentials, or fragment; a URL already listed; or a deployment that cannot save sources. A newly added source becomes the selected index. +Open **Plugins** and select **Discover**. With no index source, the tab shows an empty state whose **Add index source** button opens the **Index sources** dialog. The dialog lists each source by index title, or by host before the first read, with its URL, the error of its last failed read, and a remove button. It also reminds you to add only sources you trust. A newly added source becomes the selected index. -The toolbar holds the index menu, which switches indexes and ends with **Manage index sources…**; the search field; a **Labels** menu with multi-select checkmarks when the index declares labels; the **Sort** menu; and a refresh button. Controls wrap onto additional rows when space is limited, keeping search, filtering, sorting, and refresh available on mobile. Category pills, with **All** first, follow when the index declares categories. +Paste a JSON address or a Git repository address such as `https://github.com/acme/plugins` or `git@github.com:acme/plugins.git`. The dialog detects Git repository addresses and reads other addresses as direct JSON sources. For a custom HTTPS Git address without a `.git` suffix, use `git+https://`. Leave **Index file path** and **Git ref** blank to read the root `index.json` on the default branch. To use a private repository, set up [Git access on the Host](../../boot/plugin-market/README.md#use-this-package). If the dialog refuses to save the source, it keeps your entries and shows the reason. + +The toolbar holds the index menu, which switches indexes and ends with **Manage index sources…**; the search field; a **Labels** menu with multi-select checkmarks when the index declares labels; the **Sort** menu; and a refresh button. The index button and its menu entries show `github:owner/repo` for GitHub repository and Raw sources. A Raw index's title, if present, appears before the repository name. When GitHub labels repeat, the button and menu also show the Git ref and index file path or the part of the Raw path after the repository name. Controls wrap onto additional rows when space is limited, keeping search, filtering, sorting, and refresh available on mobile. Category pills, with **All** first, follow when the index declares categories. Each card shows the icon, localized title, label tags, a one-line description, and the default version, author, and publish date, with one action: **Update** for a bundle installed from a Git commit when the default version, else the newest stable version, is a newer commit of the repository directory it came from; **Install** for an installable entry; a disabled **Install** whose tooltip says no version is compatible with the running DSH when the plugin has no default version and its highest version is neither compatible nor exempted; or **Installed**, **Update available**, or **Provided by DSH**, which switches to the Installed tab and opens that bundle's page when that tab lists it. Selecting a card opens the entry's page with its full description, compatibility notice, and, under the source heading, the default version's facts: author; homepage and source code repository, as links that open in a new tab, with the package directory beside the repository; the npm package and registry, or the Git repository, full commit, and directory; publish date; category; labels; and index title. The page shows the long description first, without a heading of its own, then **Versions**, then the source facts. The **Versions** list is in descending SemVer order; each row tags the recommended, prerelease, installed, incompatible, and exempted versions. A row offers **Update** for each version the Host marks as an update of a bundle installed from a Git commit, and **Install** while the entry is not installed, each only for a version installation accepts; installation never goes over an installed or provided bundle. The page's back link returns to the list with its search, filters, and sort intact. diff --git a/packages/client/ui-plugin-market/README.zh.md b/packages/client/ui-plugin-market/README.zh.md index 77c1d7d638..23a0df5fdf 100644 --- a/packages/client/ui-plugin-market/README.zh.md +++ b/packages/client/ui-plugin-market/README.zh.md @@ -24,9 +24,11 @@ kind: "package-reference" ## 使用本包 -打开**插件**并选择**发现**。没有索引源时,该标签页显示空状态,其中的**添加索引源**按钮打开**索引源**对话框。对话框按插件索引标题列出每个索引源(首次读取前按主机名),并显示其 URL、最近一次读取失败的错误和删除按钮,同时保留一条提示,说明索引由第三方提供。URL 被拒绝时保留草稿并说明原因:不支持的协议、包含凭据或片段、URL 已在列表中,或当前部署无法保存索引源。新添加的索引源成为所选插件索引。 +打开**插件**并选择**发现**。没有索引源时,该标签页显示空状态,其中的**添加索引源**按钮打开**索引源**对话框。对话框按插件索引标题列出每个索引源(首次读取前按主机名),并显示其 URL、最近一次读取失败的错误和删除按钮。对话框还会提醒你只添加信任的索引源。新添加的索引源成为所选插件索引。 -工具栏包含:插件索引菜单,用于切换插件索引,最后一项为**管理索引源…**;搜索框;插件索引声明了标签时显示的**标签**菜单,以勾选标记支持多选;**排序**菜单;以及刷新按钮。空间不足时,控件自动换行,确保手机端仍可使用搜索、筛选、排序和刷新。插件索引声明了分类时,其后显示分类按钮,**全部**排在第一位。 +粘贴 JSON 地址或 Git 仓库地址,例如 `https://github.com/acme/plugins` 或 `git@github.com:acme/plugins.git`。对话框会识别 Git 仓库地址,其余地址按直接返回 JSON 的索引源读取。自托管仓库的 HTTPS 地址如果没有 `.git` 后缀,可以使用 `git+https://`。将**索引文件路径**和 **Git 引用**留空即可读取默认分支上根目录的 `index.json`。要使用私有仓库,请先配置 [Host 上的 Git 访问权限](../../boot/plugin-market/README.zh.md#use-this-package)。无法保存索引源时,对话框会保留已填写的内容并显示原因。 + +工具栏包含:插件索引菜单,用于切换插件索引,最后一项为**管理索引源…**;搜索框;插件索引声明了标签时显示的**标签**菜单,以勾选标记支持多选;**排序**菜单;以及刷新按钮。GitHub 仓库和 Raw 源在索引按钮及其菜单项中显示为 `github:owner/repo`。Raw 索引有标题时,标题显示在仓库名前。GitHub 标签重复时,索引按钮和菜单项还会显示 Git 引用和索引文件路径,或 Raw 地址中仓库名之后的路径。空间不足时,控件自动换行,确保手机端仍可使用搜索、筛选、排序和刷新。插件索引声明了分类时,其后显示分类按钮,**全部**排在第一位。 每张卡片显示图标、本地化标题、标签、一行描述,以及默认版本、作者和发布日期,并只有一个操作:从 Git 提交安装的组合包在默认版本(没有默认版本时为最新的稳定版本)是其来源仓库目录中较新的提交时显示**更新**;可安装的条目显示**安装**;没有默认版本、且最高版本既不兼容也未豁免的条目显示禁用的**安装**,其提示框说明没有与当前运行的 DSH 兼容的版本;其余条目显示**已安装**、**有新版本**或**随 DSH 提供**,点击后切换到「已安装」标签页,并在该标签页列出该组合包时打开其页面。选择卡片会打开条目页面,显示其完整描述、兼容性提示,并在来源标题下显示默认版本的信息:作者;主页和源代码仓库(在新标签页中打开的链接,仓库旁显示包所在目录);npm 包和注册表,或 Git 仓库、完整提交和目录;发布日期;分类;标签;以及插件索引标题。页面先显示详细介绍,不带单独的标题,然后是**版本**,然后是来源信息。**版本**列表按 SemVer 降序排列;每行标出推荐、预发布、已安装、不兼容和已豁免的版本。Host 标为某个从 Git 提交安装的组合包之更新的每个版本,其行提供**更新**;条目未安装时,行提供**安装**;两者都只针对安装检查接受的版本。安装从不覆盖已安装或 DSH 随附的组合包。页面的返回链接回到列表,搜索、筛选和排序保持不变。 diff --git a/packages/client/ui-plugin-market/package.json b/packages/client/ui-plugin-market/package.json index 14c8e68dc4..5e0dffaf9c 100644 --- a/packages/client/ui-plugin-market/package.json +++ b/packages/client/ui-plugin-market/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plugin-market", "description": "Discover tab of the dsh web Plugins page: browse configured plugin market indexes and install their bundles", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plugin-market/src/client/DiscoverSection.module.css b/packages/client/ui-plugin-market/src/client/DiscoverSection.module.css index 6f874795f9..7fd8ba4509 100644 --- a/packages/client/ui-plugin-market/src/client/DiscoverSection.module.css +++ b/packages/client/ui-plugin-market/src/client/DiscoverSection.module.css @@ -26,6 +26,12 @@ white-space: nowrap; } +.indexMenuName { + display: block; + overflow-wrap: anywhere; + white-space: normal; +} + .search { flex: 1; min-width: 120px; @@ -394,13 +400,22 @@ .sourceForm { display: flex; - align-items: center; + flex-direction: column; gap: 8px; } -.grow { - flex: 1; - min-width: 0; +.sourceField { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 13px; + line-height: 20px; + font-weight: 500; +} + +.sourceActions { + display: flex; + justify-content: flex-end; } .confirmHead { diff --git a/packages/client/ui-plugin-market/src/client/DiscoverSection.tsx b/packages/client/ui-plugin-market/src/client/DiscoverSection.tsx index ff59f12906..cc347ce0ea 100644 --- a/packages/client/ui-plugin-market/src/client/DiscoverSection.tsx +++ b/packages/client/ui-plugin-market/src/client/DiscoverSection.tsx @@ -7,9 +7,11 @@ import { } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { MarketCompatibility, MarketListingEntry, MarketListingVersion, MarketSearchResult, MarketSort } from '@deepseek-ai/dsh-api-remotes/client' +import { isGitMarketIndexSourceAddress } from '@deepseek-ai/dsh-plugin-market-index/source' import type { DiscoverFace, DiscoverState, ListingFailure, ListingState, SourceFailure } from './market-store.ts' import { - displayDeclarations, indexLabel, presentedVersion, sourceFacts, withText, type DiscoverQuery, type DisplayDeclaration, type SourceFact, + displayDeclarations, indexLabel, indexMenuItems, presentedVersion, sourceFacts, withText, + type DiscoverQuery, type DisplayDeclaration, type SourceFact, } from './presentation.ts' import { PluginDetailSection } from './PluginDetailSection.tsx' import css from './DiscoverSection.module.css' @@ -54,6 +56,7 @@ function MarketIcon({ src, size }: { readonly src: string | undefined; readonly function sourceFailureText(failure: SourceFailure, t: Translate): string { switch (failure.kind) { case 'invalid': return t('sourceInvalid') + case 'invalid-git': return t('sourceInvalidGit') case 'duplicate': return t('sourceDuplicate') case 'unavailable': return t('sourceUnavailable') case 'other': return t('sourceFailed') @@ -314,6 +317,7 @@ function SourcesDialog({ state, t, face }: { readonly t: Translate readonly face: DiscoverActions }): ReactNode { + const git = isGitMarketIndexSourceAddress(state.draft) return ( @@ -337,12 +341,32 @@ function SourcesDialog({ state, t, face }: { )} { event.preventDefault(); face.addSource() }}> - { face.editDraft(event.target.value) }} /> - + + {git ? ( + <> + + + + ) : null} +
    + +
    {state.sourceFailure === null ? null :

    {sourceFailureText(state.sourceFailure, t)}

    }

    @@ -459,8 +483,8 @@ function Browser({ state, listing, t, face, hooks, language, onInstall, onUpdate onOpenInstalled={() => { openPackage(openEntry.name) }} /> ) } - const selected = state.indexes.find(index => index.url === listing.url) ?? { url: listing.url } - const market = indexLabel(selected, face.resolveText) + const indexItems = indexMenuItems(state.indexes, face.resolveText) + const market = indexItems.find(item => item.id === listing.url)?.label ?? indexLabel({ url: listing.url }, face.resolveText) const { sort } = query const sortOptions = [ ...query.text.trim() === '' ? [] : [{ id: 'relevance', label: t('sortRelevance') }], @@ -495,7 +519,7 @@ function Browser({ state, listing, t, face, hooks, language, onInstall, onUpdate <>

    { setMenu(null) }} portal autoFocus selectedId={listing.url} - items={state.indexes.map(index => ({ id: index.url, label: indexLabel(index, face.resolveText) }))} + items={indexItems.map(({ id, label }) => ({ id, label: {label} }))} footer={[{ id: 'manage', label: t('manageSources'), icon: }]} onSelect={(id) => { setMenu(null) @@ -504,7 +528,7 @@ function Browser({ state, listing, t, face, hooks, language, onInstall, onUpdate }} anchor={( diff --git a/packages/client/ui-plugin-market/src/client/locales.ts b/packages/client/ui-plugin-market/src/client/locales.ts index 3bcadd89cc..f21690d1f1 100644 --- a/packages/client/ui-plugin-market/src/client/locales.ts +++ b/packages/client/ui-plugin-market/src/client/locales.ts @@ -15,9 +15,15 @@ export const zh = { manageSources: '管理索引源…', marketMenu: '切换插件索引,当前为 {market}', sourcesTitle: '索引源', - sourcesDescription: '插件索引以一个索引文件的 URL 提供,「发现」从这里列出的索引浏览插件', + sourcesDescription: '可以从 JSON 地址或 Git 仓库添加插件索引', sourcesLabel: '已添加的索引源', - sourceUrl: '索引 URL', + sourceUrl: '源地址', + sourcePath: '索引文件路径', + sourceRef: 'Git 引用', + sourceDefaultRef: '默认分支', + sourceInvalidGit: '请使用 HTTPS 或 SSH 仓库地址,并填写有效的索引路径和 Git 引用', + sourceRepositoryPlaceholder: 'https://github.com/owner/repository', + sourcePathPlaceholder: 'index.json', sourcePlaceholder: 'https://example.com/index.json', addSource: '添加', removeSource: '移除', @@ -111,9 +117,15 @@ export const en = { manageSources: 'Manage index sources…', marketMenu: 'Switch plugin index, currently {market}', sourcesTitle: 'Index sources', - sourcesDescription: 'A plugin index is published as the URL of one index file. Discover browses the indexes listed here.', + sourcesDescription: 'Add a plugin index from a JSON address or a Git repository.', sourcesLabel: 'Added index sources', - sourceUrl: 'Index URL', + sourceUrl: 'Source address', + sourcePath: 'Index file path', + sourceRef: 'Git ref', + sourceDefaultRef: 'Default branch', + sourceInvalidGit: 'Use an HTTPS or SSH repository address and a valid index path and Git ref.', + sourceRepositoryPlaceholder: 'https://github.com/owner/repository', + sourcePathPlaceholder: 'index.json', sourcePlaceholder: 'https://example.com/index.json', addSource: 'Add', removeSource: 'Remove', @@ -204,9 +216,15 @@ export const ja = { 'manageSources': 'インデックスソースを管理…', 'marketMenu': 'プラグインインデックスを切り替え、現在は{market}', 'sourcesTitle': 'インデックスソース', - 'sourcesDescription': 'プラグインインデックスは1つのインデックスファイルのURLとして公開されます。「見つける」ではここに一覧されたインデックスを閲覧します。', + 'sourcesDescription': 'JSON の URL または Git リポジトリからプラグインインデックスを追加します。', 'sourcesLabel': '追加済みのインデックスソース', - 'sourceUrl': 'インデックスURL', + 'sourceUrl': 'ソースのアドレス', + 'sourcePath': 'インデックスファイルのパス', + 'sourceRef': 'Git 参照', + 'sourceDefaultRef': 'デフォルトブランチ', + 'sourceInvalidGit': 'HTTPS または SSH のリポジトリアドレスと、有効なインデックスパスおよび Git 参照を指定してください。', + 'sourceRepositoryPlaceholder': 'https://github.com/owner/repository', + 'sourcePathPlaceholder': 'index.json', 'sourcePlaceholder': 'https://example.com/index.json', 'addSource': '追加', 'removeSource': '削除', @@ -297,9 +315,15 @@ export const es = { manageSources: 'Administrar fuentes de índice...', marketMenu: 'Cambiar el índice de complementos; actual: {market}', sourcesTitle: 'Fuentes del índice', - sourcesDescription: 'Un índice de complementos se publica mediante la URL de un archivo de índice. Descubrir explora los índices enumerados aquí.', + sourcesDescription: 'Añade un índice de complementos desde una dirección JSON o un repositorio Git.', sourcesLabel: 'Fuentes de índice agregadas', - sourceUrl: 'URL del índice', + sourceUrl: 'Dirección de la fuente', + sourcePath: 'Ruta del archivo de índice', + sourceRef: 'Referencia de Git', + sourceDefaultRef: 'Rama predeterminada', + sourceInvalidGit: 'Usa una dirección de repositorio HTTPS o SSH y una ruta de índice y una referencia de Git válidas.', + sourceRepositoryPlaceholder: 'https://github.com/owner/repository', + sourcePathPlaceholder: 'index.json', sourcePlaceholder: 'https://example.com/index.json', addSource: 'Añadir', removeSource: 'Quitar', @@ -390,9 +414,15 @@ export const fr = { manageSources: "Gérer les sources d'index…", marketMenu: 'Changer d’index de plugins, actuellement {market}', sourcesTitle: "Sources d'index", - sourcesDescription: 'Un index de plugins est publié à l’URL d’un fichier d’index. Découvrir parcourt les index répertoriés ici.', + sourcesDescription: 'Ajoutez un index de plugins depuis une adresse JSON ou un dépôt Git.', sourcesLabel: "Sources d'index ajoutées", - sourceUrl: "URL de l'index", + sourceUrl: 'Adresse de la source', + sourcePath: 'Chemin du fichier d’index', + sourceRef: 'Référence Git', + sourceDefaultRef: 'Branche par défaut', + sourceInvalidGit: 'Utilisez une adresse de dépôt HTTPS ou SSH, ainsi qu’un chemin d’index et une référence Git valides.', + sourceRepositoryPlaceholder: 'https://github.com/owner/repository', + sourcePathPlaceholder: 'index.json', sourcePlaceholder: 'https://example.com/index.json', addSource: 'Ajouter', removeSource: 'Supprimer', @@ -483,9 +513,15 @@ export const de = { manageSources: 'Indexquellen verwalten…', marketMenu: 'Plugin-Index wechseln, aktuell {market}', sourcesTitle: 'Indexquellen', - sourcesDescription: 'Ein Plugin-Index wird über die URL einer Indexdatei veröffentlicht. Entdecken durchsucht die hier aufgeführten Indizes.', + sourcesDescription: 'Füge einen Plugin-Index über eine JSON-Adresse oder ein Git-Repository hinzu.', sourcesLabel: 'Indexquellen hinzugefügt', - sourceUrl: 'Index-URL', + sourceUrl: 'Quelladresse', + sourcePath: 'Pfad zur Indexdatei', + sourceRef: 'Git-Referenz', + sourceDefaultRef: 'Standardbranch', + sourceInvalidGit: 'Verwende eine HTTPS- oder SSH-Repository-Adresse sowie einen gültigen Indexpfad und eine gültige Git-Referenz.', + sourceRepositoryPlaceholder: 'https://github.com/owner/repository', + sourcePathPlaceholder: 'index.json', sourcePlaceholder: 'https://example.com/index.json', addSource: 'Hinzufügen', removeSource: 'Entfernen', @@ -576,9 +612,15 @@ export const ru = { manageSources: 'Управление источниками индексов…', marketMenu: 'Переключить индекс плагинов, текущий: {market}', sourcesTitle: 'Источники индекса', - sourcesDescription: 'Индекс плагинов публикуется по URL файла индекса. В разделе «Обнаружение» можно просматривать перечисленные здесь индексы.', + sourcesDescription: 'Добавьте индекс плагинов по адресу JSON или из репозитория Git.', sourcesLabel: 'Добавлены источники индекса', - sourceUrl: 'URL-адрес индекса', + sourceUrl: 'Адрес источника', + sourcePath: 'Путь к файлу индекса', + sourceRef: 'Ссылка Git', + sourceDefaultRef: 'Ветка по умолчанию', + sourceInvalidGit: 'Укажите адрес репозитория HTTPS или SSH, а также допустимый путь к индексу и ссылку Git.', + sourceRepositoryPlaceholder: 'https://github.com/owner/repository', + sourcePathPlaceholder: 'index.json', sourcePlaceholder: 'https://example.com/index.json', addSource: 'Добавить', removeSource: 'Удалить', @@ -669,9 +711,15 @@ export const pt = { manageSources: 'Gerenciar fontes de índice…', marketMenu: 'Mudar de índice de plug-ins, atual: {market}', sourcesTitle: 'Fontes de índice', - sourcesDescription: 'Um índice de plug-ins é publicado pela URL de um arquivo de índice. Descobrir navega pelos índices listados aqui.', + sourcesDescription: 'Adicione um índice de plug-ins a partir de um endereço JSON ou repositório Git.', sourcesLabel: 'Fontes de índice adicionadas', - sourceUrl: 'URL do índice', + sourceUrl: 'Endereço da fonte', + sourcePath: 'Caminho do arquivo de índice', + sourceRef: 'Referência do Git', + sourceDefaultRef: 'Branch padrão', + sourceInvalidGit: 'Use um endereço de repositório HTTPS ou SSH e um caminho de índice e uma referência do Git válidos.', + sourceRepositoryPlaceholder: 'https://github.com/owner/repository', + sourcePathPlaceholder: 'index.json', sourcePlaceholder: 'https://example.com/index.json', addSource: 'Adicionar', removeSource: 'Remover', diff --git a/packages/client/ui-plugin-market/src/client/market-store.ts b/packages/client/ui-plugin-market/src/client/market-store.ts index 43d5d2b721..49718ea28f 100644 --- a/packages/client/ui-plugin-market/src/client/market-store.ts +++ b/packages/client/ui-plugin-market/src/client/market-store.ts @@ -6,6 +6,7 @@ import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type { MarketIndexSummary, MarketSearchResult, PluginDetail, PluginDetailDocumentId, RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' import type { LocaleSnapshot } from '@deepseek-ai/dsh-client-locale/client' +import { gitMarketIndexSource, isGitMarketIndexSourceAddress } from '@deepseek-ai/dsh-plugin-market-index/source' import { declaredQuery, INITIAL_QUERY, type DiscoverQuery } from './presentation.ts' /** Why the last listing read failed: the index could not be fetched, is not a valid index, or changed while its pages loaded. */ @@ -13,9 +14,17 @@ export type ListingFailure = 'fetch' | 'invalid' | 'changed' /** Why the last source change was refused. */ export type SourceFailure = - | { readonly kind: 'invalid' | 'duplicate' | 'unavailable' } + | { readonly kind: 'invalid' | 'invalid-git' | 'duplicate' | 'unavailable' } | { readonly kind: 'other'; readonly reason: string } +type SourceKind = 'http' | 'git' + +/** The optional location of an index in Git. */ +interface SourceOptions { + readonly path: string + readonly ref: string +} + /** Plugins loaded before "Show more", and loaded again by each press. */ export const PAGE_SIZE = 50 @@ -45,6 +54,7 @@ export interface DiscoverState { /** Whether the source editor is open; it is always shown when no source exists. */ readonly editing: boolean readonly draft: string + readonly sourceOptions: SourceOptions readonly saving: boolean readonly sourceFailure: SourceFailure | null } @@ -122,6 +132,7 @@ export interface DiscoverFace extends DetailFace { readonly retry: () => void readonly toggleSources: () => void readonly editDraft: (text: string) => void + readonly editSourceOptions: (options: Partial) => void readonly addSource: () => void readonly removeSource: (url: string) => void } @@ -129,12 +140,18 @@ export interface DiscoverFace extends DetailFace { /** Largest page the Host returns, the `limit` bound of `pluginMarket.search`. */ const MAX_PAGE = 100 +const INITIAL_SOURCE_OPTIONS: SourceOptions = { path: '', ref: '' } + const INITIAL: DiscoverState = { - status: 'idle', indexes: [], selected: null, listing: null, editing: false, draft: '', saving: false, sourceFailure: null, + status: 'idle', indexes: [], selected: null, listing: null, editing: false, draft: '', sourceOptions: INITIAL_SOURCE_OPTIONS, + saving: false, sourceFailure: null, } -function sourceFailure(failure: RemoteFailure): SourceFailure { - if (failure.code === 'plugin-market/invalid-index-url') return { kind: failure.details.reason === 'duplicate' ? 'duplicate' : 'invalid' } +function sourceFailure(failure: RemoteFailure, kind?: SourceKind): SourceFailure { + if (failure.code === 'plugin-market/invalid-index-url') { + if (failure.details.reason === 'duplicate') return { kind: 'duplicate' } + return { kind: kind === 'git' ? 'invalid-git' : 'invalid' } + } if (failure.code === 'plugin-market/settings-unavailable') return { kind: 'unavailable' } return { kind: 'other', reason: failure.message } } @@ -209,13 +226,9 @@ export class DiscoverController { }, toggleSources: () => { this.patch({ editing: !this.state().editing, sourceFailure: null }) }, editDraft: (text) => { this.patch({ draft: text, sourceFailure: null }) }, - addSource: () => { - const draft = this.state().draft.trim() - if (draft === '') return - this.selectAdded = true - void this.saveSources([...this.state().indexes.map(index => index.url), draft], true) - }, - removeSource: (url) => { void this.saveSources(this.state().indexes.map(index => index.url).filter(item => item !== url), false) }, + editSourceOptions: (options) => { this.patch({ sourceOptions: { ...this.state().sourceOptions, ...options }, sourceFailure: null }) }, + addSource: () => { this.addSource() }, + removeSource: (url) => { void this.saveSources(this.state().indexes.map(index => index.url).filter(item => item !== url)) }, } } @@ -400,16 +413,37 @@ export class DiscoverController { this.patch({ listing, indexes }) } - private async saveSources(urls: string[], adding: boolean): Promise { + private addSource(): void { + const { draft, sourceOptions, indexes, saving } = this.state() + const address = draft.trim() + if (saving || address === '') return + const kind = isGitMarketIndexSourceAddress(address) ? 'git' : 'http' + let url = address + if (kind === 'git') { + try { + url = gitMarketIndexSource(address, sourceOptions.path.trim() || undefined, sourceOptions.ref.trim() || undefined) + } catch { + this.patch({ sourceFailure: { kind: 'invalid-git' } }) + return + } + } + this.selectAdded = true + void this.saveSources([...indexes.map(index => index.url), url], kind) + } + + private async saveSources(urls: string[], adding?: SourceKind): Promise { + if (this.state().saving) return + const isDisposed = (): boolean => this.disposed this.patch({ saving: true, sourceFailure: null }) const answer = await this.ctx.remote.pluginMarket.setIndexes(urls) - if (this.disposed) return + if (isDisposed()) return if (!answer.ok) { this.selectAdded = false - this.patch({ saving: false, sourceFailure: sourceFailure(answer.error) }) + this.patch({ saving: false, sourceFailure: sourceFailure(answer.error, adding) }) return } - this.patch({ saving: false, ...adding ? { draft: '' } : {} }) await this.loadIndexes() + if (isDisposed()) return + this.patch({ saving: false, ...adding === undefined ? {} : { draft: '', sourceOptions: INITIAL_SOURCE_OPTIONS } }) } } diff --git a/packages/client/ui-plugin-market/src/client/presentation.ts b/packages/client/ui-plugin-market/src/client/presentation.ts index 2ce11ebb7f..a11a60d96b 100644 --- a/packages/client/ui-plugin-market/src/client/presentation.ts +++ b/packages/client/ui-plugin-market/src/client/presentation.ts @@ -2,6 +2,7 @@ import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { MarketIndexSummary, MarketListingEntry, MarketListingVersion, MarketSort } from '@deepseek-ai/dsh-api-remotes/client' import type { MarketIndexMetadata } from '@deepseek-ai/dsh-plugin-market-index' +import { parseGitMarketIndexSource } from '@deepseek-ai/dsh-plugin-market-index/source' /** The Discover query: text, filters, and order, without paging. */ export interface DiscoverQuery { @@ -113,3 +114,68 @@ export function indexLabel(index: MarketIndexSummary, resolveText: (text: Locali if (index.title !== undefined) return resolveText(index.title) return URL.canParse(index.url) ? new URL(index.url).host : index.url } + +interface GitHubIndexName { + readonly label: string + readonly location: string +} + +function githubIndexName(index: MarketIndexSummary, resolveText: (text: LocalizedText) => string): GitHubIndexName | undefined { + if (!URL.canParse(index.url)) return undefined + const { host, protocol, pathname } = new URL(index.url) + if (host === 'github.com' && /^git\+(?:https|ssh):$/u.test(protocol)) { + const repository = /^\/([\w.-]+\/[\w.-]+)\.git$/u.exec(pathname)?.[1] + if (repository === undefined) return undefined + try { + const { ref = 'HEAD', path } = parseGitMarketIndexSource(index.url) + return { label: `github:${repository}`, location: `${ref}:${path}` } + } catch (_invalidGitSource) { + return undefined + } + } + if (host === 'raw.githubusercontent.com' && /^https?:$/u.test(protocol)) { + const prefix = /^\/[\w.-]+\/[\w.-]+\/(?=[^/]+\/[^/])/u.exec(pathname)?.[0] + if (prefix === undefined) return undefined + const source = `github:${prefix.slice(1, -1)}` + const label = index.title === undefined ? source : `${resolveText(index.title)} · ${source}` + return { label, location: pathname.slice(prefix.length) } + } + return undefined +} + +function repeatedLabels(items: readonly { readonly label: string }[]): Set { + const seen = new Set() + const repeated = new Set() + for (const { label } of items) { + if (seen.has(label)) repeated.add(label) + seen.add(label) + } + return repeated +} + +/** + * Label the Discover selector and its menu in source order. Titled Raw indexes keep their localized title. + * Duplicate GitHub labels include the file location, then an ordinal if the location still matches. + * @param indexes - the configured sources in display order. + * @param resolveText - current-language text resolution. + * @returns menu items identified by their configured source URLs. + */ +export function indexMenuItems( + indexes: readonly MarketIndexSummary[], resolveText: (text: LocalizedText) => string, +): { readonly id: string; readonly label: string }[] { + const items = indexes.map((index) => { + const github = githubIndexName(index, resolveText) + return { id: index.url, label: github?.label ?? indexLabel(index, resolveText), location: github?.location } + }) + const duplicates = repeatedLabels(items) + const named = items.map(item => item.location !== undefined && duplicates.has(item.label) + ? { ...item, label: `${item.label} · ${item.location}` } : item) + const repeated = repeatedLabels(named) + const positions = new Map() + return named.map(({ id, label, location }) => { + if (location === undefined || !repeated.has(label)) return { id, label } + const position = (positions.get(label) ?? 0) + 1 + positions.set(label, position) + return { id, label: `${label} (${position})` } + }) +} diff --git a/packages/client/ui-plugin-market/tests/discover.client.spec.tsx b/packages/client/ui-plugin-market/tests/discover.client.spec.tsx index d2b58fd9b8..9e019b5093 100644 --- a/packages/client/ui-plugin-market/tests/discover.client.spec.tsx +++ b/packages/client/ui-plugin-market/tests/discover.client.spec.tsx @@ -75,7 +75,8 @@ const LISTING: MarketSearchResult = { const READY: DiscoverState = { status: 'ready', indexes: [{ url: A, title: LISTING.title }, { url: B }], selected: A, - listing: { url: A, query: INITIAL_QUERY, status: 'ready', value: LISTING, answered: INITIAL_QUERY, failure: null }, editing: false, draft: '', saving: false, sourceFailure: null, + listing: { url: A, query: INITIAL_QUERY, status: 'ready', value: LISTING, answered: INITIAL_QUERY, failure: null }, + editing: false, draft: '', sourceOptions: { path: '', ref: '' }, saving: false, sourceFailure: null, } function renderTab(state: Partial = {}, dictionary: Record = en) { @@ -85,7 +86,7 @@ function renderTab(state: Partial = {}, dictionary: Record undefined), } const install = vi.fn() @@ -281,6 +282,40 @@ describe('DiscoverSection', () => { expect(actions.toggleSources).toHaveBeenCalledOnce() }) + it('keeps the Raw index title before its GitHub repository on the button and in the menu', () => { + const url = 'https://raw.githubusercontent.com/acme/plugins/main/index.json' + const other = 'git+ssh://git@github.com/acme/internal.git' + const label = 'Alpha index · github:acme/plugins' + const { actions } = renderTab({ + indexes: [{ url, title: LISTING.title }, { url: other, title: 'Internal plugins' }], selected: url, + listing: { url, query: INITIAL_QUERY, status: 'ready', value: { ...LISTING, url }, answered: INITIAL_QUERY, failure: null }, + }) + const button = screen.getByRole('button', { name: `Switch plugin index, currently ${label}` }) + expect(within(button).getByText(label)).toBeTruthy() + fireEvent.click(button) + expect(screen.getByRole('menuitem', { name: label })).toBeTruthy() + fireEvent.click(screen.getByRole('menuitem', { name: 'github:acme/internal' })) + expect(actions.select).toHaveBeenCalledWith(other) + }) + + it('distinguishes Git indexes in the same GitHub repository by ref and file path', () => { + const url = 'git+https://github.com/acme/plugins.git' + const other = 'git+ssh://git@github.com/acme/plugins.git?path=market%2Findex.json&ref=release%2Fstable' + const label = 'github:acme/plugins · HEAD:index.json' + const otherLabel = 'github:acme/plugins · release/stable:market/index.json' + const listing: ListingState = { + url, query: INITIAL_QUERY, status: 'ready', value: { ...LISTING, url }, answered: INITIAL_QUERY, failure: null, + } + const { actions, set } = renderTab({ indexes: [{ url }, { url: other }], selected: url, listing }) + openMenu(`Switch plugin index, currently ${label}`) + expect(screen.getByRole('menuitem', { name: label })).toBeTruthy() + fireEvent.click(screen.getByRole('menuitem', { name: otherLabel })) + expect(actions.select).toHaveBeenCalledWith(other) + set({ selected: other, listing: { ...listing, url: other, value: { ...LISTING, url: other } } }) + const button = screen.getByRole('button', { name: `Switch plugin index, currently ${otherLabel}` }) + expect(within(button).getByText(otherLabel)).toBeTruthy() + }) + it('opens an entry page with its source facts and actions, and returns to the list', () => { const { install, openPackage, actions } = renderTab() fireEvent.click(card('dsh-a').getByRole('button', { name: 'View Alpha' })) @@ -481,6 +516,7 @@ describe('DiscoverSection', () => { expect(actions.addSource).toHaveBeenCalledOnce() for (const [failure, text] of [ [{ kind: 'invalid' }, en.sourceInvalid], [{ kind: 'duplicate' }, en.sourceDuplicate], + [{ kind: 'invalid-git' }, en.sourceInvalidGit], [{ kind: 'unavailable' }, en.sourceUnavailable], [{ kind: 'other', reason: 'boom' }, en.sourceFailed], ] as const) { set({ sourceFailure: failure }) @@ -494,6 +530,27 @@ describe('DiscoverSection', () => { expect(screen.queryByRole('list', { name: en.sourcesLabel })).toBeNull() }) + it('shows Git file options only for a recognized repository address', () => { + const { actions, set } = renderTab({ editing: true, draft: 'https://git.example/acme/plugins' }) + const dialog = within(screen.getByRole('dialog', { name: en.sourcesTitle })) + const address = dialog.getByRole('textbox', { name: en.sourceUrl }) + const add = dialog.getByRole('button', { name: en.addSource }) + expect(dialog.queryByRole('combobox')).toBeNull() + expect(add.hasAttribute('disabled')).toBe(false) + expect(dialog.queryByRole('textbox', { name: en.sourcePath })).toBeNull() + expect(dialog.queryByRole('textbox', { name: en.sourceRef })).toBeNull() + set({ draft: 'git@github.com:acme/plugins.git' }) + expect(add.hasAttribute('disabled')).toBe(false) + expect(dialog.getByRole('textbox', { name: en.sourceUrl })).toBe(address) + fireEvent.change(dialog.getByRole('textbox', { name: en.sourcePath }), { target: { value: 'market/index.json' } }) + fireEvent.change(dialog.getByRole('textbox', { name: en.sourceRef }), { target: { value: 'main' } }) + expect(actions.editSourceOptions).toHaveBeenNthCalledWith(1, { path: 'market/index.json' }) + expect(actions.editSourceOptions).toHaveBeenNthCalledWith(2, { ref: 'main' }) + set({ draft: 'https://raw.githubusercontent.com/acme/plugins/main/index.json' }) + expect(dialog.queryByRole('textbox', { name: en.sourcePath })).toBeNull() + expect(dialog.queryByRole('textbox', { name: en.sourceRef })).toBeNull() + }) + it('renders the Chinese copy and dates', () => { renderTab({}, zh) expect(screen.getByRole('button', { name: '切换插件索引,当前为 甲索引' })).toBeTruthy() diff --git a/packages/client/ui-plugin-market/tests/market-store.client.spec.ts b/packages/client/ui-plugin-market/tests/market-store.client.spec.ts index 72c4a86095..3c974ff886 100644 --- a/packages/client/ui-plugin-market/tests/market-store.client.spec.ts +++ b/packages/client/ui-plugin-market/tests/market-store.client.spec.ts @@ -157,6 +157,82 @@ describe('DiscoverController', () => { expect(snapshot()).toMatchObject({ editing: false, selected: null, listing: null }) }) + it('saves an ambiguous HTTPS address directly and honors an explicit Git address', async () => { + const { face, market, snapshot } = setup([{ url: A }]) + face.ensure() + await vi.waitFor(() => { expect(snapshot().status).toBe('ready') }) + const address = 'https://git.example/acme/plugins' + face.editDraft(address) + face.addSource() + await vi.waitFor(() => { expect(snapshot()).toMatchObject({ selected: address, saving: false }) }) + expect(market.setIndexes).toHaveBeenCalledWith([A, address]) + face.editDraft(`git+${address}`) + face.editSourceOptions({ path: 'market/index.json', ref: 'main' }) + face.addSource() + const source = `git+${address}?path=market%2Findex.json&ref=main` + await vi.waitFor(() => { expect(snapshot()).toMatchObject({ selected: source, saving: false }) }) + expect(market.setIndexes).toHaveBeenLastCalledWith([A, address, source]) + expect(snapshot()).toMatchObject({ draft: '', sourceOptions: { path: '', ref: '' } }) + }) + + it('saves a GitHub repository address with the default index path and ref', async () => { + const { face, market, snapshot } = setup([{ url: A }]) + face.ensure() + await vi.waitFor(() => { expect(snapshot().status).toBe('ready') }) + face.editDraft('https://github.com/acme/plugins') + face.addSource() + expect(market.setIndexes).toHaveBeenCalledWith([A, 'git+https://github.com/acme/plugins.git']) + await vi.waitFor(() => { expect(snapshot().saving).toBe(false) }) + }) + + it('keeps a Git source draft with an invalid file path', () => { + const { face, market, snapshot } = setup([]) + const address = 'https://github.com/acme/plugins' + face.editDraft(address) + face.editSourceOptions({ path: '../index.json' }) + face.addSource() + expect(snapshot()).toMatchObject({ draft: address, sourceOptions: { path: '../index.json' }, sourceFailure: { kind: 'invalid-git' } }) + expect(market.setIndexes).not.toHaveBeenCalled() + }) + + it('keeps the Git draft and its file options when the Host rejects the source', async () => { + const { face, market, snapshot } = setup([]) + face.ensure() + await vi.waitFor(() => { expect(snapshot().status).toBe('ready') }) + const address = 'git@github.com:acme/plugins.git' + const source = 'git+ssh://git@github.com/acme/plugins.git?path=market%2Findex.json&ref=main' + market.setIndexes.mockImplementationOnce(() => fail('plugin-market/invalid-index-url', 'Invalid source', { url: source, reason: 'git-source' })) + face.editDraft(address) + face.editSourceOptions({ path: 'market/index.json', ref: 'main' }) + face.addSource() + await vi.waitFor(() => { expect(snapshot().sourceFailure).toEqual({ kind: 'invalid-git' }) }) + expect(market.setIndexes).toHaveBeenCalledWith([source]) + expect(snapshot()).toMatchObject({ saving: false, draft: address, sourceOptions: { path: 'market/index.json', ref: 'main' } }) + }) + + it('blocks another source edit until the saved list has been read back', async () => { + const { face, market, snapshot } = setup([{ url: A }]) + face.ensure() + await vi.waitFor(() => { expect(snapshot().listing?.status).toBe('ready') }) + const save = Promise.withResolvers<{ ok: true; value: undefined }>() + const reload = Promise.withResolvers<{ ok: true; value: MarketIndexSummary[] }>() + market.setIndexes.mockImplementationOnce(() => save.promise) + market.listIndexes.mockImplementationOnce(() => reload.promise) + face.editDraft(B) + face.addSource() + face.removeSource(A) + expect(market.setIndexes).toHaveBeenCalledExactlyOnceWith([A, B]) + save.resolve({ ok: true, value: undefined }) + await vi.waitFor(() => { expect(market.listIndexes).toHaveBeenCalledTimes(2) }) + face.removeSource(A) + expect(market.setIndexes).toHaveBeenCalledTimes(1) + reload.resolve({ ok: true, value: [{ url: A }, { url: B }] }) + await vi.waitFor(() => { expect(snapshot()).toMatchObject({ saving: false, selected: B }) }) + face.removeSource(A) + expect(market.setIndexes).toHaveBeenLastCalledWith([B]) + await vi.waitFor(() => { expect(snapshot().saving).toBe(false) }) + }) + it.each([ ['plugin-market/invalid-index-url', { url: 'x', reason: 'scheme' }, { kind: 'invalid' }], ['plugin-market/invalid-index-url', { url: 'x', reason: 'duplicate' }, { kind: 'duplicate' }], @@ -167,10 +243,10 @@ describe('DiscoverController', () => { face.ensure() await vi.waitFor(() => { expect(snapshot().status).toBe('ready') }) market.setIndexes.mockImplementationOnce(() => fail(code, 'broken', details)) - face.editDraft('x') + face.editDraft(B) face.addSource() await vi.waitFor(() => { expect(snapshot().sourceFailure).toEqual(expected) }) - expect(snapshot()).toMatchObject({ saving: false, draft: 'x' }) + expect(snapshot()).toMatchObject({ saving: false, draft: B }) face.editDraft('y') expect(snapshot().sourceFailure).toBeNull() }) @@ -216,6 +292,23 @@ describe('DiscoverController', () => { expect(snapshot().listing?.status).toBe('loading') }) + it('drops the source-list readback when Discover is disposed after saving', async () => { + const { controller, face, market, snapshot } = setup([{ url: A }]) + face.ensure() + await vi.waitFor(() => { expect(snapshot().listing?.status).toBe('ready') }) + const reload = Promise.withResolvers<{ ok: true; value: MarketIndexSummary[] }>() + market.listIndexes.mockImplementationOnce(() => reload.promise) + face.editDraft(B) + face.addSource() + await vi.waitFor(() => { expect(market.listIndexes).toHaveBeenCalledTimes(2) }) + controller.dispose() + const before = snapshot() + reload.resolve({ ok: true, value: [{ url: A }, { url: B }] }) + await reload.promise + await Promise.resolve() + expect(snapshot()).toBe(before) + }) + it('sends the query text, filters, and order, and starts each index with the initial query', async () => { const { face, market, snapshot } = setup() face.ensure() diff --git a/packages/client/ui-plugin-market/tests/presentation.client.spec.ts b/packages/client/ui-plugin-market/tests/presentation.client.spec.ts index 94ad6c7c84..739704a729 100644 --- a/packages/client/ui-plugin-market/tests/presentation.client.spec.ts +++ b/packages/client/ui-plugin-market/tests/presentation.client.spec.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from 'vitest' import type { MarketListingEntry, MarketListingVersion } from '@deepseek-ai/dsh-api-remotes/client' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' -import { declaredQuery, displayDeclarations, indexLabel, INITIAL_QUERY, presentedVersion, sourceFacts, withText } from '../src/client/presentation.ts' +import { + declaredQuery, displayDeclarations, indexLabel, indexMenuItems, INITIAL_QUERY, presentedVersion, sourceFacts, withText, +} from '../src/client/presentation.ts' const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en @@ -80,3 +82,61 @@ describe('indexLabel', () => { expect(indexLabel({ url: 'https://[' }, resolveText)).toBe('https://[') }) }) + +describe('indexMenuItems', () => { + it.each([ + 'git+https://github.com/acme/plugins.git?path=market%2Findex.json&ref=main', + 'git+ssh://git@github.com/acme/plugins.git', + ])('uses the GitHub repository in the toolbar for %s', (url) => { + const index = { url, title: { en: 'Internal plugins', zh: '内部插件' } } + expect(indexMenuItems([index], resolveText)).toEqual([{ id: url, label: 'github:acme/plugins' }]) + expect(indexLabel(index, resolveText)).toBe('内部插件') + }) + + it('preserves localized Raw titles and distinguishes matching titles by their Raw locations', () => { + const main = 'https://raw.githubusercontent.com/acme/plugins/refs/heads/main/index.json' + const next = 'https://raw.githubusercontent.com/acme/plugins/refs/heads/next/index.json' + const release = 'https://raw.githubusercontent.com/acme/plugins/refs/heads/release/stable/index.json' + const title = { en: 'Official plugins', zh: '官方插件' } + expect(indexMenuItems([{ url: main, title }, { url: next, title }, { url: release }], resolveText)).toEqual([ + { id: main, label: '官方插件 · github:acme/plugins · refs/heads/main/index.json' }, + { id: next, label: '官方插件 · github:acme/plugins · refs/heads/next/index.json' }, + { id: release, label: 'github:acme/plugins' }, + ]) + }) + + it('distinguishes same-repository Git indexes by path and ref', () => { + const root = 'git+https://github.com/acme/plugins.git' + const customPath = `${root}?path=market%2Findex.json` + const customRef = `${customPath}&ref=release%2Fstable` + expect(indexMenuItems([{ url: root }, { url: customPath }, { url: customRef }], resolveText)).toEqual([ + { id: root, label: 'github:acme/plugins · HEAD:index.json' }, + { id: customPath, label: 'github:acme/plugins · HEAD:market/index.json' }, + { id: customRef, label: 'github:acme/plugins · release/stable:market/index.json' }, + ]) + }) + + it('distinguishes matching Raw locations without putting URL query strings in labels', () => { + const raw = 'https://raw.githubusercontent.com/acme/plugins/main/index.json' + const first = `${raw}?token=one` + const second = `${raw}?token=two` + expect(indexMenuItems([{ url: first }, { url: second }], resolveText)).toEqual([ + { id: first, label: 'github:acme/plugins · main/index.json (1)' }, + { id: second, label: 'github:acme/plugins · main/index.json (2)' }, + ]) + }) + + it('uses the regular index label when the address does not identify a GitHub index', () => { + const indexes = [ + { url: 'git+https://git.example/acme/plugins.git', title: 'Internal plugins' }, + { url: 'https://github.com/acme/plugins', title: 'Direct index' }, + { url: 'git+https://github.com/acme', title: 'Invalid Git source' }, + { url: 'git+https://github.com/acme/plugins.git?token=secret' }, + { url: 'https://raw.githubusercontent.com/acme/plugins/main' }, + { url: 'https://[' }, + ] + expect(indexMenuItems(indexes, resolveText).map(item => item.label)).toEqual([ + 'Internal plugins', 'Direct index', 'Invalid Git source', 'github.com', 'raw.githubusercontent.com', 'https://[', + ]) + }) +}) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index ee7d075165..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: 11686b52743a702d - zh: d865bb79d8f56ee1 + en: 07574e4640e01163 + zh: cc3f074a6ec0a17d /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: - en: 69acdb3375548a62 - zh: c392c11faf88938f + 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 8f5d76e6ef..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,7 +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. | +| `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. | @@ -79,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. | @@ -90,14 +93,16 @@ Four pairs are easy to confuse: - **`Tag` against `Pill`.** Reach for `Tag` for a read-only badge at the 11px capsule size, and for `Pill` when the capsule is selectable (`active` and `onClick`, as view switchers and filters use) or when it must sit on a 24px text line — `TerminalBlock` renders its exit status as a static `Pill` for exactly that reason. Size decides as much as interactivity here; the two are not interchangeable. - **`Pill` against `SegmentedControl`.** A row of `Pill`s is a set of independent chips — each one toggles on its own, and several may be active. `SegmentedControl` is one choice among a few mutually exclusive modes, drawn as a tablist with one indicator, and it comes with the tab keyboard pattern (arrow keys walk the segments, only the selected one is in the tab sequence); the Models settings add card switches its two forms with it. -- **`DisclosureRow` against a card.** The row lays its title and content side by side at a fixed 24px. A card that stacks a name over a description is a different layout, and belongs in the feature package — `ui-settings-plugins`' `PluginCard` is the precedent and records why. +- **`DisclosureRow` against a card.** The row lays its title and content side by side at a fixed 24px. A card that stacks a name over a description is a different layout, and belongs in the feature package — `ui-plugin-manager`'s `CardHead` is the precedent. - **`FoldToggle` against the exported surface.** It is package-internal and not exported; the output cards use it for their head-tail fold. Writing your own component in your own package is fine when the need is genuinely specific. What is not fine is copying a control that already exists here — and once a second package needs the same control, it belongs in this package. ### 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. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. 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. @@ -133,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 @@ -144,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. @@ -161,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 0cde331f8b..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,7 +67,7 @@ kind: "package-library" | `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。`tone="warning"` 在标题中显示橙色警告图标,并移除正文额外的顶部间距;其他弹窗的间距保持不变。 | | `RiskConfirmation` | 以显式复选框把关的敏感操作确认,采用共用的警告标题布局。 | | `Tooltip` | 锚定在克隆子元素上的悬停与键盘聚焦提示;可选的 `delayMs` 控制悬停延迟,`focusDelayMs` 控制键盘聚焦延迟,均默认为 0 毫秒。可通过 `portal` 渲染到外层,避免被容器裁剪,或受祖先层叠上下文限制其 z-index。 | -| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。 | +| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。紧凑卡片出现在锚点结束一侧;会超出视口结束边缘、而开始一侧放得下时出现在开始一侧,例如窗口末端面板中的行;两侧都放不下时出现在锚点下方,与锚点的开始边缘对齐,下方放不下则出现在上方,因此不会盖住锚点;高到上下都放不下的卡片留在视口内,位于底部结束一角。它由 CSS 锚点定位放置,卡片跟随锚点时不需要脚本测量;Firefox 解析锚点位置时不计入祖先元素的 transform,锚点位于带 transform 的祖先之内时,紧凑卡片在 Firefox 中的位置会偏移。 | | `DraggableImage` | 通过显式传递与反馈回调提供原图拖放。 | | `ImageLightbox` | 共享图片浮层,支持焦点恢复与 Esc 关闭。 | | `usePointerGrace` | 可取消的延迟关闭,让指针能够跨越触发控件与卡片间的空隙;卸载时清除待执行定时器。 | @@ -79,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 浏览器与文件夹插画,用于侧栏引导入口。 | @@ -90,14 +93,16 @@ kind: "package-library" - **`Tag` 与 `Pill`。** 11px 胶囊尺寸的只读徽章用 `Tag`;胶囊可选中(`active` 与 `onClick`,视图切换与筛选器就是这样用的),或者必须落在 24px 文本行上时用 `Pill`——`TerminalBlock` 把退出状态渲染成静态 `Pill` 正是后一种情况。这里尺寸和是否可交互同样是判据,两者不可互换。 - **`Pill` 与 `SegmentedControl`。** 一排 `Pill` 是一组彼此独立的 chip——每个各自开关,可以同时激活多个。`SegmentedControl` 是在几种互斥模式中选一,画成带一个指示块的 tablist,并自带 tab 键盘模式(方向键在分段间移动,只有选中项在 Tab 序列里);模型设置页的新增卡片就用它切换两张表单。 -- **`DisclosureRow` 与卡片。** 该行以固定 24px 把标题与内容左右排列。把名称叠在描述之上的卡片是另一种布局,属于功能包——`ui-settings-plugins` 的 `PluginCard` 是先例,并记录了原因。 +- **`DisclosureRow` 与卡片。** 该行以固定 24px 把标题与内容左右排列。把名称叠在描述之上的卡片是另一种布局,属于功能包——`ui-plugin-manager` 的 `CardHead` 是先例。 - **`FoldToggle` 与对外导出面。** 它是包内组件,未导出;输出卡片用它做头尾折叠。 需求确实特殊时,在自己的包里写自己的组件没有问题。不可以的是复制这里已有的控件——而当第二个包需要同一个控件时,它就该住进本包。 ### 控件与图标 -上面的目录说明每个导出的用途;本节讲 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 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 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 元素横向溢出才显示气泡,因此重复被省略号截断文本的标签只在能补充信息时出现。 @@ -133,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 动画与弹窗生命周期计时。普通下拉菜单不经过右键菜单的准备延迟。 ----- +行内链接保留图标完整布局框,按当前字体的大写字母高度中心定位,并保留段落内自然换行。没有说明的弹窗缩短标题至正文的距离;关闭按钮外框与正文及页尾操作共用尾端边缘,图标在较大的点击热区内居中。风险说明与确认勾选共用前导槽和文字起点。 + ## 理解实现 @@ -144,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)` 与非触摸指针事件,所以主指针为触摸时,外接鼠标或笔仍可展开子级。兼容鼠标悬停事件不会展开或收起子级。指针宽限允许跨越卡片间隙;同级其他行会关闭原子级。宽限结束关闭子级时,仍在子级中的焦点会回到父项。父项被移除、禁用或其子项清空时,恢复根面板并取消该子菜单。留在被移除子级中的焦点会回到仍可用的父项、首个可用根菜单行或锚点;已经移到其他位置的焦点保持不变。 @@ -161,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 8135385a77..8e6396cbd9 100644 --- a/packages/client/ui-primitives/package.json +++ b/packages/client/ui-primitives/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-primitives", "description": "Pure React atoms for the dsh web UI: controls, icons, markdown, and JSON inspectors (zero cordis)", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -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/clipboard.ts b/packages/client/ui-primitives/src/clipboard.ts index aa45f4c76d..c0cf711c2c 100644 --- a/packages/client/ui-primitives/src/clipboard.ts +++ b/packages/client/ui-primitives/src/clipboard.ts @@ -1,10 +1,28 @@ // Host clipboard write shared by Web UI copy controls. Success feedback stays -// with each control; this helper only reports whether the host accepted a write. +// with each control; this helper reports whether the host accepted a write and +// leaves focus where it found it. + +/** + * Attempt the async Clipboard API write. + * @param text - the exact text to place on the clipboard. + * @returns true only when the host accepted the write. + */ +async function writeWithClipboardApi(text: string): Promise { + try { + await navigator.clipboard.writeText(text) + } catch (_error) { + // A denied permission can block the async API while execCommand still works; the caller tries it below. + return false + } + return true +} /** * Write text to the host clipboard, preferring the async Clipboard API and - * falling back to `execCommand('copy')` on hosts (jsdom, insecure contexts) - * that omit it. + * falling back to `execCommand('copy')` when that API is missing (jsdom, + * insecure contexts) or refuses the write (for example, a denied clipboard + * permission). The fallback replaces the page selection and succeeds only while + * the triggering user gesture's transient activation is still valid. * @param text - the exact text to place on the clipboard. * @returns true only when the host accepted the write. */ @@ -12,36 +30,32 @@ export async function writeClipboard(text: string): Promise { // lib.dom types clipboard non-optional, but insecure contexts omit it — // that runtime gap is exactly what this guard detects. /* oxlint-disable-next-line typescript/no-unnecessary-condition */ - if (navigator.clipboard?.writeText) { - try { - await navigator.clipboard.writeText(text) - return true - } catch { - // Denied permissions / iframe policy — do not claim success. - return false - } + if (typeof navigator.clipboard?.writeText === 'function') { + if (await writeWithClipboardApi(text)) return true } - // jsdom and older hosts: best-effort execCommand path when present. // execCommand('copy') is the only clipboard fallback where the async API - // is missing; deprecated but deliberately retained. + // is missing or refused; deprecated but deliberately retained. /* oxlint-disable typescript/no-deprecated */ const exec = typeof document.execCommand === 'function' ? document.execCommand.bind(document) : undefined if (exec === undefined) return false + // Selecting the textarea moves focus; return it so a keyboard user stays on the copy control. + const focused = document.activeElement const el = document.createElement('textarea') el.value = text el.setAttribute('readonly', '') el.style.position = 'fixed' el.style.left = '-9999px' - document.body.appendChild(el) - el.select() try { + document.body.appendChild(el) + el.select() return exec('copy') } catch { return false } finally { el.remove() + if (focused instanceof HTMLElement) focused.focus({ preventScroll: true }) } /* oxlint-enable typescript/no-deprecated */ } diff --git a/packages/client/ui-primitives/src/icons/artwork.ts b/packages/client/ui-primitives/src/icons/artwork.ts index dc438249f4..4f6f1e3b26 100644 --- a/packages/client/ui-primitives/src/icons/artwork.ts +++ b/packages/client/ui-primitives/src/icons/artwork.ts @@ -20,100 +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 => `` }, - '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 => `` }, @@ -122,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 4bb49d1352..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. */ @@ -318,6 +318,12 @@ export const IconDownloadOutlineRegular = productIcon('download-outline', 'regul /** Medium IconDownloadOutline artwork with a 1.3px stroke. */ export const IconDownloadOutlineMedium = productIcon('download-outline', 'medium') +/** Regular one-pixel IconUploadOutline artwork: the download tray with the arrow pointing up. */ +export const IconUploadOutlineRegular = productIcon('upload-outline', 'regular') + +/** Medium IconUploadOutline artwork with a 1.3px stroke. */ +export const IconUploadOutlineMedium = productIcon('upload-outline', 'medium') + /** Regular one-pixel IconPlayOutline artwork. */ export const IconPlayOutlineRegular = productIcon('play-outline', 'regular') @@ -456,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') @@ -486,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. */ @@ -555,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 44dbcd8871..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' @@ -92,7 +94,6 @@ export type { export { CODE_HIGHLIGHT_EXTENSIONS, languageForPath, useCodeHighlighter } from './code-highlighting.ts' export type { CodeHighlighter, HighlightSpan } from './code-highlighting.ts' export { relativeTime } from './relative-time.ts' -export { rankByName } from './rank-by-name.ts' export { isDarwinDesktop } from './darwin-desktop.ts' export type { RelativeTime, RelativeTimeUnit } from './relative-time.ts' export { JsonTree } from './JsonTree.tsx' 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/rank-by-name.ts b/packages/client/ui-primitives/src/rank-by-name.ts deleted file mode 100644 index 2f7bdd880f..0000000000 --- a/packages/client/ui-primitives/src/rank-by-name.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Shared ranking for `/` menu candidates: the query must be a - * case-insensitive ordered subsequence of the candidate name or, when the - * candidate carries one, of its display label (a localized title). Prefix - * hits rank first, then the strongest alignment score over either key, then - * the source order of the input. Decision record: - * .agents/notes/archived/feature/2026-08-04-web-slash-command-fuzzy-discovery.md - */ - -/** One match with its stable source position. */ -interface Ranked { - readonly item: T - readonly index: number - readonly prefix: boolean - readonly score: number -} - -/** Extra weight for name starts and separator boundaries. */ -function boundaryBonus(name: string, index: number): number { - return index === 0 || name.charAt(index - 1) === '-' || name.charAt(index - 1) === '_' ? 8 : 0 -} - -/** - * Score the strongest ordered-subsequence alignment in O(name × query). - * Boundary and adjacent matches earn weight; skipped and leading characters - * cost weight. Undefined when the query is not a subsequence of the name. - */ -function alignmentScore(name: string, query: string): number | undefined { - if (query.length > name.length) return undefined - const noMatch = Number.NEGATIVE_INFINITY - let previous = Array(name.length).fill(noMatch) - for (let index = 0; index < name.length; index++) { - if (name.charAt(index) === query.charAt(0)) previous[index] = 1 + boundaryBonus(name, index) - index - } - for (let queryIndex = 1; queryIndex < query.length; queryIndex++) { - const current = Array(name.length).fill(noMatch) - // Sweep the previous row once: `left` is its score one character back - // (the adjacent continuation), `leftLeft` two back (the earliest gapped one). - let left = noMatch - let leftLeft = noMatch - let bestGapped = noMatch - for (const [index, prior] of previous.entries()) { - if (leftLeft !== noMatch) bestGapped = Math.max(bestGapped, leftLeft + index - 2) - if (name.charAt(index) === query.charAt(queryIndex)) { - const bonus = 1 + boundaryBonus(name, index) - let score = noMatch - if (left !== noMatch) score = left + bonus + 4 - if (bestGapped !== noMatch) score = Math.max(score, bestGapped + bonus + 1 - index) - current[index] = score - } - leftLeft = left - left = prior - } - previous = current - } - let best = noMatch - for (const score of previous) best = Math.max(best, score) - return best === noMatch ? undefined : best -} - -/** - * Rank named items by a menu query. - * @param items - candidates in source order (a host catalog, then client - * contributions); an item's optional `label` is a second search key beside - * its name. - * @param rawQuery - the text typed after the trigger, matched case-insensitively. - * @returns the matching items: prefix hits first, then by alignment score, - * then in source order. The input list itself for an empty query. - */ -export function rankByName( - items: readonly T[], - rawQuery: string, -): readonly T[] { - const query = rawQuery.toLowerCase() - if (query === '') return items - const ranked: Ranked[] = [] - items.forEach((item, index) => { - const keys = item.label === undefined ? [item.name] : [item.name, item.label] - let prefix = false - let score: number | undefined - for (const key of keys) { - const lower = key.toLowerCase() - const keyScore = alignmentScore(lower, query) - if (keyScore === undefined) continue - prefix ||= lower.startsWith(query) - score = score === undefined ? keyScore : Math.max(score, keyScore) - } - if (score !== undefined) ranked.push({ item, index, prefix, score }) - }) - ranked.sort((left, right) => - Number(right.prefix) - Number(left.prefix) || right.score - left.score || left.index - right.index) - return ranked.map(match => match.item) -} 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/rank-by-name.client.spec.ts b/packages/client/ui-primitives/tests/rank-by-name.client.spec.ts deleted file mode 100644 index 027fbb4958..0000000000 --- a/packages/client/ui-primitives/tests/rank-by-name.client.spec.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Shared `/` menu ranker: case-insensitive ordered-subsequence matching, - * prefix hits first, alignment score next, source order for ties. - */ -import { describe, expect, it } from 'vitest' -import { rankByName } from '@deepseek-ai/dsh-client-ui-primitives' - -const named = (...names: string[]) => names.map(name => ({ name })) -const names = (items: readonly { name: string }[]) => items.map(item => item.name) - -describe('rankByName', () => { - it('returns the input list itself for an empty query', () => { - const items = named('b', 'a') - expect(rankByName(items, '')).toBe(items) - }) - - it('matches case-insensitive subsequences and ranks prefixes, boundaries, adjacency, gaps, then source order', () => { - const items = named('q-xylophone', 'qx-long', 'fabulous', 'foo-bar', 'zuv', 'zu1v', 'yu1v', 'zu12v') - expect(names(rankByName(items, 'QX'))).toEqual(['qx-long', 'q-xylophone']) - expect(names(rankByName(items, 'fb'))).toEqual(['foo-bar', 'fabulous']) - expect(names(rankByName(items, 'uv'))).toEqual(['zuv', 'zu1v', 'yu1v', 'zu12v']) - expect(names(rankByName(items, 'zzz'))).toEqual([]) - expect(names(rankByName(items, 'query-longer-than-every-name'))).toEqual([]) - }) - - it('a prefix hit outranks a stronger non-prefix alignment', () => { - // 'z_a_b' aligns both characters on separator boundaries and outscores - // every non-prefix rival; a name that starts with the query still wins. - expect(names(rankByName(named('z_a_b', 'xabc'), 'ab'))).toEqual(['z_a_b', 'xabc']) - expect(names(rankByName(named('z_a_b', 'abc'), 'ab'))).toEqual(['abc', 'z_a_b']) - }) - - it('takes the stronger of an adjacent and a gapped alignment for the same character', () => { - expect(names(rankByName(named('aab', 'ab'), 'ab'))).toEqual(['ab', 'aab']) - }) - - it('matches the display label as a second key and keeps the stronger alignment', () => { - const items = [ - { name: 'goal', label: '目标' }, - { name: 'plan', label: '计划' }, - { name: 'permission', label: '权限' }, - ] - expect(names(rankByName(items, '目标'))).toEqual(['goal']) - expect(names(rankByName(items, 'goal'))).toEqual(['goal']) - expect(names(rankByName(items, 'p'))).toEqual(['plan', 'permission']) - expect(names(rankByName(items, '划'))).toEqual(['plan']) - // A label prefix hit ranks like a name prefix hit. - expect(names(rankByName([{ name: 'xplan', label: 'plan' }, { name: 'plant' }], 'pla'))).toEqual(['xplan', 'plant']) - }) - - it('returns the ranked items with their payload intact', () => { - const items = [{ name: 'goal', description: 'g' }, { name: 'plan', description: 'p' }] - expect(rankByName(items, 'pl')).toEqual([{ name: 'plan', description: 'p' }]) - }) -}) diff --git a/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx index b801dd6e91..5a6dbd9567 100644 --- a/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx @@ -448,14 +448,32 @@ describe('writeClipboard', () => { expect(writeText).toHaveBeenCalledWith('payload') }) - it('reports false when the Clipboard API rejects', async () => { + it('reports false when the Clipboard API rejects and no fallback exists', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined }) await expect(writeClipboard('payload')).resolves.toBe(false) }) + it('falls back to execCommand when the Clipboard API rejects', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }) + let selected: string | undefined + const exec = vi.fn(() => { + selected = document.querySelector('textarea[readonly]')?.value + return true + }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: exec }) + await expect(writeClipboard('payload')).resolves.toBe(true) + expect(exec).toHaveBeenCalledWith('copy') + expect(selected).toBe('payload') + expect(document.querySelector('textarea')).toBeNull() + }) + it('selects a detached textarea for the execCommand fallback and removes it after', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) let selected: string | undefined @@ -470,6 +488,25 @@ describe('writeClipboard', () => { expect(document.querySelector('textarea')).toBeNull() }) + it('returns focus to the copy control after the execCommand fallback', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => true) }) + const button = document.createElement('button') + document.body.appendChild(button) + button.focus() + await expect(writeClipboard('payload')).resolves.toBe(true) + expect(document.activeElement).toBe(button) + button.remove() + }) + + it('copies through the fallback when nothing had focus', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => true) }) + const activeElement = vi.spyOn(document, 'activeElement', 'get').mockReturnValue(null) + await expect(writeClipboard('payload')).resolves.toBe(true) + activeElement.mockRestore() + }) + it('reports execCommand\'s own refusal verbatim', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => false) }) 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/package.json b/packages/client/ui-reference/package.json index 57ba4eba16..ca3240f4be 100644 --- a/packages/client/ui-reference/package.json +++ b/packages/client/ui-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-reference", "description": "Unified Web @file and @session reference source", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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..efab708f13 --- /dev/null +++ b/packages/client/ui-reference/src/client/context-menu.ts @@ -0,0 +1,51 @@ +/** File references contributed to the shared file menu. */ +import type { Context } from '@deepseek-ai/cordis' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' +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(sessionDirectory(ctx.sessions, target.sessionId), 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..ff58b82471 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. @@ -21,10 +26,14 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' 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 +43,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 +55,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,21 +65,29 @@ 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 => ({ - resolveFilePath: path => resolveWorkspacePath(sessions.list.getSnapshot().byId[sessionId]?.cwd, path), + ...presenceFor(sessionId), + resolveFilePath: path => resolveWorkspacePath(sessionDirectory(sessions, sessionId), path), openFile: (path) => { - const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd - ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path)) + ctx.sidebarRight.openResource(fileAddressFor(sessionId, sessionDirectory(sessions, sessionId), path)) }, }), }, 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,9 +184,8 @@ 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 cwd = sessions.list.getSnapshot().byId[session.sessionId]?.cwd - ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, cwd, path)) + const path = mentionPath(ref) + ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, sessionDirectory(sessions, session.sessionId), path)) return true }, codec: { 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')! @@ -688,7 +728,7 @@ describe('reference preview', () => { const file = factory(session.sessionId) await sessions.updateSummary(session.sessionId, { cwd: '/workspace' }) await sessions.setProjection(session.sessionId, 'workingDirectory', '/workspace/elsewhere') - expect(file.resolveFilePath('docs/a b.md')).toBe('/workspace/docs/a b.md') + expect(file.resolveFilePath('docs/a b.md')).toBe('/workspace/elsewhere/docs/a b.md') expect(factory(sid('other')).resolveFilePath('/absolute.md')).toBe('/absolute.md') expect(openResource.mock.calls).toEqual([ ['dsh-resource://file/session/target/docs/a%20b.md'], 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..8d654b45fa --- /dev/null +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -0,0 +1,220 @@ +// @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('resolves the captured path against the directory the Session works in', async () => { + const b = await bench() + await b.runtime.sessions.setProjection(id, 'workingDirectory', '/workspace/elsewhere') + const menu = await b.menu() + menu.select(actionId) + expect(b.shell.snapshot.draft).toBe('@"/workspace/elsewhere/docs/a b.md" ') +}) + +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-renderer/package.json b/packages/client/ui-renderer/package.json index e386a6d22b..f23fad3028 100644 --- a/packages/client/ui-renderer/package.json +++ b/packages/client/ui-renderer/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-renderer", "description": "Browser UI renderer: React slot bindings, ctx.uiRenderer, and the assembled application root", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-renderer/src/client/registry.ts b/packages/client/ui-renderer/src/client/registry.ts index 4c3f520c8a..a3e7b3e8c6 100644 --- a/packages/client/ui-renderer/src/client/registry.ts +++ b/packages/client/ui-renderer/src/client/registry.ts @@ -97,6 +97,7 @@ interface ErasedRegisterOptions { /** Declared dictionary namespace (the renderer synthesizes the `t` seat from it). */ locale?: string registrant?: string + module?: string } interface ErasedFactoryOptions { @@ -116,6 +117,29 @@ interface ErasedFactoryCore { registerFactory(options: object, component: unknow /** One synchronous effect installed while an injected slot declaration is live. */ type SlotInjectionEffect = (() => void) | Iterable<() => void, void, void> +/** + * Name the Loader entry that owns a calling Context: the nearest fiber, walking + * up through nested plugins, that the Loader attached an entry to. + * @param ctx - the caller's Context. + * @returns the entry's module name, which the client module system sets to the package name. + */ +function entryName(ctx: Context): string | undefined { + // The Loader augments fibers with `entry`; this package does not depend on the Loader's types. + let fiber = ctx.fiber as EntryFiber + for (;;) { + if (fiber.entry !== undefined) return fiber.entry.options.name + const parent = fiber.parent.fiber + if (parent === fiber) return undefined + fiber = parent + } +} + +/** The fiber members {@link entryName} reads: the Loader's entry and the parent chain ending at the root fiber. */ +interface EntryFiber { + readonly entry?: { readonly options: { readonly name: string } } | undefined + readonly parent: { readonly fiber: EntryFiber } +} + /** cordis Service layer of the slot system; see the module doc for the split with SlotCore. */ export class SlotRegistry extends Service { private readonly _core = new SlotCore() @@ -479,10 +503,12 @@ export class SlotRegistry extends Service { // core's shared-handle scope pinning applies to it harmlessly). const store = typeof options.store === 'function' ? options.store() : options.store const registrant = options.registrant ?? (this.ctx.fiber as { name?: string } | undefined)?.name + const module = entryName(this.ctx) const erased: ErasedRegisterOptions = { ...options, ...(store !== undefined ? { store } : {}), ...(registrant !== undefined ? { registrant } : {}), + ...(module !== undefined ? { module } : {}), } // Core write first: all load-time validation (undeclared target, // duplicate declaration, kind conflicts, cross-scope handle) throws diff --git a/packages/client/ui-renderer/tests/registry.client.spec.ts b/packages/client/ui-renderer/tests/registry.client.spec.ts index 43ee101f93..27de92ff74 100644 --- a/packages/client/ui-renderer/tests/registry.client.spec.ts +++ b/packages/client/ui-renderer/tests/registry.client.spec.ts @@ -245,6 +245,25 @@ describe('Factory definition ledger', () => { }) }) +describe('registering package', () => { + it('stamps the nearest Loader entry name, walking up through nested plugins, and nothing outside an entry', async () => { + const b = await boot() + b.erased.register({ name: 'root', children: { 't.rows': { kind: 'list', scope: 'root' } } }, C) + let outer: Context | undefined, inner: Context | undefined + await b.ctx.plugin({ inject: ['slots'], apply: (ctx: Context) => { + outer = ctx + ctx.plugin({ inject: ['slots'], apply: (child: Context) => { inner = child } }) + } }) + Object.assign(outer!.fiber, { entry: { options: { name: '@acme/dsh-rows' } } }) + inner!.slots.register({ name: 't.rows', id: 'nested' }, C) + outer!.slots.register({ name: 't.rows', id: 'outer' }, C) + b.erased.register({ name: 't.rows', id: 'root' }, C) + expect(b.svc.entries('t.rows').map(entry => [entry.options.id, entry.module])).toEqual([ + ['nested', '@acme/dsh-rows'], ['outer', '@acme/dsh-rows'], ['root', undefined], + ]) + }) +}) + describe("built-in 'root'", () => { it('is declared at construction: spec readable, occupancy open, no plugin needed', async () => { const bench = await boot() 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 @@ -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 8f17675697..ada7723808 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-subagent", "description": "Subagent conversation catalog, continuation routing UI, and '@' reference source", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -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..a191bb340e 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 } } } @@ -106,7 +106,7 @@ function subagentChatResourceProvider(sessions: ISessions): ResourceProvider<'su const address = parseSubagentChatAddress(resourceAddress) if (address === undefined) throw new Error(`ui-subagent: invalid chat resource address "${resourceAddress}"`) if (isAbortRequested(signal)) return - const reference = sessions.retain(address, { source: 'sidebarChat', signal }) + const reference = sessions.retain(address, { source: 'sidebarChat', facets: { conversation: true }, signal }) try { yield { ok: true, value: { address, reference } } await waitForAbort(signal) @@ -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(<>
    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/package.json b/packages/client/ui-schedule/package.json index 066f1ec561..4155b140ce 100644 --- a/packages/client/ui-schedule/package.json +++ b/packages/client/ui-schedule/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-schedule", "description": "Host task management page and Session reminder catalog", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", @@ -81,7 +81,8 @@ "clsx": "^2.1.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "@deepseek-ai/dsh-util-text-search": "workspace:*" }, "files": [ "locale/*.json", 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/RuleSelectRow.tsx b/packages/client/ui-schedule/src/client/RuleSelectRow.tsx index f8dc4cea94..4ba61c24b2 100644 --- a/packages/client/ui-schedule/src/client/RuleSelectRow.tsx +++ b/packages/client/ui-schedule/src/client/RuleSelectRow.tsx @@ -4,6 +4,7 @@ import type { ReactNode } from 'react' import clsx from 'clsx' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import { IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' import { TaskMenu } from './TaskMenu.tsx' import type { TaskMenuEntry } from './TaskMenu.tsx' import { zoneChoices, zoneName } from './schedule-format.ts' @@ -56,10 +57,21 @@ export function RuleZoneRow({ value, disabled, onChange, t }: PropsLocale<'sched } return [...byLabel.values()] }, [value, systemZone, t]) - const normalized = query.trim().toLocaleLowerCase(t('time.locale')) - const matches = catalog.filter(item => `${item.zones.join(' ')} ${item.label}`.toLocaleLowerCase(t('time.locale')).includes(normalized)) - .map(item => ({ ...item, id: item.zones.find(zone => zone.toLocaleLowerCase(t('time.locale')) === normalized) ?? item.id })) - const recentItems = normalized === '' ? recent.flatMap((zone) => { + // A row groups zones that share one label. The zone saved is the one the query + // names, by the same matching that kept the row; the row's own id wins only + // while the query names it or names no zone at all. The label answers query + // terms that name no zone, such as a localized city name. + const rowIndex = useMemo(() => new TextSearchIndex( + catalog.map(item => ({ item, zones: new TextSearchIndex(item.zones, zone => ({ fuzzy: [zone, item.label] })) })), + ({ item }) => ({ fuzzy: [...item.zones, item.label] }), + ), [catalog]) + const searching = query.trim() !== '' + const matches = rowIndex.search(query).map(({ item, zones }) => { + if (!searching) return item + const named = zones.search(query) + return { ...item, id: named.includes(item.id) ? item.id : named[0] ?? item.id } + }) + const recentItems = !searching ? recent.flatMap((zone) => { const item = catalog.find(item => item.zones.includes(zone)) return item === undefined ? [] : [{ ...item, id: zone }] }).filter((item, index, items) => items.findIndex(candidate => candidate.label === item.label) === index) : [] 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 53a53fe9d4..5ca57d5933 100644 --- a/packages/client/ui-schedule/src/client/TaskManagerPage.tsx +++ b/packages/client/ui-schedule/src/client/TaskManagerPage.tsx @@ -12,6 +12,7 @@ import type { ScheduleId, ScheduleCatalogEntry, ScheduleCreateRequest } from '@d import type { TaskCreateOutcome } from './TaskDetail.tsx' import type { TaskEditorStoreProps } from './editor-store.ts' import { taskNextRunAt, taskSessionId } from './task-record.ts' +import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' import type { CatalogSnapshot } from './catalog-source.ts' import { CatalogFeedback } from './CatalogFeedback.tsx' import { TaskDetail, useTaskDetail, type TaskDetailInjected } from './TaskDetail.tsx' @@ -19,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. */ @@ -30,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. * @@ -58,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) @@ -93,17 +101,15 @@ export function TaskManagerPage(props: TaskManagerPageProps) { () => records.filter(record => record.status === 'ended').length, [records], ) - const rows = useMemo(() => { - const query = search.trim().toLowerCase() - return records.filter(record => ( - (statusFilter === 'all' || record.status === statusFilter) - && (record.prompt.toLowerCase().includes(query) - || (taskSessionId(record) ?? '').toLowerCase().includes(query) - || taskName(record).toLowerCase().includes(query)) - )).toSorted((left, right) => - Date.parse(taskNextRunAt(left)) - Date.parse(taskNextRunAt(right))) - }, [records, search, statusFilter]) + const rowIndex = useMemo(() => new TextSearchIndex( + records.filter(record => statusFilter === 'all' || record.status === statusFilter) + .toSorted((left, right) => Date.parse(taskNextRunAt(left)) - Date.parse(taskNextRunAt(right))), + record => ({ fuzzy: [taskName(record)], substring: [taskSessionId(record), record.prompt] }), + ), [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' @@ -288,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 5d30c52d64..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(), @@ -1624,6 +1624,38 @@ describe('time zone menu', () => { expectSavedRule(h, 'DTSTART;TZID=Europe/Bucharest:20990101T090000\nRRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,WE') }) + it("keeps the row's own zone when a search names several zones of the row or none alone", () => { + pinSystemZone('UTC') + vi.mocked(Intl.supportedValuesOf).mockReturnValue(['Europe/Athens', 'Europe/Bucharest']) + // The stored zone makes Bucharest the shared row's own zone, while Athens is the row's first zone. + mount([{ ...task, rrule: task.rrule.replace('TZID=UTC', 'TZID=Europe/Bucharest') }]) + const detail = openEdit() + // `eur` names both zones; `athens bucharest` names neither zone with both terms. + for (const query of ['eur', 'athens bucharest']) { + openZones(detail) + searchZones(query) + fireEvent.click(screen.getByRole('menuitem', { name: zoneName('Europe/Bucharest', 'UTC', t) })) + expect((JSON.parse(localStorage.getItem(RECENT)!) as string[])[0]).toBe('Europe/Bucharest') + } + }) + + it('saves the zone a fuzzy or full-width search names inside a shared row', async () => { + pinSystemZone('UTC') + vi.mocked(Intl.supportedValuesOf).mockReturnValue(['Europe/Athens', 'Europe/Bucharest']) + expect(zoneName('Europe/Bucharest', 'UTC', t)).toContain('European') + // The last query's second term matches only the shared label, not a zone id. + for (const query of ['bchrst', 'BUCHAREST', 'bucharest european']) { + const h = mount() + const detail = openEdit() + openZones(detail) + searchZones(query) + fireEvent.click(screen.getByRole('menuitem', { name: zoneName('Europe/Bucharest', 'UTC', t) })) + await save(detail) + expectSavedRule(h, 'DTSTART;TZID=Europe/Bucharest:20990101T090000\nRRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,WE') + cleanup() + } + }) + it('offers the system zone alone without a separator and says when no zone matches', () => { pinSystemZone('UTC') mount() 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 b5e6187408..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(), @@ -706,6 +707,11 @@ describe('Task manager catalog', () => { expect(taskNames()).toEqual([]) fireEvent.change(input, { target: { value: 'numbers' } }) expect(taskNames()).toEqual(['Quarterly report']) + // Names match fuzzily; the long instruction matches only contiguous text. + fireEvent.change(input, { target: { value: 'qrtly' } }) + expect(taskNames()).toEqual(['Quarterly report']) + fireEvent.change(input, { target: { value: 'sndnum' } }) + expect(taskNames()).toEqual([]) }) it('combines search with the status filter and keeps both behind the empty state action', () => { @@ -834,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('') @@ -1791,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\);/) }) }) @@ -1820,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. @@ -1861,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. @@ -1889,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. @@ -1901,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/) @@ -1915,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\);/) @@ -1934,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\);/) @@ -2057,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) @@ -2070,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-schedule/tsconfig.json b/packages/client/ui-schedule/tsconfig.json index 09401d4291..304cfc91b7 100644 --- a/packages/client/ui-schedule/tsconfig.json +++ b/packages/client/ui-schedule/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../../util/text-search" + }, { "path": "../../api/session-controller/tsconfig.client.json" }, @@ -39,7 +42,7 @@ "path": "../ui-tool" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" }, { "path": "../ui-renderer" diff --git a/packages/client/ui-secret-mask/package.json b/packages/client/ui-secret-mask/package.json index e58278b6a8..75ac2897cb 100644 --- a/packages/client/ui-secret-mask/package.json +++ b/packages/client/ui-secret-mask/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-secret-mask", "description": "Web display masking for recognized credentials in sent user text", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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-settings-plugins/src/css-modules.d.ts b/packages/client/ui-session-panel/src/css-modules.d.ts similarity index 100% rename from packages/client/ui-settings-plugins/src/css-modules.d.ts rename to packages/client/ui-session-panel/src/css-modules.d.ts 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-settings-plugins/tsdown.config.ts b/packages/client/ui-session-panel/tsdown.config.ts similarity index 100% rename from packages/client/ui-settings-plugins/tsdown.config.ts rename to packages/client/ui-session-panel/tsdown.config.ts diff --git a/packages/client/ui-session-status/package.json b/packages/client/ui-session-status/package.json index f6856b6ebc..e0decb54f9 100644 --- a/packages/client/ui-session-status/package.json +++ b/packages/client/ui-session-status/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-session-status", "description": "Client Session status table over Host reading records: running state, the effective pending interaction, and read or unread reminders shared by clients of one Host", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-session-status/tests/status-controller.client.spec.ts b/packages/client/ui-session-status/tests/status-controller.client.spec.ts index 13ce251f13..72da186bc3 100644 --- a/packages/client/ui-session-status/tests/status-controller.client.spec.ts +++ b/packages/client/ui-session-status/tests/status-controller.client.spec.ts @@ -94,7 +94,7 @@ it('preserves unlisted child status through metadata updates and main view ackno await client.flush() expect(status.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: true }) - using reference = sessions.retain(childId, { source: 'mainView' }) + using reference = sessions.retain(childId, { source: 'mainView', facets: { conversation: true } }) await reference.ready expect(sessions.list.getSnapshot().ids).not.toContain(childId) mock.streams.push('sessionStatus/follow', { type: 'changed', state: { diff --git a/packages/client/ui-session/package.json b/packages/client/ui-session/package.json index 8aa051aca0..d8901a69bb 100644 --- a/packages/client/ui-session/package.json +++ b/packages/client/ui-session/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-session", "description": "Session Controller adapter for React and session-scoped slots", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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/package.json b/packages/client/ui-settings-account/package.json index 16bdf0111f..de257cfd5c 100644 --- a/packages/client/ui-settings-account/package.json +++ b/packages/client/ui-settings-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-account", "description": "Manage DeepSeek login and open Platform billing pages", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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-agent-loop/package.json b/packages/client/ui-settings-agent-loop/package.json index bf9b907b2d..41dce23dca 100644 --- a/packages/client/ui-settings-agent-loop/package.json +++ b/packages/client/ui-settings-agent-loop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-agent-loop", "description": "Settings page of the agent loop on the dsh web client's Plugins page: the parallel tool-call cap of the agent-loop namespace", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index a3e6d06c2b..a56b70ab37 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -15,8 +15,8 @@ en: 83760d53b3ee5fb8 zh: 30dd8802d4ffdcb7 /deepseek-ai-dsh-client-ui-settings-general/use-this-package: - en: 8ae337011190f5f3 - zh: 508eca60c6fcdc34 + en: 3f25debd8877c4bd + zh: 51f0c1d6924550f1 /deepseek-ai-dsh-client-ui-settings-general/use-this-package/the-general-section: en: de35e867b2a56d73 zh: 6d4e5c912636f889 @@ -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 a7782b0518..a12ef36089 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -29,7 +29,7 @@ In browsers below 768px viewport width, the panel fills the viewport and navigat ## Use this package -Users reach the shell through the sidebar's bottom Settings control; feature plugins contribute their pages and onboarding steps through the slot ledgers this shell projects. In both the expanded sidebar and collapsed rail, the control exposes the localized Settings label as its accessible name. A pale-yellow **Disconnected** action beside Settings indicates browser offline suspension; its permanent retry glyph marks the retry action, which the Chinese outage copy also names (连接异常,刷新重试). Every recovery attempt shows the shared ongoing loader beside **Reconnecting** with one to three dots advancing every 500ms, and an attempt stays visible for at least 800ms so brief retries do not flicker. Selecting either yellow state starts an immediate retry; press feedback stays within the warning palette. Recovery changes the region to pale-green **Connected** for two seconds from the moment the green pill becomes visible. The pill fades in on appearance, fades out over 150ms on removal, and sizes to its current label. Initial startup and uninterrupted healthy operation remain silent. The shell renders the modal panel, the navigation built from `settings.section` entries, and exactly one mounted onboarding step at a time. +Users reach the shell through the sidebar's bottom Settings control; feature plugins contribute their pages and onboarding steps through the slot ledgers this shell projects. In both the expanded sidebar and collapsed rail, the control exposes the localized Settings label as its accessible name. A pale-yellow **Disconnected** action beside Settings indicates browser offline suspension; its permanent retry glyph marks the retry action, which the Chinese outage copy also names (连接异常,刷新重试). Every recovery attempt shows the shared ongoing loader beside **Reconnecting** with one to three dots advancing every 500ms, and an attempt stays visible for at least 800ms so brief retries do not flicker. Selecting either yellow state starts an immediate retry; press feedback stays within the warning palette. Recovery changes the region to pale-green **Connected** for two seconds from the moment the green pill becomes visible. The pill fades in on appearance, fades out over 150ms on removal, and sizes to its current label. Initial startup and uninterrupted healthy operation remain silent. The shell registers the `settings.section.view` Component Factory, which declares `settings.section`, and renders the modal panel, the navigation built from `settings.section` entries, the selected page through that Factory with a `close` that closes the panel, and exactly one mounted onboarding step at a time. In a browser below 768px, the body-portaled panel fills the CSS layout viewport without additional safe-area padding and covers the mask. It keeps a fixed layout height rather than measuring the software keyboard; focused controls rely on the browser’s native viewport panning. @@ -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 a9e949c08e..d3db7fcf87 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ## 使用本包 -用户通过侧边栏底部的 Settings 控件进入外壳;功能插件通过本外壳所投影的 slot 账本贡献自己的页面与引导步骤。在展开侧边栏和收起轨道中,该控件都会把本地化的 Settings 文案作为其可访问名称。Settings 右侧浅黄色的**连接异常**操作表示浏览器离线暂停;其常驻重试图形与中文文案「连接异常,刷新重试」都指明重试动作。每次恢复尝试都显示共享 ongoing loading 加**重新连接中**,其后一至三个点每 500ms 前进一次,且每次尝试至少可见 800ms,短暂重试不会闪动。选中任一黄色状态都会立即发起重试;按压反馈留在黄色色阶内。恢复后该区域变为浅绿色的**连接成功**,从绿色药丸可见起驻留 2 秒再消失。药丸出现时淡入、移除时以 150ms 淡出,宽度随当前文案自适应。首次启动与未曾中断的健康连接保持静默。外壳渲染模态面板、由 `settings.section` 条目构建的导航,以及每次只挂载一个的引导步骤。 +用户通过侧边栏底部的 Settings 控件进入外壳;功能插件通过本外壳所投影的 slot 账本贡献自己的页面与引导步骤。在展开侧边栏和收起轨道中,该控件都会把本地化的 Settings 文案作为其可访问名称。Settings 右侧浅黄色的**连接异常**操作表示浏览器离线暂停;其常驻重试图形与中文文案「连接异常,刷新重试」都指明重试动作。每次恢复尝试都显示共享 ongoing loading 加**重新连接中**,其后一至三个点每 500ms 前进一次,且每次尝试至少可见 800ms,短暂重试不会闪动。选中任一黄色状态都会立即发起重试;按压反馈留在黄色色阶内。恢复后该区域变为浅绿色的**连接成功**,从绿色药丸可见起驻留 2 秒再消失。药丸出现时淡入、移除时以 150ms 淡出,宽度随当前文案自适应。首次启动与未曾中断的健康连接保持静默。外壳注册声明 `settings.section` 的 `settings.section.view` Component Factory,并渲染模态面板、由 `settings.section` 条目构建的导航、经该 Factory 渲染且以关闭面板为 `close` 的所选页面,以及每次只挂载一个的引导步骤。 浏览器宽度低于 768px 时,挂载到 body 的面板铺满 CSS 布局视口并覆盖遮罩,不额外留出安全区边距。面板保持固定布局高度,不测量软键盘;获得焦点的控件依赖浏览器原生的视口平移来露出。 @@ -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/package.json b/packages/client/ui-settings-general/package.json index 0a7750b051..3efadad6a0 100644 --- a/packages/client/ui-settings-general/package.json +++ b/packages/client/ui-settings-general/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-general", "description": "Settings ownerless-copy and product onboarding plugin: the General section, shell trigger/header chrome content, settings dictionaries, and the versioned welcome notice", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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 95e74201b7..96bddf9410 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -44,6 +44,7 @@ function navIcon(id: string) { type PanelProps = { rows: readonly SettingsSectionRow[] renderSlot: SettingsRootComponentProps['renderSlot'] + renderFactorySlot: SettingsRootComponentProps['renderFactorySlot'] activeId: string | undefined onSelect: (id: string) => void onClose: () => void @@ -54,7 +55,7 @@ type PanelProps = { * header button, a mask click, and document-level Escape (mounted only while * open, so the listener lifetime is the panel's). */ -function SettingsPanel({ rows, renderSlot, activeId, onSelect, onClose }: PanelProps) { +function SettingsPanel({ rows, renderSlot, renderFactorySlot, activeId, onSelect, onClose }: PanelProps) { // Entries can unmount underneath the requested id, so the render-time // projection falls back to the first row when the id is gone. const active = rows.find(r => r.id === activeId)?.id ?? rows[0]?.id @@ -106,7 +107,7 @@ function SettingsPanel({ rows, renderSlot, activeId, onSelect, onClose }: PanelP
      - {active !== undefined && renderSlot('settings.section', { close: onClose }, { only: active })} + {active !== undefined && renderFactorySlot('settings.section.view', { id: active, close: onClose })}
      @@ -120,7 +121,7 @@ function SettingsPanel({ rows, renderSlot, activeId, onSelect, onClose }: PanelP */ export function SettingsRoot(props: SettingsRootComponentProps) { const { - wide, reconnect, useConnectionState, useSections, useOnboardingSteps, useSessions, renderSlot, t, + wide, reconnect, useConnectionState, useSections, useOnboardingSteps, useSessions, renderSlot, renderFactorySlot, t, useDesktopUpdate, openDesktopUpdate, useStore, actions, useShortcuts, } = props const { open, activeId } = useStore(state => state) @@ -220,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: @@ -259,6 +263,7 @@ export function SettingsRoot(props: SettingsRootComponentProps) { ): ReactNode { + return renderSlot('settings.section', { close }, { only: id }) +} diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts index 3ee2c01e05..ee3bb86d99 100644 --- a/packages/client/ui-settings-general/src/client/index.ts +++ b/packages/client/ui-settings-general/src/client/index.ts @@ -40,6 +40,7 @@ import { DesktopChannelRow, DesktopChannelToast } from './DesktopChannelRow.tsx' import { DesktopUpdateSource } from './desktop-update-source.ts' import { CloseLabel, HeaderContent, TriggerContent } from './chrome.tsx' import { GeneralSection } from './GeneralSection.tsx' +import { SettingsSectionView } from './SettingsSectionView.tsx' import { CurrentVersionRow } from './CurrentVersionRow.tsx' import { DeveloperToolsRow, type DeveloperToolsRowInjected } from './DeveloperToolsRow.tsx' import { SettingsDocumentAction } from './SettingsDocumentAction.tsx' @@ -235,11 +236,11 @@ 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' }, 'settings.close': { kind: 'single', scope: 'root' }, - 'settings.section': { kind: 'list', scope: 'root' }, 'settings.section.icon': { kind: 'list', scope: 'root', inline: true }, 'settings.onboarding': { kind: 'list', scope: 'root' }, }, @@ -263,6 +264,11 @@ export function apply(ctx: ClientContext): void { } ctx.slots.inject('settings.close', () => ctx.slots.register({ name: 'settings.close', locale: NS }, CloseLabel)) + // Every surface that shows a settings page renders it through this Factory, which declares `settings.section`. + ctx.slots.registerFactory({ + name: 'settings.section.view', scope: 'root', + children: { 'settings.section': { kind: 'list', scope: 'root' } }, + }, SettingsSectionView) ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'general', 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 a44e6a1e70..1150d3f48c 100644 --- a/packages/client/ui-settings-general/src/client/shell-contract.ts +++ b/packages/client/ui-settings-general/src/client/shell-contract.ts @@ -8,7 +8,7 @@ */ import type { ConnectionState } from '@deepseek-ai/dsh-client-connection/client' import type { - HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, + HostObservable, InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls ui-sidebar's SlotMap merge (the 'sidebar.settings' entry) // into every program that sees this contract. @@ -67,14 +67,15 @@ export type SettingsRootComponentProps = PropsRuntime<'sidebar.settings'> & PropsRenderSlots< | 'settings.launcher' + | 'settings.notice' | 'settings.trigger' | 'settings.header' | 'settings.action' | 'settings.close' - | 'settings.section' | 'settings.section.icon' | 'settings.onboarding' > + & PropsRenderFactories & InjectFace & PropsLocale<'settings'> & PropsStore> diff --git a/packages/client/ui-settings-general/tests/apply.client.spec.ts b/packages/client/ui-settings-general/tests/apply.client.spec.ts index fd983d46dc..09723981da 100644 --- a/packages/client/ui-settings-general/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-general/tests/apply.client.spec.ts @@ -343,8 +343,10 @@ describe('ui-settings-general apply', () => { await c.reload(SIDEBAR) await c.flush() expectSeated(c) + // The General page sits in the Factory-declared `settings.section`, which the sidebar rebuild does not collapse. SEATS.forEach(([name], index) => { - expect(ownEntries(c, name)[0]).not.toBe(before[index]) + if (name === 'settings.section') expect(ownEntries(c, name)[0]).toBe(before[index]) + else expect(ownEntries(c, name)[0]).not.toBe(before[index]) }) expect(c.ctx.slots.spec('settings.general.item')).toEqual({ kind: 'list', scope: 'root' }) expect(c.ctx.slots.entries('settings.general.item').filter(row => row.locale === NS).map(row => row.options.id)).toEqual(['developer-tools', 'current-version']) diff --git a/packages/client/ui-settings-general/tests/section-view.client.spec.tsx b/packages/client/ui-settings-general/tests/section-view.client.spec.tsx new file mode 100644 index 0000000000..73d7654f94 --- /dev/null +++ b/packages/client/ui-settings-general/tests/section-view.client.spec.tsx @@ -0,0 +1,19 @@ +// @vitest-environment jsdom +/** The Factory that renders one settings page wherever a surface shows it. */ +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' +import { SettingsSectionView } from '../src/client/SettingsSectionView.tsx' + +afterEach(cleanup) + +describe('SettingsSectionView', () => { + it('renders the requested entry with the caller\'s leave action', () => { + const close = vi.fn() + const renderSlot = vi.fn(() =>

      page body

      ) + const props = { id: 'timeline', close, renderSlot } as Partial> + render(} />) + expect(screen.getByText('page body')).toBeTruthy() + expect(renderSlot).toHaveBeenCalledExactlyOnceWith('settings.section', { close }, { only: 'timeline' }) + }) +}) 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 a5587a608b..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', @@ -88,10 +89,12 @@ function mount({ const connectionListeners = new Set<() => void>() const reconnect = vi.fn() const renderSlot = vi.fn( - ((key: string, _owner: unknown, opts?: { only?: string; fallback?: import('react').ReactNode }) => { - if (key === 'settings.section') return
      - return SEAT_CONTENT[key] ?? opts?.fallback - }) as SettingsRootComponentProps['renderSlot'], + ((key: string, _owner: unknown, opts?: { only?: string; fallback?: import('react').ReactNode }) => + SEAT_CONTENT[key] ?? opts?.fallback) as SettingsRootComponentProps['renderSlot'], + ) + const renderFactorySlot = vi.fn( + ((name: string, factoryProps: { id: string }) => + name === 'settings.section.view' ?
      : null) as SettingsRootComponentProps['renderFactorySlot'], ) const activeId = brandString('active-session') const sessions: SessionListState = { @@ -144,6 +147,7 @@ function mount({ return select(current) }, renderSlot, + renderFactorySlot, } const view = render() const bump = (next: Row[]) => { @@ -162,6 +166,7 @@ function mount({ desktopUpdate = next view.rerender() } + const setWide = (next: boolean) => { view.rerender() } const setShortcuts = (next: readonly ShortcutCatalogEntry[]) => { shortcuts = next view.rerender() @@ -173,7 +178,10 @@ function mount({ act(() => { sessions.byId[activeId] = { ...session, blank: next } }) view.rerender() } - return { view, renderSlot, bump, listeners, reconnect, setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive } + return { + view, renderSlot, renderFactorySlot, bump, listeners, reconnect, + setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive, setWide, + } } function openPanel() { @@ -486,12 +494,11 @@ describe('SettingsPanel navigation', () => { }) it('renders an empty content column and focuses the title when the ledger is empty', () => { - const { renderSlot } = mount({ rows: [] }) + const { renderFactorySlot } = mount({ rows: [] }) openPanel() expect(document.activeElement).toBe(screen.getByText('Settings Title')) expect(screen.getByRole('dialog')).toBeTruthy() - const sectionCalls = renderSlot.mock.calls.filter(c => c[0] === 'settings.section') - expect(sectionCalls).toHaveLength(0) + expect(renderFactorySlot).not.toHaveBeenCalled() }) it('drops the ledger subscription on unmount', () => { @@ -553,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 75af01b079..c728b1e704 100644 --- a/packages/client/ui-settings-general/tests/shell.client.spec.ts +++ b/packages/client/ui-settings-general/tests/shell.client.spec.ts @@ -25,9 +25,10 @@ function injectedOf(c: TestClient): SettingsRootInjected { return (entry.inject as () => SettingsRootInjected)() } -/** The shell's child declarations (chrome, actions, sections, and onboarding overlays). */ +/** 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' }, @@ -40,7 +41,7 @@ const CHILD_NAMES = Object.keys(CHILD_SPECS) as Array /** * Section ids the web-app roster registers, in nav order: this package, then - * ui-settings-models, ui-settings-plugins, and ui-agent-preset. A plugin + * ui-settings-models, ui-plugin-manager, and ui-agent-preset. A plugin * adding a section changes this list. */ const PRODUCT_SECTIONS: readonly string[] = ['general', 'models', 'plugins', 'agent-presets'] diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 0b4439bdbe..d6a66e45df 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: f0122477b91ac5d6 + zh: e66ad0a21ab0fa4d /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..24605451db 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. @@ -37,7 +39,7 @@ A provider with a stored catalog error remains visible with its diagnostic and e After Apply closes an editor, its saved status appears when the current provider, settings, and credential snapshot is ready. Opening any row's editor, adding a provider, and opening a removal confirmation wait for that refresh. A newly opened Models section, or one retrying after a page-load failure, waits for a ready snapshot before mounting editors. A background refresh preserves an open draft while its editor remains mounted; a failed page load or provider removal can close it. -Host configuration `credentialOnboarding` defaults to `true`. The Electron preload marker suppresses automatic credential onboarding and the Web welcome notice; Models settings and explicit API-key editing remain available. The [account plugin](../ui-settings-account/README.md#desktop-onboarding) owns the Desktop introduction. Other native shells can disable only the credential step with `credentialOnboarding: false`. Host publishes this public boolean through `webserver/index-inject`, and Client validates it before registering dialogs. It is page initialization data, not a durable completion marker. +Host configuration `credentialOnboarding` defaults to `true`. The Electron preload marker suppresses automatic credential onboarding and the Web welcome notice; Models settings and explicit API-key editing remain available. The [account plugin](../ui-settings-account/README.md#desktop-onboarding) owns the Desktop introduction. Other native shells can disable only the credential step with `credentialOnboarding: false`. The field is volatile and reaches the browser through the plugin's [synced Config](../modules/README.md#synced-plugin-configuration): a change decides whether a credential step that has not mounted yet opens on its own, while a step that already mounted keeps its decision, so an open step stays open. A browser that receives no value uses `true`. The field is configuration, not a durable completion marker. ### API keys @@ -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..9af095ccac 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 排第二;第三方提供方保留目录中的相对顺序。 @@ -37,7 +39,7 @@ kind: "package-reference" 应用设置并关闭编辑器后,当前提供商、settings 与凭据快照就绪时才显示保存状态。打开任一行的编辑器、添加提供商和打开移除确认都会等待该刷新。新打开的 Models 区域或页面加载失败后的重试会等到 ready 快照后才挂载编辑器。后台刷新期间,只要编辑器仍挂载,已打开的草稿就会保留用户的修改;页面加载失败或提供商被移除可能关闭编辑器。 -Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会抑制自动凭证引导和 Web 欢迎须知;模型设置页与显式 API Key 编辑仍然可用。[账号插件](../ui-settings-account/README.zh.md#desktop-onboarding)负责 Desktop 引导。其他原生壳可以通过 `credentialOnboarding: false` 仅禁用凭证步骤。Host 通过 `webserver/index-inject` 发布这个公开的布尔值,Client 在注册弹窗前校验它。它是页面初始化数据,不是持久化的完成标记。 +Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会抑制自动凭证引导和 Web 欢迎须知;模型设置页与显式 API Key 编辑仍然可用。[账号插件](../ui-settings-account/README.zh.md#desktop-onboarding)负责 Desktop 引导。其他原生壳可以通过 `credentialOnboarding: false` 仅禁用凭证步骤。该字段是 volatile 字段,经插件的[同步 Config](../modules/README.zh.md#synced-plugin-configuration) 送达浏览器:修改决定尚未挂载的凭证步骤是否自动打开,已挂载的步骤保留其决定,因此已打开的步骤不会被收回。浏览器未收到值时使用 `true`。该字段是配置,不是持久化的完成标记。 ### API 密钥 @@ -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/package.json b/packages/client/ui-settings-models/package.json index 7713bd60d1..e0957334ec 100644 --- a/packages/client/ui-settings-models/package.json +++ b/packages/client/ui-settings-models/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-models", "description": "Models settings and shared product-onboarding dialogs over existing settings and credential joins", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -45,7 +45,6 @@ "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { - "@deepseek-ai/dsh-host-webserver": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", @@ -58,7 +57,9 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-remote-mock": "workspace:*", - "@deepseek-ai/dsh-client-product-analytics": "workspace:*" + "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-util-text-search": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" diff --git a/packages/client/ui-settings-models/src/client/DeepSeekOnboardingDialog.tsx b/packages/client/ui-settings-models/src/client/DeepSeekOnboardingDialog.tsx index 63c090b3d5..3521a584f4 100644 --- a/packages/client/ui-settings-models/src/client/DeepSeekOnboardingDialog.tsx +++ b/packages/client/ui-settings-models/src/client/DeepSeekOnboardingDialog.tsx @@ -8,7 +8,7 @@ import type { TrackProductEvent } from '@deepseek-ai/dsh-client-product-analytics/client' import { useEffect, useState } from 'react' import type { ReactNode } from 'react' -import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { InjectFace, PropsRuntime, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import type { ModelsSettingsState, ModelsSettingsStore } from './store.ts' import { onboardingReadiness } from './store.ts' @@ -24,11 +24,14 @@ import styles from './DeepSeekOnboardingDialog.module.css' export interface DeepSeekOnboardingInjected { /** Desktop-only event collection. */ track?: TrackProductEvent - /** Whether first-run setup should show automatically. Explicit requests remain available. */ - automatic: boolean hooks: { /** Shared Models-page join state, bound by the slot renderer. */ models: SnapshotStore + /** + * Whether first-run setup should show automatically; the step reads it once when it mounts, so a later change + * never withdraws a step that already took its turn. Explicit requests remain available. + */ + automatic: ObservableSnapshot } /** Shared Models-page join controller. */ controller: ModelsSettingsStore @@ -56,8 +59,10 @@ function assertNever(_value: never): never { * @returns the onboarding modal or null when onboarding needs no intervention. */ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): ReactNode { - const { complete, controller, useModels, operations, schema, t, renderSlot, automatic, explicit = false } = props + const { complete, controller, useModels, useAutomatic, operations, schema, t, renderSlot, explicit = false } = props const [apiKey, setApiKey] = useState(explicit) + const automaticOnMount = useAutomatic(value => value) + const [automatic] = useState(automaticOnMount) const state = useModels(snapshot => snapshot) const readiness = onboardingReadiness(state) diff --git a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx index 11e5a52d5b..7e7f2c1907 100644 --- a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx @@ -22,6 +22,7 @@ import { useEffect, useMemo, useState } from 'react' import type { ReactNode } from 'react' import type { LlmDiscoveredModel } from '@deepseek-ai/dsh-api-remotes/client' import { AnimatedRows, Button, IconPlusOutlineRegular, Modal } from '@deepseek-ai/dsh-client-ui-primitives' +import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' import { formatCapacity, parseCapacity } from './DeepSeekModelsEditor.tsx' import type { ModelsOperations } from './operations.ts' import type { DeepSeekModelDraft } from './DeepSeekModelsEditor.tsx' @@ -251,6 +252,10 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode { const isPicked = (id: string): boolean => pickedByDefault(id) !== flipped.has(id) const activeCandidates = candidates ?? [] + const candidateIndex = useMemo( + () => new TextSearchIndex(candidates ?? [], candidate => ({ fuzzy: [candidate.id, candidate.name] })), + [candidates], + ) const listed = new Set(activeCandidates.map(candidate => candidate.id)) // An unchecked candidate leaves the list. A row the listing does not name, // including a half-typed row without an id, is outside the picker and stays. @@ -283,11 +288,7 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode { }) } - const normalizedCandidateQuery = candidateQuery.trim().toLowerCase() - const visibleCandidates = normalizedCandidateQuery.length === 0 - ? activeCandidates - : activeCandidates.filter(candidate => candidate.id.toLowerCase().includes(normalizedCandidateQuery) - || candidate.name?.toLowerCase().includes(normalizedCandidateQuery) === true) + const visibleCandidates = candidateIndex.search(candidateQuery) const allVisibleCandidatesPicked = visibleCandidates.length > 0 && visibleCandidates.every(candidate => isPicked(candidate.id)) 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-models/src/client/index.ts b/packages/client/ui-settings-models/src/client/index.ts index d0b61802a5..da6ef1637e 100644 --- a/packages/client/ui-settings-models/src/client/index.ts +++ b/packages/client/ui-settings-models/src/client/index.ts @@ -8,6 +8,8 @@ */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' // Type-only: pulls the shell's SlotMap merge (the 'settings.section' entry). import type {} from '@deepseek-ai/dsh-client-ui-settings/client' // Type-only: pulls the locale plugin's Context merge (ctx.locale). @@ -28,7 +30,7 @@ import { createModelsOperations } from './operations.ts' import { createSettingsSchemaOperations } from './schema-operations.ts' import { en, ja, es, fr, de, ru, pt, zh, type ModelsKey } from './locales.ts' import { WELCOME_NOTICE_SETTINGS_NAMESPACE } from '../onboarding-copy.ts' -import { Config, ONBOARDING_CONFIG_GLOBAL } from '../onboarding-config.ts' +import type { ModelsConfig } from '../types.ts' export type { ModelsSectionInjected, ModelsSectionProps } from './ModelsSection.tsx' export type { ModelsFooterOwnerProps, ProviderCardExtrasOwnerProps } from './slot-contract.ts' @@ -44,6 +46,9 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { /** Dictionary namespace owned by this plugin. */ const NS = 'settings.models' +/** Credential-onboarding choice while the Host sends none; the Host schema default. */ +const ABSENT_CREDENTIAL_ONBOARDING = true + export type { ModelsSettingsState, ProviderDirectoryEntry, ProviderRow, } from './store.ts' @@ -74,12 +79,15 @@ export const inject = [ * the ledger, wire its store to the connection, and keep it fresh on every * pushed invalidation (settings, credentials, or provider topology). * @param ctx - client root context. + * @param config - Host-synced credential-onboarding choice, followed live until the official-DeepSeek step mounts. */ -export function apply(ctx: ClientContext): void { - const page = globalThis as Partial> - const payload = page[ONBOARDING_CONFIG_GLOBAL] - const configured = Config(payload === undefined ? {} : payload) - const credentialOnboarding = configured.credentialOnboarding && !('dshDesktop' in globalThis) +export function apply(ctx: ClientContext, config: SyncedConfig): void { + const nativeShell = 'dshDesktop' in globalThis + // Whether the official-DeepSeek step opens on its own; the native shell owns its own onboarding. + const automatic: ObservableSnapshot = { + getSnapshot: () => !nativeShell && (config.credentialOnboarding.get() ?? ABSENT_CREDENTIAL_ONBOARDING), + subscribe: listener => config.credentialOnboarding.subscribe(listener), + } ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-settings-models: copy dictionaries') const schema = createSettingsSchemaOperations(ctx.settingsSchema) @@ -98,10 +106,9 @@ export function apply(ctx: ClientContext): void { t, }) const deepSeekOnboardingInjected = (): DeepSeekOnboardingInjected => ({ - automatic: credentialOnboarding, track: (name, attributes) => ctx.get('productAnalytics')?.track(name, attributes), controller, - hooks: { models: controller.store }, + hooks: { models: controller.store, automatic }, operations, schema, t, @@ -144,7 +151,7 @@ export function apply(ctx: ClientContext): void { 'settings.models.footer': { kind: 'list', scope: 'root' }, }, }, ModelsSection)) - if (!('dshDesktop' in globalThis)) ctx.slots.inject('settings.onboarding', () => ctx.slots.register({ + if (!nativeShell) ctx.slots.inject('settings.onboarding', () => ctx.slots.register({ name: 'settings.onboarding', id: 'welcome-notice', order: -100, diff --git a/packages/client/ui-settings-models/src/index.ts b/packages/client/ui-settings-models/src/index.ts index d73e39dc5e..7ed142770f 100644 --- a/packages/client/ui-settings-models/src/index.ts +++ b/packages/client/ui-settings-models/src/index.ts @@ -1,22 +1,20 @@ -/** Host configuration and page bootstrap for Models credential onboarding. */ - +/** Host Loader entry declaring the Models credential-onboarding choice; onboarding belongs to the Client. */ import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-host-webserver' -import { type Config, ONBOARDING_CONFIG_GLOBAL } from './onboarding-config.ts' +import z from '@deepseek-ai/schemastery' +import type { ModelsConfig } from './types.ts' -export { Config } from './onboarding-config.ts' +/** Credential-onboarding choice synced to the browser. */ +export type Config = ModelsConfig + +/** Credential-onboarding choice synced to the browser. */ +export const Config = z.object({ + credentialOnboarding: z.boolean().default(true).volatile(), +}) /** - * Publish the credential-onboarding choice before browser plugins activate. - * @param ctx - Host context collecting the page's initialization data. - * @param config - plugin options with schema defaults applied by the Loader. + * Register the browser plugin without Host behavior; the Loader validates the entry's Config, and the browser face + * receives its volatile fields. + * @param _ctx - Host context; unused. + * @param _config - validated Config; unused on the Host. */ -export function apply(ctx: Context, config: Config): void { - ctx.on('webserver/index-inject', (table) => { - table.push({ - kind: 'global', - name: ONBOARDING_CONFIG_GLOBAL, - value: { credentialOnboarding: config.credentialOnboarding }, - }) - }) -} +export function apply(_ctx: Context, _config: Config): void {} diff --git a/packages/client/ui-settings-models/src/onboarding-config.ts b/packages/client/ui-settings-models/src/onboarding-config.ts deleted file mode 100644 index 2213ea3a93..0000000000 --- a/packages/client/ui-settings-models/src/onboarding-config.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** Public page-bootstrap options shared by the Host and Client halves. */ - -import z from '@deepseek-ai/schemastery' - -/** Onboarding options after schema defaults are applied. */ -export interface Config { - /** Offer the browser API-key step when no native shell owns credential onboarding. */ - credentialOnboarding: boolean -} - -/** Validate Host configuration and its public page-bootstrap payload. */ -export const Config: z, Config> = z.object({ - credentialOnboarding: z.boolean().default(true), -}) - -/** Page-global key carrying only the public onboarding options. */ -export const ONBOARDING_CONFIG_GLOBAL = '__DSH_MODELS_ONBOARDING__' diff --git a/packages/client/ui-settings-models/src/types.ts b/packages/client/ui-settings-models/src/types.ts new file mode 100644 index 0000000000..6d0341d477 --- /dev/null +++ b/packages/client/ui-settings-models/src/types.ts @@ -0,0 +1,8 @@ +/** Models settings plugin configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' + +/** Credential-onboarding choice; the browser receives it through its synced Config. */ +export interface ModelsConfig { + /** Offer the browser API-key step automatically when no native shell owns credential onboarding. */ + credentialOnboarding: Volatile +} diff --git a/packages/client/ui-settings-models/tests/apply.client.spec.ts b/packages/client/ui-settings-models/tests/apply.client.spec.ts index 66e3eae78c..b757044a46 100644 --- a/packages/client/ui-settings-models/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-models/tests/apply.client.spec.ts @@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { syncedConfig, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { remoteDefaultResponses } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/remote-default-responses.ts' import { ok, RemoteMock } from '@deepseek-ai/dsh-remote-mock' import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client' @@ -17,12 +17,9 @@ import { import { ModelsSection } from '../src/client/ModelsSection.tsx' import { DeepSeekOnboardingDialog } from '../src/client/DeepSeekOnboardingDialog.tsx' import { WelcomeNotice } from '../src/client/WelcomeNotice.tsx' -import type { IndexInjection, WebServer } from '@deepseek-ai/dsh-host-webserver' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import * as hostPlugin from '../src/index.ts' -import { ONBOARDING_CONFIG_GLOBAL } from '../src/onboarding-config.ts' - -/** The Peer an index render speaks for; this listener reads no field of it. */ -const PAGE_PEER = { principal: { kind: 'owner' } } as Parameters[1] afterEach(() => { vi.unstubAllGlobals() }) @@ -69,41 +66,65 @@ function declare(slots: SlotRegistry): () => void { ) } +/** The official-DeepSeek step's injected automatic-onboarding source. */ +function automaticSource(slots: SlotRegistry): ObservableSnapshot { + const entry = slots.entries('settings.onboarding').find(candidate => candidate.options.id === 'deepseek-official')! + return (entry.inject as () => { hooks: { automatic: ObservableSnapshot } })().hooks.automatic +} + describe('ui-settings-models apply', () => { - it('keeps manual credential onboarding available when the native shell owns automatic onboarding', async () => { + it('declares a live credential-onboarding switch without Host behavior', () => { + expect(hostPlugin.Config({}).credentialOnboarding.get()).toBe(true) + expect(hostPlugin.Config({ credentialOnboarding: false }).credentialOnboarding.get()).toBe(false) + expect(hostPlugin.Config['~standard'].validate({ credentialOnboarding: 'false' })).toHaveProperty('issues') + hostPlugin.apply(new Context(), hostPlugin.Config({})) + }) + + it('keeps manual credential onboarding available when automatic onboarding is off', async () => { const { ctx, slots } = await bench() declare(slots) try { - const host = ctx.plugin(hostPlugin, { credentialOnboarding: false }) - await host.await() - const rows: IndexInjection[] = [] - ctx.emit('webserver/index-inject', rows, PAGE_PEER) - expect(rows).toEqual([{ kind: 'global', name: ONBOARDING_CONFIG_GLOBAL, value: { credentialOnboarding: false } }]) - for (const row of rows) if (row.kind === 'global') vi.stubGlobal(row.name, row.value) - const plugin = ctx.plugin({ inject: [...inject], apply }) + const plugin = ctx.plugin({ inject: [...inject], apply }, syncedConfig({ credentialOnboarding: false })) await plugin.await() expect(slots.entries('settings.onboarding').map(entry => entry.options.id)).toEqual(['welcome-notice', 'deepseek-official']) - const onboarding = slots.entries('settings.onboarding').find(entry => entry.options.id === 'deepseek-official')! - expect((onboarding.inject as () => { automatic: boolean })().automatic).toBe(false) + expect(automaticSource(slots).getSnapshot()).toBe(false) expect(slots.entries('settings.section').map(entry => entry.options.id)).toEqual(['models']) await plugin.dispose() expect(slots.entries('settings.onboarding')).toEqual([]) - await host.dispose() - const after: IndexInjection[] = [] - ctx.emit('webserver/index-inject', after, PAGE_PEER) - expect(after).toEqual([]) } finally { await ctx.fiber.dispose() } }) - it('defaults to browser onboarding and rejects malformed bootstrap options', async () => { - expect(hostPlugin.Config({})).toEqual({ credentialOnboarding: true }) - expect(hostPlugin.Config['~standard'].validate({ credentialOnboarding: 'false' })).toHaveProperty('issues') - const { ctx } = await bench() + it('follows Host edits of the credential-onboarding switch and defaults it when absent', async () => { + const { ctx, slots } = await bench() + declare(slots) try { - vi.stubGlobal(ONBOARDING_CONFIG_GLOBAL, { credentialOnboarding: 'false' }) - expect(() => { apply(ctx) }).toThrow() + const value = createSnapshotStore(undefined) + const read = (): boolean | undefined => value.getSnapshot() + const ref = { get: read, getSnapshot: read, subscribe: (fn: () => void) => value.subscribe(fn) } + await ctx.plugin({ inject: [...inject], apply }, { credentialOnboarding: ref }).await() + const source = automaticSource(slots) + expect(source.getSnapshot()).toBe(true) + const listener = vi.fn() + const unsubscribe = source.subscribe(listener) + value.set(false) + expect(listener).toHaveBeenCalledTimes(1) + expect(source.getSnapshot()).toBe(false) + unsubscribe() + } finally { + await ctx.fiber.dispose() + } + }) + + it('leaves automatic onboarding and the welcome notice to the native shell', async () => { + vi.stubGlobal('dshDesktop', {}) + const { ctx, slots } = await bench() + declare(slots) + try { + await ctx.plugin({ inject: [...inject], apply }, syncedConfig({ credentialOnboarding: true })).await() + expect(slots.entries('settings.onboarding').map(entry => entry.options.id)).toEqual(['deepseek-official']) + expect(automaticSource(slots).getSnapshot()).toBe(false) } finally { await ctx.fiber.dispose() } @@ -119,7 +140,7 @@ describe('ui-settings-models apply', () => { it('registers the models nav entry for declarations before or after apply', async () => { const before = await bench() declare(before.slots) - await before.ctx.plugin({ inject: [...inject], apply }).await() + await before.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() const entry = before.slots.entries('settings.section')[0]! expect(entry.component).toBe(ModelsSection) expect(entry.options).toMatchObject({ id: 'models', order: 10 }) @@ -156,7 +177,7 @@ describe('ui-settings-models apply', () => { expect(typeof deepSeekInjected.operations.storeCredential).toBe('function') const after = await bench() - await after.ctx.plugin({ inject: [...inject], apply }).await() + await after.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() expect(after.slots.entries('settings.section')).toHaveLength(0) expect(after.slots.entries('settings.onboarding')).toHaveLength(0) declare(after.slots) @@ -170,7 +191,7 @@ describe('ui-settings-models apply', () => { it('the label thunk follows the active locale without re-registration', async () => { const b = await bench() declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() b.locale.setLocale('en') expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('Models') const injected = b.slots.entries('settings.section')[0]!.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected @@ -182,7 +203,7 @@ describe('ui-settings-models apply', () => { it('locale change while the slot is undeclared stays a no-op', async () => { const b = await bench() - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() b.locale.setLocale('en') expect(b.slots.entries('settings.section')).toHaveLength(0) b.locale.setLocale('zh') @@ -191,7 +212,7 @@ describe('ui-settings-models apply', () => { it('re-registers after an HMR collapse re-declares the slot (stale disposer must not block)', async () => { const b = await bench() const redeclare = declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() expect(b.slots.entries('settings.section')).toHaveLength(1) // Declarer unload: the cascade removes our entry while our local // disposer variable goes stale. @@ -211,7 +232,7 @@ describe('ui-settings-models apply', () => { it('accepts extension entries under the declared seats and cascades them with the declarer', async () => { const b = await bench() declare(b.slots) - const fiber = b.ctx.plugin({ inject: [...inject], apply }) + const fiber = b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})) await fiber.await() // A keyed card extension and a footer entry register through the ordinary // ledger once the section's registration declared the seats. @@ -233,7 +254,7 @@ describe('ui-settings-models apply', () => { it('registers the zh/en nav dictionaries and disposes everything with the fiber', async () => { const b = await bench() declare(b.slots) - const fiber = b.ctx.plugin({ inject: [...inject], apply }) + const fiber = b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})) await fiber.await() expect(b.locale.bind('settings.models')('nav')).toBe('模型') await fiber.dispose() @@ -249,7 +270,7 @@ describe('pushed invalidations', () => { it('ignores invalidations before the page ever loaded', async () => { const b = await bench() declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() // The fake wire face has no methods: a fetch attempt would throw. b.remote.emit('settings/document-updated', ['llm-pi-ai', 1]) b.remote.emit('credentials/reference-updated', ['OPENAI_API_KEY']) @@ -276,7 +297,7 @@ describe('pushed invalidations', () => { it('routes pushed credential invalidation into the shared onboarding join', async () => { const b = await bench() declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() const entry = b.slots.entries('settings.onboarding') .find(candidate => candidate.options.id === 'deepseek-official')! const injected = ( @@ -305,7 +326,7 @@ describe('pushed invalidations', () => { mock.remote.settings.describe.mockResolvedValue(ok(document)) const b = await bench(mock) declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() const entry = b.slots.entries('settings.onboarding') .find(candidate => candidate.options.id === 'welcome-notice')! const injected = ( @@ -335,7 +356,7 @@ describe('pushed invalidations', () => { const listProviders = vi.fn(() => Promise.resolve({ ok: true as const, value: [] })) const b = await bench(mock, { listProviders }) declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({})).await() const entry = b.slots.entries('settings.section') .find(candidate => candidate.options.id === 'models')! const injected = ( diff --git a/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx b/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx index 5bec76ddce..b8f849d52a 100644 --- a/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx @@ -8,6 +8,7 @@ import Schema from '@deepseek-ai/schemastery' import type { SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { allowAllAccess, bindSnapshotSelector, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { DeepSeekOnboardingDialog } from '../src/client/DeepSeekOnboardingDialog.tsx' import type { DeepSeekOnboardingDialogProps } from '../src/client/DeepSeekOnboardingDialog.tsx' import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' @@ -76,6 +77,7 @@ function harness(options: { settingsWritable?: boolean providersFailure?: string setFailure?: string + automatic?: boolean } = {}) { if (document.getElementById('root') === null) { const appRoot = document.createElement('div') @@ -143,8 +145,8 @@ function harness(options: { const openSection = vi.fn() const complete = vi.fn() const unusedHook = (() => { throw new Error('unused standard hook') }) as never + const automatic = createSnapshotStore(options.automatic ?? true) const props: DeepSeekOnboardingDialogProps = { - automatic: true, stepId: 'deepseek-official', complete, openSection, @@ -157,12 +159,13 @@ function harness(options: { useContextMenu: contextMenuHook(), controller, useModels: bindSnapshotSelector(controller.store), + useAutomatic: bindSnapshotSelector(automatic), operations, schema: settingsSchema, t: key => en[key], } return { - controller, complete, openSection, props, mutate, set, + automatic, controller, complete, openSection, props, mutate, set, configure: () => { fileConfigured = true }, } } @@ -307,9 +310,26 @@ it('explicit account-menu setup reuses the editor without another login choice', expect(h.complete).not.toHaveBeenCalled() }) -it('keeps explicit API key setup available when automatic onboarding is disabled', async () => { +it('keeps an open step after automatic onboarding turns off', async () => { const h = harness() - h.props.automatic = false + render() + await waitFor(() => { expect(screen.getByRole('dialog')).toBeTruthy() }) + act(() => { h.automatic.set(false) }) + expect(screen.getByRole('dialog')).toBeTruthy() + expect(h.complete).not.toHaveBeenCalled() +}) + +it('completes without loading when automatic onboarding is off at mount', () => { + const h = harness({ automatic: false }) + const load = vi.spyOn(h.controller, 'load') + const { container } = render() + expect(container.innerHTML).toBe('') + expect(h.complete).toHaveBeenCalled() + expect(load).not.toHaveBeenCalled() +}) + +it('keeps explicit API key setup available when automatic onboarding is disabled', async () => { + const h = harness({ automatic: false }) h.props.explicit = true render() await waitFor(() => { expect(screen.getByRole('dialog')).toBeTruthy() }) diff --git a/packages/client/ui-settings-models/tsconfig.json b/packages/client/ui-settings-models/tsconfig.json index 121f44cdde..b61f518800 100644 --- a/packages/client/ui-settings-models/tsconfig.json +++ b/packages/client/ui-settings-models/tsconfig.json @@ -9,7 +9,10 @@ ], "references": [ { - "path": "../../host/webserver" + "path": "../../util/text-search" + }, + { + "path": "../config" }, { "path": "../../../vendor/schemastery" diff --git a/packages/client/ui-settings-plugin-inventory/README.i18n.yaml b/packages/client/ui-settings-plugin-inventory/README.i18n.yaml deleted file mode 100644 index 17f73de103..0000000000 --- a/packages/client/ui-settings-plugin-inventory/README.i18n.yaml +++ /dev/null @@ -1,52 +0,0 @@ -# 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-settings-plugin-inventory/README.md -/: - en: 9121298d88fe8ea6 - zh: 5da705491f951d0e -/deepseek-ai-dsh-client-ui-settings-plugin-inventory: - en: 463eecf002ec0f54 - zh: b8dc6003ddccd14a -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/summary: - en: f52353cf99816eb8 - zh: e172c1751289882f -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/table-of-contents: - en: d152484eb41ac6b4 - zh: 09388d293f9be9cb -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/use-this-package: - en: 67637808e7940157 - zh: d4d0716ea4d33e4a -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/use-this-package/reading-a-card: - en: 3cb7d3a63d5c0fea - zh: d127dfbb58e50e4b -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/use-this-package/the-preset-switcher: - en: 84e5938329199a22 - zh: 6f5cfaac56433e8b -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/use-this-package/retrying-a-failed-read: - en: 673c7574e14078be - zh: b093e897f0341973 -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/understand-the-implementation: - en: cab883d26642c932 - zh: 54e7321bd781b400 -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/understand-the-implementation/registration: - en: e4792880c5916ce0 - zh: 4c8171a446dd153f -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/understand-the-implementation/rendering: - en: 779146e3d3732803 - zh: 0dfafa328dfeda75 -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/further-exploration: - en: ae3819f0c5da95bd - zh: 40972ab96d5c95e2 -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/model-experience: - en: 69fb187ac2361233 - zh: d4d3ec4ed3e3d98d -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/model-experience/kv-cache-effect: - en: ca75c51c89c2c9b0 - zh: de54f3467ef3b9be -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/known-limitations-and-deferred-work: - en: 3d3343d97eb73762 - zh: 5fc9d1c1f0c4055d -/deepseek-ai-dsh-client-ui-settings-plugin-inventory/known-limitations-and-deferred-work/dev-note: - en: e67f633dc6fe7773 - zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-settings-plugin-inventory/README.md b/packages/client/ui-settings-plugin-inventory/README.md deleted file mode 100644 index ceac087bd9..0000000000 --- a/packages/client/ui-settings-plugin-inventory/README.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -description: "Scope-grouped read-only plugin inventory tab in Web Plugins settings for the dsh web client: agent-preset compositions first, the global plane behind a disclosure, search across both." -kind: "package-reference" ---- - -# @deepseek-ai/dsh-client-ui-settings-plugin-inventory - -English | [中文](README.zh.md) - -## Summary - -The **Plugin list** tab lets Web users inspect plugins without changing their configuration. It lists agent presets, open by default, then the collapsed global inventory; a search opens both. Cards show localized titles and descriptions when available, identify instances by stable entry id, and expose enablement, source details, runtime status, disabled conditions, and discovery failures; preset-provided global entries name their presets. Search covers both groups and points to matches in other presets. The tab handles loading, empty, no-match, failure, and retry states without exposing transport details, and still shows the global inventory without a preset roster. - -## 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 - -Open the Plugins section in Settings and select the **Plugin list** tab to inspect the Host's plugin inventory. The tab reads no Remote during plugin activation — selecting it for the first time mounts the component and lazily calls `ctx.remote.pluginInventory.list()` through `api-remotes`. - -A failed installation with pending pnpm build permissions offers **Allow these scripts and retry**. The action displays the exact package names and persistent permission scope, then retries the original package spec and activation choice. One click approves the entire displayed group, which can include pending packages from earlier attempts. Closing the page grants no permission. - -### Reading a card - -Each collapsed card uses the plugin's localized title and description when available; a description shows at most two lines until its card is expanded. Settings shortens literal package-name or module-name fallbacks by removing the npm scope and the `cordis:`, `cordis-plugin-`, or `dsh-`/`dsh-host-`/`dsh-client-` prefix; locale titles remain unchanged. The Host supplies locale and package-field fallbacks in `meta`; the Client selects the current language. Full module specifiers remain available in details and search. Missing descriptions are omitted, and metadata diagnostics appear with the card. This compact naming applies only to Settings, not the sidebar's Plugins page. - -A small enablement tag marks only the states that differ from plainly enabled: disabled, conditional, provided by presets, and failed; a plainly enabled row carries no tag. A colored root-fiber status dot marks the live phases no tag states: `pending` maps to idle, while `loading` and `unloading` map to ongoing; an `active` or `failed` fiber shows no dot. The stable entry id appears in a code chip at the card's bottom-left, in line with the title, only when it differs from the title: a composition-generated id drops its leading `include:` marker there, and an id that then repeats the title is omitted. Whenever the chip shows, its hover text and the card's accessible name carry the complete id; search and expanded details always retain it. Long entry ids truncate in the chip and remain available on hover. Expanding one card reveals its full description, the declared entry id, the full module specifier, and the state facts: a preset row names the preset it comes from, its runtime status when the composition is live, and its disable condition when it carries one; a preset-provided global row explains that agent presets provide it per session, names the presets that enable it. Preset names resolve through the shared `presetDisplayText` fold (`dsh-agent-preset-registry/display`) over [`ui-agent-preset`](../ui-agent-preset/README.md)'s dictionaries: shipped presets follow the active locale while user-authored ones keep their own metadata, so an English surface never echoes the preset declarations' Chinese names. Search filters both groups by localized title and description, module name, and entry id. - -A card paints its hover surface only where the pointer can hover: a tap answers with the pressed fill, and an expanded card keeps its open surface on every device. The search field takes a 16px face under a coarse pointer, so iOS Safari does not zoom the page for a focused field. - -### The preset switcher - -The switcher is the same selector-pill-plus-menu control the General settings rows use. It lists every roster preset — the default suffixed as such, broken ones marked — and changes only what the list shows: it writes no settings, and selecting a broken preset shows the discovery-reported reason in place of rows. Choosing the default preset or a session's preset stays where it was: the Agent presets section and the new-session screen. - -### Retrying a failed read - -A failed read renders the shared error marker inside the tab. Loading shows skeleton cards in the card grid, and current-page synchronization uses the shared ongoing loader. Retrying re-runs the lazy `list()` call without exposing transport details. - -The Plugin list also shows synchronization failures on the current page. Its retry reapplies the latest client graph without changing Host enablement or refreshing the page. - ------ - - -## Understand the implementation - -
      -Implementation internals — click to expand - -The tab is a read-only projection of a Host-owned snapshot; it performs no Remote read during plugin activation and takes the snapshot on first selection. - -### Registration - -The browser plugin registers one localized `settings.plugins.tab` contribution with id `all`; the Plugins section owns the navigation entry and tab chrome. Registration uses `ctx.slots.inject()`, so it follows late tab declaration, redeclaration, locale changes, and teardown without importing the section owner. - -### Rendering - -Row keys are scope-qualified (`global:`, `preset::`), so one module appearing in both scopes keeps distinct disclosure state; a declared entry id appears in expanded details and, after removal of a leading composition `include:` marker, supplies the collapsed id chip when the result differs from the title, while a row without one stays unlabeled. The preset-provided marking is derived client-side: a global entry carries it when it is disabled there while at least one preset row for the same module specifier is actually enabled, so a module every preset gates off (or declares only conditionally) stays plainly disabled rather than over-claiming provision. - -
      - ------ - - -## Further Exploration - -These pages cover the settings section, the remote call, and the Host-side projection. - -- [ui-settings-plugins](../ui-settings-plugins/README.md) — the Plugins section this tab registers into. -- [ui-settings](../ui-settings/README.md) — the domain base declaring `settings.plugins.tab`. -- [api-remotes](../../api/remotes/README.md) — the Remote BFF surface behind `pluginInventory.list()`. -- [plugin-inventory](../../host/plugin-inventory/README.md) — the Host-side read-only Loader projection this tab renders. - ------ - - -## Model Experience - -None, as the package is a browser-side inventory projection that registers nothing model-facing. - -#### KV Cache effect - -None; this package neither assembles nor sends a provider request. - -## Known Limitations and Deferred Work - - - - -These limits define the freshness and reach of the inventory view; they are current package constraints. - -- **One snapshot per Settings mount or retry** — the tab does not subscribe to Loader changes or automatically refetch after reconnect; switching tabs preserves the current snapshot, while reopening Settings obtains a new one. -- **Read-only in both planes** — the tab shows global and preset enablement but mutates neither; enable/disable controls that write a custom preset's own composition file are deliberate follow-up work. - - -### Dev Note - -
      -Working context for maintainers — click to expand - -None. - -
      diff --git a/packages/client/ui-settings-plugin-inventory/README.zh.md b/packages/client/ui-settings-plugin-inventory/README.zh.md deleted file mode 100644 index f061018cef..0000000000 --- a/packages/client/ui-settings-plugin-inventory/README.zh.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -description: "dsh Web 客户端设置中按作用域分组的只读插件清单标签页:Agent 预设组合在前,全局平面收在折叠分组里,搜索跨两组。" -kind: "package-reference" ---- - -# @deepseek-ai/dsh-client-ui-settings-plugin-inventory - -[English](README.md) | 中文 - -## 概述 - -**插件列表**标签页让 Web 用户查看插件,而不改变其配置。它先列 agent(智能体)预设分组,再列全局清单;预设分组默认展开,全局分组默认收起,搜索期间两组都展开。卡片显示可用的本地化标题与描述,以稳定的条目 id 标识实例,并展示启停状态、出处、运行状态、禁用条件与发现失败;由预设提供的全局条目会列出对应预设。搜索覆盖两个分组,并指出其他预设中的匹配。标签页处理加载、空结果、无匹配、失败与重试状态,且不暴露传输细节;没有预设 roster 时仍会展示全局清单。 - -## 目录 - -- [使用本包](#use-this-package) -- [理解实现](#understand-the-implementation) -- [进一步探索](#further-exploration) -- [模型体验](#model-experience) -- [已知限制与延期工作](#known-limitations-and-deferred-work) -- [开发备注](#dev-note) - ------ - - -## 使用本包 - -打开设置中的「插件」分区并选择**插件列表**标签页,即可查看宿主的插件清单。插件激活期间不会读取 Remote——首次选择该标签页时才挂载组件,并通过 `api-remotes` 懒调用 `ctx.remote.pluginInventory.list()`。 - -安装失败且存在待审批的 pnpm 构建权限时,页面提供“允许这些脚本并重试”。该操作展示准确包名和持久授权范围,再使用原来的包规格及启用选项重试。一次点击批准整个列表,其中可能包括此前安装留下的待审批包。关闭页面不会授予权限。 - -### 阅读卡片 - -每张收起的卡片使用插件可用的本地化标题与描述;描述最多显示两行,展开卡片后显示全文。设置页会缩短字面的包名或模块名回退值,移除 npm scope 以及 `cordis:`、`cordis-plugin-` 或 `dsh-`/`dsh-host-`/`dsh-client-` 前缀;locale 标题保持原样。Host 在 `meta` 中提供 locale 与包字段的回退结果,Client 选择当前语言。详情与搜索仍保留完整模块标识。缺失的描述不显示,元信息诊断随卡片展示。这种短名显示仅用于设置页,不影响侧栏的插件页。 - -表示启停状态的小标签只标记与普通启用不同的状态:已停用、条件启用、由预设提供与启动失败;普通启用的行不带标签。彩色根 fiber 状态圆点标记没有标签表达的存活阶段:`pending` 映射为 idle,`loading` 与 `unloading` 映射为 ongoing;`active` 或 `failed` fiber 不显示圆点。稳定的条目 id 仅在与标题不同时显示,位于卡片左下角的代码标签中,与标题左对齐:组合生成的 id 在此省略开头的 `include:` 标记,省略后与标题相同的 id 不再重复显示。显示代码标签时,其悬停提示与卡片的无障碍名称带完整 id;搜索与展开详情始终保留完整 id。长条目 id 会在代码标签内截断,悬停时仍可查看完整值。展开卡片后会显示完整描述、声明的条目 id、完整模块标识与状态事实:预设行说明它来自哪个预设、组合存活时的运行状态,以及它携带的禁用条件;被预设提供的全局行说明它由 Agent 预设按会话提供、列出启用它的预设。预设名经共享的 `presetDisplayText` 纯函数(`dsh-agent-preset-registry/display`)叠在 [`ui-agent-preset`](../ui-agent-preset/README.zh.md) 的字典上解析:内置预设走当前语言,用户自建预设保留自己的元数据,因此英文界面不会回显预设声明里的中文名。搜索按本地化标题与描述、模块名称及条目 id 过滤两组。 - -卡片只在可悬停的指针下绘制悬停底色:点按以按下填充回馈,展开的卡片在任何设备上保持展开底色。搜索框在粗指针下使用 16px 字号,iOS Safari 不会因聚焦而放大页面。 - -### 预设切换器 - -切换器与通用设置各行使用同一种「选择胶囊 + 菜单」控件。它列出 roster 的每个预设——默认项带后缀、坏预设带标记——并且只改变列表显示什么:它不写任何设置,选中坏预设时在行的位置展示 discovery 报告的原因。选择默认预设或会话预设的入口仍在原处:Agent 预设分区与新会话页。 - -### 重试失败的读取 - -读取失败会在标签页内渲染共享 error 标记。加载时在卡片网格中显示骨架卡片,当前页面同步使用共享 ongoing loading。重试会重新执行懒 `list()` 调用,且不会暴露传输细节。 - -插件列表还显示当前页面的同步失败。重试会重新应用最新客户端图,不改变 Host 启用状态,也不刷新页面。 - ------ - - -## 理解实现 - -
      -实现细节——点击展开 - -该标签页是宿主拥有快照的只读投影;插件激活期间不执行任何 Remote 读取,首次选择时才取快照。 - -### 注册 - -浏览器插件注册一个 id 为 `all` 的本地化 `settings.plugins.tab` 贡献;「插件」分区拥有导航入口与标签栏。注册使用 `ctx.slots.inject()`,因此能跟随标签 slot 的延迟声明、重新声明、本地化变化与 teardown,而无需 import 分区拥有方。 - -### 渲染 - -行 key 按作用域限定(`global:`、`preset::`),因此同一模块出现在两个作用域时保持各自的展开状态;声明的条目 id 出现在展开详情中;去掉开头的组合 `include:` 标记后若与标题不同,则作为收起卡片的 id 代码标签,没有 id 的行不显示次级标签。预设提供标记在客户端推导:一个全局条目在全局被停用、且至少一个预设行对同一模块标识实际启用时才携带它,因此被所有预设关掉(或仅条件声明)的模块保持单纯的已停用,而不是夸大提供关系。 - -
      - ------ - - -## 进一步探索 - -以下页面覆盖设置分区、Remote 调用与宿主侧投影。 - -- [ui-settings-plugins](../ui-settings-plugins/README.zh.md)——本标签页注册进的「插件」分区。 -- [ui-settings](../ui-settings/README.zh.md)——声明 `settings.plugins.tab` 的领域底座。 -- [api-remotes](../../api/remotes/README.zh.md)——`pluginInventory.list()` 背后的 Remote BFF 表面。 -- [plugin-inventory](../../host/plugin-inventory/README.zh.md)——本标签页所渲染的宿主侧只读 Loader 投影。 - ------ - - -## 模型体验 - -无。该包是浏览器端清单投影,不注册任何面向模型的内容。 - -#### KV Cache 影响 - -无;该包既不组装也不发送提供方请求。 - -## 已知限制与延期工作 - - - - -这些限制定义清单视图的新鲜度与触达范围;它们是当前包约束。 - -- **每次 Settings 挂载或重试只读取一份快照**:标签页不订阅 Loader 变化,也不会在重连后自动重新读取;切换标签页会保留当前快照,重新打开 Settings 则会取得新快照。 -- **两个平面都只读**:标签页展示全局与预设的启停状态但都不修改;写回自定义预设组合文件的启停控件是刻意留作后续的工作。 - - -### 开发备注 - -
      -维护者的工作上下文——点击展开 - -无。 - -
      diff --git a/packages/client/ui-settings-plugin-inventory/locale/de.json b/packages/client/ui-settings-plugin-inventory/locale/de.json deleted file mode 100644 index e949caba64..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/de.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Integrierte Plug-in-Listenschnittstelle", - "description": "Überprüfen Sie in den Einstellungen die globalen Plug-Ins und Plug-Ins, die von jedem Agenten verwendet werden." - } -} diff --git a/packages/client/ui-settings-plugin-inventory/locale/en.json b/packages/client/ui-settings-plugin-inventory/locale/en.json deleted file mode 100644 index 38e92db659..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/en.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "meta": { - "title": "ui-settings-plugin-inventory" - } -} diff --git a/packages/client/ui-settings-plugin-inventory/locale/es.json b/packages/client/ui-settings-plugin-inventory/locale/es.json deleted file mode 100644 index 32ef114ca5..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/es.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interfaz de lista de complementos incorporada", - "description": "Verifique los complementos globales y los complementos utilizados por cada Agente en la configuración." - } -} diff --git a/packages/client/ui-settings-plugin-inventory/locale/fr.json b/packages/client/ui-settings-plugin-inventory/locale/fr.json deleted file mode 100644 index a83279a5dc..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/fr.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interface de liste de plug-ins intégrée", - "description": "Vérifiez les plug-ins globaux et les plug-ins utilisés par chaque Agent dans les paramètres." - } -} diff --git a/packages/client/ui-settings-plugin-inventory/locale/ja.json b/packages/client/ui-settings-plugin-inventory/locale/ja.json deleted file mode 100644 index 8c90e7eb4b..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/ja.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "組み込みプラグイン一覧 UI", - "description": "設定でグローバルプラグインと各エージェントプリセットのプラグインを確認します。" - } -} diff --git a/packages/client/ui-settings-plugin-inventory/locale/pt.json b/packages/client/ui-settings-plugin-inventory/locale/pt.json deleted file mode 100644 index c82847e91e..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/pt.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interface de lista de plug-ins integrada", - "description": "Verifique os plug-ins globais e plug-ins usados por cada Agente nas configurações." - } -} diff --git a/packages/client/ui-settings-plugin-inventory/locale/ru.json b/packages/client/ui-settings-plugin-inventory/locale/ru.json deleted file mode 100644 index 4d1b1aae31..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/ru.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Встроенный интерфейс списка плагинов", - "description": "Проверьте в настройках глобальные плагины и плагины, используемые каждым Агентом." - } -} diff --git a/packages/client/ui-settings-plugin-inventory/locale/zh.json b/packages/client/ui-settings-plugin-inventory/locale/zh.json deleted file mode 100644 index df4f5ab36f..0000000000 --- a/packages/client/ui-settings-plugin-inventory/locale/zh.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "内置插件列表界面", - "description": "在设置中查看全局插件和各 Agent 预设使用的插件。" - } -} diff --git a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css deleted file mode 100644 index db943b1066..0000000000 --- a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css +++ /dev/null @@ -1,512 +0,0 @@ -/* The tab's own width, not the window's, decides the card columns below. */ -.section { - container: plugin-inventory / inline-size; - display: flex; - flex-direction: column; - gap: 14px; - width: 100%; - max-width: 760px; - color: var(--dsw-alias-label-primary); -} - -.status, -.failure p { - margin: 0; -} - -.status, -.failure { - font-size: 13px; - line-height: 20px; - color: var(--dsw-alias-label-tertiary); -} - -.failure { - display: flex; - align-items: center; - gap: 10px; - color: var(--dsw-alias-state-error-primary); -} - -.statusWithDot { - display: inline-flex; - align-items: center; - gap: 6px; -} - -.failure button { - border: 0.5px solid var(--dsw-alias-border-l3); - border-radius: var(--dsw-radius-sm); - padding: 4px 10px; - background: transparent; - color: var(--dsw-alias-label-primary); - font: inherit; - cursor: pointer; -} - -.catalog { - display: flex; - flex-direction: column; - gap: 12px; -} - -.search { - position: relative; - display: flex; - align-items: center; - width: 100%; - color: var(--dsw-alias-label-tertiary); -} - -.search > svg { - position: absolute; - left: 12px; - pointer-events: none; -} - -.search input { - width: 100%; - height: 36px; - border: 0.5px solid var(--dsw-alias-border-l4); - border-radius: var(--dsw-radius-md); - padding: 0 34px 0 36px; - outline: none; - background: var(--dsw-alias-bg-layer-1); - color: var(--dsw-alias-label-primary); - font: inherit; - font-size: 13px; -} - -.search input::placeholder { - color: var(--dsw-alias-label-tertiary); -} - -.search input:focus-visible { - border-color: var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - box-shadow: 0 0 0 2px color-mix(in srgb, var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)) 18%, transparent); -} - -.cards { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 10px; - margin: 0; - padding: 0; - list-style: none; -} - -/* Cards stretch to their grid row's height. The button fills a stretched card: - the title row and description stay at the top, in line with the other card's, - and the spare height sits above the entry id chip or at the bottom. */ -.card { - display: flex; - flex-direction: column; - min-width: 0; - overflow: hidden; - border: 0.5px solid var(--dsw-alias-settings-card-stroke); - border-radius: var(--dsw-radius-xl); - background: var(--dsw-alias-settings-card-fill); -} - -.card[data-open='true'] { - border-color: var(--dsw-alias-border-l3); -} - -/* The other card in an expanded card's row keeps its own height instead of - stretching alongside the details. The selectors assume the two columns - `.cards` declares, where each row starts at an odd position, and must change - with that count; in one column the matched card sits alone in its row. */ -.card:nth-child(odd)[data-open='true'] + .card, -.card:nth-child(odd):has(+ .card[data-open='true']) { - align-self: start; -} - -.cardContent { - box-sizing: border-box; - display: flex; - flex: 1 1 auto; - flex-direction: column; - align-items: stretch; - gap: 2px; - width: 100%; - min-height: 52px; - border: 0; - padding: 12px 14px; - background: transparent; - color: inherit; - font: inherit; - text-align: left; - cursor: pointer; -} - -.card[data-open='true'] > .cardContent { - background: var(--dsw-alias-interactive-bg-hover); -} - -/* Hover stays behind @media (hover: hover) so a tap cannot latch it; the press - state carries the feedback a touch client would otherwise lose. */ -.cardContent:active { - background: var(--dsw-alias-interactive-bg-active); -} - -@media (hover: hover) { - .cardContent:hover { - background: var(--dsw-alias-interactive-bg-hover); - } -} - -.cardContent:focus-visible { - outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - outline-offset: -2px; -} - -.cardMainRow { - display: flex; - align-items: center; - justify-content: space-between; - gap: 12px; - min-width: 0; -} - -.cardTitle, -.cardIdentity { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.cardTitle { - flex: 1; - min-width: 0; - font-size: 14px; - line-height: 20px; - font-weight: 500; -} - -/* Two lines at most while collapsed; the expanded card shows the full text. */ -.cardDescription { - display: -webkit-box; - overflow: hidden; - color: var(--dsw-alias-label-tertiary); - font-size: 12px; - line-height: 18px; - text-wrap: pretty; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; -} - -.card[data-open='true'] .cardDescription { - display: block; -} - -/* The entry id is metadata, not prose: a code chip in the card's bottom-left - corner whose left edge lines up with the title. */ -.cardMeta { - display: flex; - margin-top: auto; - padding-top: 6px; -} - -/* The Loader entry id keeps one size in the card chip and the row it expands into; - the collapsed chip stays on the quieter label tier, while the expanded row carries - the card's primary value. */ -.cardIdentity, -.entryValue { - font-family: var(--ds-font-family-code); - font-size: 12px; - line-height: 18px; -} - -.cardIdentity { - display: block; - box-sizing: border-box; - max-width: 100%; - border-radius: var(--dsw-radius-xs); - padding: 1px 6px; - background: var(--dsw-alias-bg-module-platform); - color: var(--dsw-alias-label-secondary); -} - -.cardTrailing { - display: inline-flex; - flex: none; - align-items: center; - gap: 8px; - color: var(--dsw-alias-label-tertiary); -} - -/* Accessible-name and layout wrapper: StateDot is aria-hidden and carries no - name, and the row needs the phase to stay on one flex line. */ -.phaseDot { - display: inline-flex; - flex: none; -} - -.group { - display: flex; - flex-direction: column; - gap: 10px; -} - -/* Every group header takes the preset switcher's 36px height, so each subtitle - sits the same distance below its title. */ -.groupTitleRow { - display: flex; - align-items: center; - gap: 8px; - min-height: 36px; -} - -.group + .group { - border-top: 0.5px solid var(--dsw-alias-border-l2); - padding-top: 14px; -} - -.headerEnd { - margin-left: auto; -} - -.groupToggle { - display: flex; - flex: none; - align-items: center; - gap: 8px; - border: 0; - padding: 0; - background: transparent; - color: inherit; - font: inherit; - text-align: left; - cursor: pointer; -} - -.groupToggle:focus-visible { - outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - outline-offset: 2px; -} - -.groupToggle > .chevron { - transform: rotate(-90deg); -} - -.groupToggle[aria-expanded='true'] > .chevron { - transform: none; -} - -.groupTitle { - font-size: 14px; - line-height: 22px; - font-weight: 400; - color: var(--dsw-alias-label-primary); -} - -.groupSub { - display: flex; - flex-wrap: wrap; - row-gap: 4px; - margin: -6px 0 0 20px; - color: var(--dsw-alias-label-tertiary); - font-size: 12px; - line-height: 18px; - font-variant-numeric: tabular-nums; -} - -/* The preset switcher trigger mirrors the General-settings selector pill. */ -.switcher { - display: inline-flex; - flex: none; - align-items: center; - gap: 12px; - height: 36px; - white-space: nowrap; - border: none; - border-radius: var(--dsw-radius-md); - padding: 0 14px; - background: var(--dsw-alias-bg-module-platform); - color: var(--dsw-alias-label-primary); - font: inherit; - font-size: 14px; - line-height: 22px; - cursor: pointer; -} - -.switcher:active { - background: var(--dsw-alias-interactive-bg-active); -} - -@media (hover: hover) { - .switcher:hover { - background: var(--dsw-alias-interactive-bg-hover); - } -} - -.switcher:focus-visible { - outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - outline-offset: 2px; -} - -.switcher > .chevron { - flex: none; -} - -.switcherLabel { - max-width: 240px; - overflow: hidden; - text-overflow: ellipsis; -} - - -.groupBody { - display: flex; - flex-direction: column; - gap: 10px; -} - - -.brokenNote { - margin: 0; - border-radius: var(--dsw-radius-lg); - padding: 8px 10px; - background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 8%, transparent); - color: var(--dsw-alias-state-error-primary); - font-size: 12px; - line-height: 18px; - overflow-wrap: anywhere; - white-space: pre-line; -} - -.hint { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 4px 8px; - margin: 0; - color: var(--dsw-alias-label-tertiary); - font-size: 12px; - line-height: 18px; -} - -.jumpLink { - border: 0; - padding: 0; - background: transparent; - color: var(--dsw-alias-state-business-primary); - font: inherit; - font-size: 12px; - cursor: pointer; -} - -/* Loading placeholder in the cards grid, sized like a card with one description - line; its bars pulse through the shared skeleton token as the input-trigger - menu's pending rows do. */ -.skeletonCard { - display: flex; - flex-direction: column; - gap: 8px; - border: 0.5px solid var(--dsw-alias-settings-card-stroke); - border-radius: var(--dsw-radius-xl); - padding: 15px 14px; - background: var(--dsw-alias-settings-card-fill); -} - -.skeletonBar { - width: 40%; - height: 14px; - border-radius: var(--dsw-radius-xs); - background: var(--dsw-alias-bg-skeleton); -} - -.skeletonBar + .skeletonBar { - width: 80%; - height: 12px; -} - -.card[data-failed='true'] { - border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent); -} - -.chevron { - flex: none; - color: var(--dsw-alias-label-tertiary); -} - -.card[data-open='true'] .chevron { - transform: rotate(180deg); -} - -.cardDetails { - border-top: 0.5px solid var(--dsw-alias-border-l2); - padding: 10px 14px 12px; - background: var(--dsw-alias-bg-module-platform); -} - -.entryValue { - display: block; - overflow-wrap: anywhere; - color: var(--dsw-alias-label-primary); -} - -.details { - display: grid; - grid-template-columns: 76px minmax(0, 1fr); - gap: 6px 10px; - margin: 8px 0 0; -} - -.details div { - display: contents; -} - -.details dt { - color: var(--dsw-alias-label-tertiary); - font-size: 11px; - line-height: 17px; -} - -.details dd { - min-width: 0; - margin: 0; - overflow-wrap: anywhere; - color: var(--dsw-alias-label-secondary); - font-size: 12px; - line-height: 17px; -} - -.visuallyHidden { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip: rect(0 0 0 0); - clip-path: inset(50%); - white-space: nowrap; -} - -@media (prefers-reduced-motion: no-preference) { - .chevron { - transition: transform 140ms var(--ds-ease-in-out); - } - - .skeletonBar { - animation: plugin-inventory-skeleton 2s cubic-bezier(0.36, 0, 0.64, 1) infinite; - } -} - -@keyframes plugin-inventory-skeleton { - 0% { opacity: 1; } - 40% { opacity: 0.6; } - 80%, 100% { opacity: 1; } -} - -@container plugin-inventory (max-width: 520px) { - .cards { - grid-template-columns: minmax(0, 1fr); - } -} - -/* iOS Safari zooms the visual viewport for a focused field under 16px. */ -@media (pointer: coarse) { - .search input { - font-size: 16px; - } -} diff --git a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx deleted file mode 100644 index 8138b0d397..0000000000 --- a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx +++ /dev/null @@ -1,580 +0,0 @@ -import { useEffect, useId, useMemo, useState, type ReactNode } from 'react' -import type { ClientEntryState } from '@deepseek-ai/dsh-client-modules/client' -import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' -import type { PluginInventorySnapshot } from '@deepseek-ai/dsh-api-remotes/client' -import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' -import { - IconChevronDownOutlineRegular, - IconSearchOutlineRegular, - Menu, - StateDot, - Tag, -} from '@deepseek-ai/dsh-client-ui-primitives' -import type { StateDotState, TagTone } from '@deepseek-ai/dsh-client-ui-primitives' -import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { PluginInventoryLocaleKey } from './locales.ts' -import css from './PluginInventorySettingsTab.module.css' - -type PluginInventoryEntry = PluginInventorySnapshot['entries'][number] -type AgentPresetGroup = NonNullable[number] -type AgentPresetRow = AgentPresetGroup['rows'][number] - -/** Registration-side Remote face used by the section. */ -export interface PluginInventorySettingsTabInjected { - /** Resolve local package text in the current Client locale at render time. */ - resolveText: (text: LocalizedText) => string - /** Page-local module synchronization, independent from the Host inventory. */ - hooks: { clientSync: ObservableSnapshot } - /** Retry the latest client graph without changing the Host composition. */ - retryClient: () => void - /** Read a current Host inventory snapshot. */ - list: () => Promise - /** - * Display name for one preset: shipped presets resolve through the - * agent-preset dictionaries, user-authored ones keep their own metadata. - */ - presetName: (preset: AgentPresetGroup) => string -} -type PluginFiberPhase = PluginInventoryEntry['fiberPhase'] - -/** Full component props assembled by the Settings slot renderer. */ -export type PluginInventorySettingsTabProps = - PropsRuntime<'settings.plugins.tab'> - & PropsLocale<'settings.pluginInventory'> - & InjectFace - -type Translate = PluginInventorySettingsTabProps['t'] - -type ViewState = - | { readonly status: 'loading' } - | { readonly status: 'error' } - | { readonly status: 'ready'; readonly snapshot: PluginInventorySnapshot } - -const PHASE_KEYS = { - pending: 'pending', - loading: 'loadingPhase', - active: 'active', - failed: 'failed', - unloading: 'unloading', -} satisfies Record, PluginInventoryLocaleKey> - -/** Placeholder cards the loading skeleton lays out in the cards grid. */ -const SKELETON_CARDS = [0, 1, 2, 3] as const - -/** Localized accessible label for one root Fiber phase. */ -function phaseLabel(phase: PluginFiberPhase, t: Translate): string { - return phase === null ? t('unobserved') : t(PHASE_KEYS[phase]) -} - -/** Compact technical names for Settings without changing their module identity. */ -function moduleShortName(moduleName: string): string { - const unscoped = moduleName.startsWith('@') ? moduleName.slice(moduleName.indexOf('/') + 1) : moduleName - return unscoped - .replace(/^cordis:/, '') - .replace(/^cordis-plugin-/, '') - .replace(/^dsh-(?:host-|client-)?/, '') -} - -/** Display an entry identity without the composition-only `include:` marker. */ -function entrySubtitle(entryId: string): string { - return entryId.replace(/^include:/, '') -} - -/** Whether a card shows its entry id: the id exists and, without its `include:` marker, differs from the title. */ -function idAddsToTitle(entryId: string | null, title: string): entryId is string { - return entryId !== null && entrySubtitle(entryId) !== title -} - -/** Accessible card name: the title, the complete entry id when the card shows one, then the enablement state. */ -function cardLabel(title: string, entryId: string | null, state: string): string { - return idAddsToTitle(entryId, title) ? `${title}, ${entryId}, ${state}` : `${title}, ${state}` -} - -/** Preserve translated titles and shorten literal package or module name fallbacks in Settings. */ -function pluginText(row: PluginInventoryEntry | AgentPresetRow, resolveText: PluginInventorySettingsTabInjected['resolveText']) { - const title = row.meta?.title - return { - title: typeof title === 'object' ? resolveText(title) : moduleShortName(title ?? row.moduleName), - description: row.meta?.description === undefined ? undefined : resolveText(row.meta.description) || undefined, - } -} - -/** Match translated text alongside the row's technical module and entry identities. */ -function matches(row: PluginInventoryEntry | AgentPresetRow, normalizedQuery: string, resolveText: PluginInventorySettingsTabInjected['resolveText']): boolean { - if (normalizedQuery.length === 0) return true - const { title, description } = pluginText(row, resolveText) - return [row.moduleName, row.entryId, title, description] - .some(value => value?.toLocaleLowerCase().includes(normalizedQuery)) -} - -/** The roster row shown when the preset switcher has no explicit choice. */ -function fallbackPreset(presets: readonly AgentPresetGroup[]): AgentPresetGroup | undefined { - return presets.find(preset => preset.isDefault) ?? presets[0] -} - -/** The switcher's display label for one preset. */ -function presetLabel(preset: AgentPresetGroup, t: Translate, presetName: (preset: AgentPresetGroup) => string): string { - const name = presetName(preset) - if (preset.broken !== undefined) return t('presetOptionBroken', { name }) - if (preset.isDefault) return t('presetOptionDefault', { name }) - return name -} - -/** One expandable plugin card; the caller owns the trailing status content. */ -function PluginCard({ - rowKey, moduleName, title, description, metadataError, entryId, trailing, ariaLabel, failed, expanded, onToggle, children, -}: { - readonly rowKey: string - readonly moduleName: string - readonly title: string - readonly description: string | undefined - readonly metadataError: string | undefined - readonly entryId: string | null - readonly trailing: ReactNode - readonly ariaLabel: string - readonly failed: boolean - readonly expanded: string | null - readonly onToggle: (key: string) => void - readonly children: ReactNode -}): ReactNode { - const open = expanded === rowKey - const detailId = `plugin-details-${encodeURIComponent(rowKey)}` - const descriptionId = useId() - return ( -
    • - - {metadataError === undefined ? null :

      {metadataError}

      } - {open ?
      {children}
      : null} -
    • - ) -} - -/** Detail rows shared by every card: the Loader identity, then labeled facts. */ -function CardFacts({ moduleName, moduleLabel, entryId, facts }: { - readonly moduleName: string - readonly moduleLabel: string - readonly entryId: string | null - readonly facts: readonly (readonly [label: string, value: ReactNode])[] -}): ReactNode { - return ( - <> - {entryId === null ? null : {entryId}} -
      -
      -
      {moduleLabel}
      -
      {moduleName}
      -
      - {facts.map(([label, value]) => ( -
      -
      {label}
      -
      {value}
      -
      - ))} -
      - - ) -} - -/* `pending` is the only dotted phase with no work under way. `loading` and - * `unloading` are both live transitions the Host is running — an async - * disposer can hold `unloading` for a while — so both animate. `active` and - * `failed` carry no dot: a settled enabled row needs no marker, and a failed - * row has the failure tag. */ -const PHASE_DOT_STATES = { - pending: 'idle', - loading: 'ongoing', - unloading: 'ongoing', -} as const satisfies Partial, StateDotState>> - -/** A live root-fiber phase the row marks with a dot. */ -type DotPhase = keyof typeof PHASE_DOT_STATES - -/** Whether a live root-fiber phase carries a dot of its own. */ -function showsPhaseDot(phase: PluginFiberPhase): phase is DotPhase { - return phase === 'pending' || phase === 'loading' || phase === 'unloading' -} - -/** Status dot naming a live root-fiber phase; rows without a dotted phase show none. */ -function PhaseDot({ phase, t }: { readonly phase: DotPhase; readonly t: Translate }): ReactNode { - const status = phaseLabel(phase, t) - /* StateDot is aria-hidden, so the phase name lives on this wrapper. */ - return ( - - - - ) -} - -/** Enablement states one inventory row can report. */ -type EnablementKind = 'enabled' | 'disabled' | 'conditional' | 'preset' | 'failed' - -const TAG_TONES = { - disabled: 'neutral', - conditional: 'warning', - preset: 'info', - failed: 'danger', -} as const satisfies Record, TagTone> - -/** Enablement tag for the states that depart from the default; a plainly enabled row carries none. */ -function StateTag({ kind, label }: { readonly kind: EnablementKind; readonly label: string }): ReactNode { - return kind === 'enabled' ? null : {label} -} - -/** Render the read-only plugin inventory: agent presets first, then the global plane. */ -export function PluginInventorySettingsTab( - { list, presetName, resolveText, t, useClientSync, retryClient }: PluginInventorySettingsTabProps, -): ReactNode { - const clientSync = useClientSync(snapshot => snapshot) - const sectionId = useId() - const [request, setRequest] = useState(0) - const [query, setQuery] = useState('') - const [expanded, setExpanded] = useState(null) - const [chosenPreset, setChosenPreset] = useState(null) - const [switcherOpen, setSwitcherOpen] = useState(false) - const [presetOpen, setPresetOpen] = useState(null) - const [globalOpen, setGlobalOpen] = useState(null) - const [state, setState] = useState({ status: 'loading' }) - - useEffect(() => { - let current = true - void Promise.resolve().then(() => list()).then( - (snapshot) => { if (current) setState({ status: 'ready', snapshot }) }, - () => { if (current) setState({ status: 'error' }) }, - ) - return () => { current = false } - }, [list, request]) - - const normalizedQuery = query.trim().toLocaleLowerCase() - const searching = normalizedQuery.length > 0 - const snapshot = state.status === 'ready' ? state.snapshot : undefined - const presets = snapshot?.agentPresets ?? [] - const selected = presets.find(preset => preset.id === chosenPreset) ?? fallbackPreset(presets) - - /** Presets that actually enable a module, keyed by module name. */ - const enabledIn = useMemo(() => { - const found = new Map() - for (const preset of presets) { - for (const row of preset.rows) { - if (row.enabled !== true) continue - const groups = found.get(row.moduleName) - if (groups === undefined) found.set(row.moduleName, [preset]) - else if (!groups.includes(preset)) groups.push(preset) - } - } - return found - }, [presets]) - - const entries = snapshot?.entries ?? [] - const failedEntries: PluginInventoryEntry[] = [] - const regularEntries: PluginInventoryEntry[] = [] - for (const entry of entries) { - if (entry.fiberPhase === 'failed') failedEntries.push(entry) - else regularEntries.push(entry) - } - - const entryMatch = (entry: PluginInventoryEntry): boolean => matches(entry, normalizedQuery, resolveText) - const rowMatch = (row: AgentPresetRow): boolean => matches(row, normalizedQuery, resolveText) - const filteredFailed = failedEntries.filter(entryMatch) - const filteredRegular = regularEntries.filter(entryMatch) - const globalCount = filteredFailed.length + filteredRegular.length - const selectedRows = selected === undefined ? [] : selected.rows.filter(rowMatch) - const otherPresetMatches = searching - ? presets.filter(preset => preset !== selected && preset.rows.some(rowMatch)) - : [] - const otherMatchCount = otherPresetMatches - .reduce((total, preset) => total + preset.rows.filter(rowMatch).length, 0) - - // The preset group starts open and the larger global plane folded; a search opens both for as long as it lasts. - const presetEffectiveOpen = searching || (presetOpen ?? true) - const globalEffectiveOpen = searching || (globalOpen ?? false) - const nothingMatches = searching && globalCount === 0 && selectedRows.length === 0 - && otherPresetMatches.length === 0 - - const retry = (): void => { - setState({ status: 'loading' }) - setRequest(value => value + 1) - } - const toggleRow = (key: string): void => { - setExpanded(current => current === key ? null : key) - } - - /** Trailing status and detail facts for one row of the selected preset. */ - const presetRowCard = (preset: AgentPresetGroup, row: AgentPresetRow, index: number): ReactNode => { - const key = `preset:${preset.id}:${String(index)}` - const { title, description } = pluginText(row, resolveText) - const failed = row.fiberPhase === 'failed' - const stateText = failed - ? t('failedTag') - : row.enabled === true ? t('enabledTag') : row.enabled === false ? t('disabledTag') : t('conditionalTag') - const kind = failed ? 'failed' : row.enabled === true ? 'enabled' : row.enabled === false ? 'disabled' : 'conditional' - return ( - - {row.enabled === true && showsPhaseDot(row.fiberPhase) - ? - : null} - - - )} - > - {row.condition}] as const], - ]} - /> - - ) - } - - /** One global-plane row; a preset-provided row carries the presets that enable it. */ - const globalRowCard = ( - entry: PluginInventoryEntry, - providers?: readonly [AgentPresetGroup, ...AgentPresetGroup[]], - ): ReactNode => { - const key = `global:${entry.entryId}` - const { title, description } = pluginText(entry, resolveText) - const failed = entry.fiberPhase === 'failed' - const stateText = failed - ? t('failedTag') - : providers !== undefined ? t('presetEnabledTag') : t(entry.enabled ? 'enabledTag' : 'disabledTag') - const kind = failed ? 'failed' : providers !== undefined ? 'preset' : entry.enabled ? 'enabled' : 'disabled' - return ( - - {entry.enabled && showsPhaseDot(entry.fiberPhase) - ? - : null} - - - )} - > - presetName(preset)).join(' · ')], - ] - : [ - [t('configuration'), t(entry.enabled ? 'enabledTag' : 'disabledTag')], - ...entry.enabled ? [[t('runtime'), phaseLabel(entry.fiberPhase, t)] as const] : [], - ]} - /> - - ) - } - - return ( -
      - {clientSync.syncing ? ( -

      - {t('clientSyncing')} -

      - ) : null} - {clientSync.failures.length === 0 ? null : ( -
      -

      - {t('clientSyncFailed')} -

      -
        {clientSync.failures.map(failure =>
      • {failure.id}: {failure.message}
      • )}
      - -
      - )} - {state.status === 'loading' ? ( -
      - {t('loading')} - {SKELETON_CARDS.map(slot => ( - - ))} -
      - ) : null} - {state.status === 'error' ? ( -
      -

      - {t('error')} -

      - -
      - ) : null} - {snapshot !== undefined ? ( -
      - - {entries.length === 0 && presets.length === 0 ?

      {t('empty')}

      : null} - {nothingMatches ?

      {t('emptySearch')}

      : null} - - {selected !== undefined ? ( -
      -
      - -
      - { setSwitcherOpen(false) }} - items={presets.map(preset => ({ id: preset.id, label: presetLabel(preset, t, presetName) }))} - selectedId={selected.id} - onSelect={(id) => { - setSwitcherOpen(false) - setChosenPreset(id) - }} - align="end" - portal - anchor={( - - )} - /> -
      -
      -

      {t('presetSubtitle')}

      - {presetEffectiveOpen ? ( -
      - {selected.broken !== undefined ? ( -

      {selected.broken}

      - ) : null} - {selectedRows.length > 0 ? ( -
        - {selectedRows.map((row, index) => presetRowCard(selected, row, index))} -
      - ) : null} - {otherMatchCount > 0 ? ( -

      - {t('matchesInOtherPresets', { count: String(otherMatchCount) })} - {otherPresetMatches.map(preset => ( - - ))} -

      - ) : null} -
      - ) : null} -
      - ) : null} - - {entries.length > 0 ? ( -
      -
      - -
      -

      {t('globalSubtitle')}

      - {globalEffectiveOpen && globalCount > 0 ? ( -
        - {filteredFailed.map(entry => globalRowCard(entry))} - {filteredRegular.map(entry => globalRowCard( - entry, - entry.enabled ? undefined : enabledIn.get(entry.moduleName), - ))} -
      - ) : null} -
      - ) : null} -
      - ) : null} -
      - ) -} diff --git a/packages/client/ui-settings-plugin-inventory/src/client/index.ts b/packages/client/ui-settings-plugin-inventory/src/client/index.ts deleted file mode 100644 index acb324117a..0000000000 --- a/packages/client/ui-settings-plugin-inventory/src/client/index.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** Read-only Host plugin inventory registered into Web Settings. */ - -import type {} from '@deepseek-ai/dsh-client-locale/client' -import type {} from '@deepseek-ai/dsh-client-modules/client' -import type { Context as ClientContext } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-client-ui-settings/client' -import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' -// Type-only: pulls the 'settings.agentPreset' LocaleNamespaceMap merge, whose -// dictionaries the shipped-preset name resolution below reads. -import type {} from '@deepseek-ai/dsh-client-ui-agent-preset/client' -// Inline-safe shared fold: shipped ids map to dictionary keys in one home. -import { presetDisplayText } from '@deepseek-ai/dsh-agent-preset-registry/display' -import { PluginInventorySettingsTab, type PluginInventorySettingsTabInjected } from './PluginInventorySettingsTab.tsx' -import { en, ja, es, fr, de, ru, pt, zh, type PluginInventoryLocaleKey } from './locales.ts' - -export type { PluginInventorySettingsTabInjected, PluginInventorySettingsTabProps } from './PluginInventorySettingsTab.tsx' -export type { PluginInventoryLocaleKey } from './locales.ts' - -declare module '@deepseek-ai/dsh-client-ui-slots' { - interface LocaleNamespaceMap { - /** Read-only Host plugin inventory copy. */ - 'settings.pluginInventory': PluginInventoryLocaleKey - } -} - -/** Dictionary namespace owned by this plugin. */ -export const NS = 'settings.pluginInventory' - -/** Services required by the Settings registration and generated Remote face. */ -export const inject = ['slots', 'locale', 'remote', 'remote.pluginInventory', 'modules'] - -/** Contribute the lazy inventory tab to the Plugins settings section. */ -export function apply(ctx: ClientContext): void { - ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-settings-plugin-inventory: dictionaries') - - const t = ctx.locale.bind(NS) - const list: PluginInventorySettingsTabInjected['list'] = async () => { - const result = await ctx.remote.pluginInventory.list() - if (!result.ok) { - throw new Error(`pluginInventory.list failed: ${result.error.code}: ${result.error.message}`) - } - return result.value - } - // Resolved per call over ui-agent-preset's dictionaries, so a language - // switch re-resolves shipped names; user-authored metadata passes through. - const agentPresetCopy = ctx.locale.bind('settings.agentPreset') - const presetName: PluginInventorySettingsTabInjected['presetName'] = preset => - presetDisplayText(preset, agentPresetCopy).name - const injected = (): PluginInventorySettingsTabInjected => ({ - list, presetName, - resolveText: text => ctx.locale.resolveText(text), - hooks: { clientSync: ctx.modules.entries.state }, - retryClient: () => { void ctx.modules.entries.retry().catch((error: unknown) => { ctx.logger.error(error) }) }, - }) - - ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({ - name: 'settings.plugins.tab', - id: 'all', - order: 10, - label: () => t('tab'), - locale: NS, - inject: injected, - }, PluginInventorySettingsTab)) -} diff --git a/packages/client/ui-settings-plugin-inventory/src/client/locales.ts b/packages/client/ui-settings-plugin-inventory/src/client/locales.ts deleted file mode 100644 index d0d7480472..0000000000 --- a/packages/client/ui-settings-plugin-inventory/src/client/locales.ts +++ /dev/null @@ -1,332 +0,0 @@ -/** Copy dictionaries for the plugin inventory Settings section. */ - -/** Simplified Chinese dictionary and key source of truth. */ -export const zh = { - tab: '插件列表', - loading: '正在读取插件…', - clientSyncing: '正在同步本页面的插件…', - clientSyncFailed: '本页面的插件未能完成同步;服务端的启用状态保持不变。', - clientSyncRetry: '重试本页面同步', - error: '暂时无法读取插件。', - metadataError: '包元信息错误:{error}', - retry: '重试', - search: '搜索插件', - empty: '暂无插件。', - emptySearch: '没有匹配的插件。', - presetTitle: '会话插件', - presetSubtitle: '由 Agent 预设按会话组成', - switcherLabel: '选择要查看的 Agent 预设', - presetOptionDefault: '{name}(默认)', - presetOptionBroken: '{name}(加载失败)', - globalTitle: '全局插件', - globalSubtitle: '系统与所有会话共用', - presetProvidedDetail: '全局已停用,由 Agent 预设按会话提供', - enabledIn: '启用于', - matchesInOtherPresets: '其他预设中还有 {count} 个匹配:', - enabledTag: '已启用', - disabledTag: '已停用', - conditionalTag: '条件启用', - presetEnabledTag: '预设中启用', - failedTag: '启动失败', - moduleLabel: '完整名称', - fromPreset: '来自', - condition: '禁用条件', - configuration: '配置状态', - runtime: '运行状态', - unobserved: '未运行', - pending: '等待依赖', - loadingPhase: '加载中', - active: '运行中', - failed: '启动失败', - unloading: '卸载中', -} satisfies Record - -/** Plugin inventory locale key union. */ -export type PluginInventoryLocaleKey = keyof typeof zh - -/** English dictionary checked against the Chinese key set. */ -export const en = { - tab: 'Plugin list', - loading: 'Reading plugins…', - clientSyncing: 'Syncing plugins on this page…', - clientSyncFailed: 'Some plugins could not sync on this page. Host enablement is unchanged.', - clientSyncRetry: 'Retry this page', - error: 'Plugins are temporarily unavailable.', - metadataError: 'Package metadata error: {error}', - retry: 'Retry', - search: 'Search plugins', - empty: 'No plugins are available.', - emptySearch: 'No matching plugins.', - presetTitle: 'Session plugins', - presetSubtitle: 'Composed per session by agent presets', - switcherLabel: 'Choose the agent preset to inspect', - presetOptionDefault: '{name} (default)', - presetOptionBroken: '{name} (failed to load)', - globalTitle: 'Global plugins', - globalSubtitle: 'Shared by the system and every session', - presetProvidedDetail: 'Disabled globally; agent presets provide it per session', - enabledIn: 'Enabled in', - matchesInOtherPresets: '{count} more matches in other presets: ', - enabledTag: 'Enabled', - disabledTag: 'Disabled', - conditionalTag: 'Conditional', - presetEnabledTag: 'Via presets', - failedTag: 'Failed', - moduleLabel: 'Module', - fromPreset: 'From', - condition: 'Disabled when', - configuration: 'Configuration', - runtime: 'Status', - unobserved: 'Not running', - pending: 'Waiting for dependencies', - loadingPhase: 'Loading', - active: 'Running', - failed: 'Failed to start', - unloading: 'Unloading', -} satisfies Record - -/** Japanese copy, checked against the English keys. */ -export const ja = { - 'tab': 'プラグイン一覧', - 'loading': 'プラグインを読み込み中…', - 'clientSyncing': 'このページでプラグインを同期中…', - 'clientSyncFailed': '一部のプラグインをこのページで同期できませんでした。ホスト側の有効化状態は変更されていません。', - 'clientSyncRetry': 'このページを再試行', - 'error': 'プラグインは一時的に利用できません。', - 'metadataError': 'パッケージメタデータのエラー: {error}', - 'retry': '再試行', - 'search': 'プラグインを検索', - 'empty': '利用可能なプラグインはありません。', - 'emptySearch': '一致するプラグインはありません。', - 'presetTitle': 'セッションプラグイン', - 'presetSubtitle': 'エージェントプリセットによりセッションごとに構成されます', - 'switcherLabel': '確認するエージェントプリセットを選択', - 'presetOptionDefault': '{name} (デフォルト)', - 'presetOptionBroken': '{name} (読み込み失敗)', - 'globalTitle': 'グローバルプラグイン', - 'globalSubtitle': 'システムとすべてのセッションで共有', - 'presetProvidedDetail': 'グローバルでは無効。エージェントプリセットがセッションごとに提供します', - 'enabledIn': '有効化先', - 'matchesInOtherPresets': '他のプリセットにさらに{count}件一致: ', - 'enabledTag': '有効', - 'disabledTag': '無効', - 'conditionalTag': '条件付き', - 'presetEnabledTag': 'プリセット経由', - 'failedTag': '失敗', - 'moduleLabel': 'モジュール', - 'fromPreset': '提供元', - 'condition': '無効になる条件', - 'configuration': '構成', - 'runtime': 'ステータス', - 'unobserved': '停止中', - 'pending': '依存関係の待機中', - 'loadingPhase': '読み込み中', - 'active': '実行中', - 'failed': '起動に失敗', - 'unloading': 'アンロード中', -} satisfies Record - -/** Spanish dictionary, checked against the English keys. */ -export const es = { - tab: 'Lista de complementos', - loading: 'Leyendo complementos…', - clientSyncing: 'Sincronizando complementos en esta página…', - clientSyncFailed: 'Algunos complementos no se pudieron sincronizar en esta página. La habilitación del host no ha cambiado.', - clientSyncRetry: 'Reintentar esta página', - error: 'Los complementos no están disponibles temporalmente.', - metadataError: 'Error de metadatos del paquete: {error}', - retry: 'Reintentar', - search: 'Complementos de búsqueda', - empty: 'No hay complementos disponibles.', - emptySearch: 'No hay complementos coincidentes.', - presetTitle: 'Complementos de sesión', - presetSubtitle: 'Compuesto por sesión por ajustes preestablecidos de agente', - switcherLabel: 'Elija el agente preestablecido para inspeccionar', - presetOptionDefault: '{name} (predeterminado)', - presetOptionBroken: '{name} (no se pudo cargar)', - globalTitle: 'Complementos globales', - globalSubtitle: 'Compartido por el sistema y cada sesión.', - presetProvidedDetail: 'Discapacitados a nivel mundial; Los ajustes preestablecidos del agente lo proporcionan por sesión.', - enabledIn: 'Habilitado en', - matchesInOtherPresets: '{count} más coincidencias en otros ajustes preestablecidos: ', - enabledTag: 'Habilitado', - disabledTag: 'Discapacitado', - conditionalTag: 'Condicional', - presetEnabledTag: 'A través de ajustes preestablecidos', - failedTag: 'Fallido', - moduleLabel: 'Módulo', - fromPreset: 'De', - condition: 'Deshabilitado cuando', - configuration: 'Configuración', - runtime: 'Estado', - unobserved: 'no corriendo', - pending: 'Esperando dependencias', - loadingPhase: 'Cargando', - active: 'corriendo', - failed: 'No se pudo iniciar', - unloading: 'Descarga', -} satisfies Record - -/** French dictionary, checked against the English keys. */ -export const fr = { - tab: 'Liste des plugins', - loading: 'Plugins de lecture…', - clientSyncing: 'Synchronisation des plugins sur cette page…', - clientSyncFailed: "Certains plugins n'ont pas pu se synchroniser sur cette page. L'activation de l'hôte est inchangée.", - clientSyncRetry: 'Réessayez cette page', - error: 'Les plugins sont temporairement indisponibles.', - metadataError: 'Erreur de métadonnées du package : {error}', - retry: 'Réessayer', - search: 'Plugins de recherche', - empty: "Aucun plugin n'est disponible.", - emptySearch: 'Aucun plugin correspondant.', - presetTitle: 'Plugins de sessions', - presetSubtitle: "Composé par session par préréglages d'agent", - switcherLabel: "Choisissez le préréglage d'agent à inspecter", - presetOptionDefault: '{name} (par défaut)', - presetOptionBroken: '{name} (échec du chargement)', - globalTitle: 'Plugins globaux', - globalSubtitle: 'Partagé par le système et à chaque session', - presetProvidedDetail: "Handicapé à l'échelle mondiale ; les préréglages d'agent le fournissent par session", - enabledIn: 'Activé dans', - matchesInOtherPresets: "{count} plus de correspondances dans d'autres préréglages : ", - enabledTag: 'Activé', - disabledTag: 'Désactivé', - conditionalTag: 'Conditionnel', - presetEnabledTag: 'Via les préréglages', - failedTag: 'Échec', - moduleLabel: 'Module', - fromPreset: 'De', - condition: 'Désactivé quand', - configuration: 'Configuration', - runtime: 'Statut', - unobserved: 'Ne fonctionne pas', - pending: 'En attente de dépendances', - loadingPhase: 'Chargement', - active: 'Courir', - failed: 'Échec du démarrage', - unloading: 'Déchargement', -} satisfies Record - -/** German dictionary, checked against the English keys. */ -export const de = { - tab: 'Plugin-Liste', - loading: 'Plugins lesen…', - clientSyncing: 'Plugins auf dieser Seite werden synchronisiert…', - clientSyncFailed: 'Einige Plugins konnten auf dieser Seite nicht synchronisiert werden. Die Host-Aktivierung bleibt unverändert.', - clientSyncRetry: 'Versuchen Sie es erneut mit dieser Seite', - error: 'Plugins sind vorübergehend nicht verfügbar.', - metadataError: 'Paketmetadatenfehler: {error}', - retry: 'Erneut versuchen', - search: 'Such-Plugins', - empty: 'Es sind keine Plugins verfügbar.', - emptySearch: 'Keine passenden Plugins.', - presetTitle: 'Sitzungs-Plugins', - presetSubtitle: 'Zusammengestellt pro Sitzung nach Agentenvoreinstellungen', - switcherLabel: 'Wählen Sie die zu überprüfende Agentenvoreinstellung aus', - presetOptionDefault: '{name} (Standard)', - presetOptionBroken: '{name} (Laden fehlgeschlagen)', - globalTitle: 'Globale Plugins', - globalSubtitle: 'Wird vom System und jeder Sitzung geteilt', - presetProvidedDetail: 'Weltweit deaktiviert; Agentenvoreinstellungen stellen es pro Sitzung bereit', - enabledIn: 'Aktiviert in', - matchesInOtherPresets: '{count} weitere Übereinstimmungen in anderen Voreinstellungen: ', - enabledTag: 'Aktiviert', - disabledTag: 'Deaktiviert', - conditionalTag: 'Bedingt', - presetEnabledTag: 'Über Voreinstellungen', - failedTag: 'Fehlgeschlagen', - moduleLabel: 'Modul', - fromPreset: 'Von', - condition: 'Deaktiviert, wenn', - configuration: 'Konfiguration', - runtime: 'Status', - unobserved: 'Läuft nicht', - pending: 'Warten auf Abhängigkeiten', - loadingPhase: 'Laden', - active: 'Laufen', - failed: 'Start fehlgeschlagen', - unloading: 'Entladen', -} satisfies Record - -/** Russian dictionary, checked against the English keys. */ -export const ru = { - tab: 'Список плагинов', - loading: 'Чтение плагинов…', - clientSyncing: 'Синхронизация плагинов на этой странице…', - clientSyncFailed: 'Некоторые плагины не смогли синхронизироваться на этой странице. Включение хоста не изменилось.', - clientSyncRetry: 'Повторить эту страницу', - error: 'Плагины временно недоступны.', - metadataError: 'Ошибка метаданных пакета: {error}.', - retry: 'Повторить', - search: 'Поиск плагинов', - empty: 'Нет доступных плагинов.', - emptySearch: 'Нет подходящих плагинов.', - presetTitle: 'Плагины сеансов', - presetSubtitle: 'Составляется за сеанс с помощью предустановок агента', - switcherLabel: 'Выберите предустановку агента для проверки', - presetOptionDefault: '{name} (по умолчанию)', - presetOptionBroken: '{name} (не удалось загрузить)', - globalTitle: 'Глобальные плагины', - globalSubtitle: 'Совместно используется системой и каждым сеансом', - presetProvidedDetail: 'Отключено глобально; предустановки агента предусматривают это за сеанс', - enabledIn: 'Включено в', - matchesInOtherPresets: '{count} больше совпадений в других пресетах: ', - enabledTag: 'Включено', - disabledTag: 'Отключено', - conditionalTag: 'Условный', - presetEnabledTag: 'Через пресеты', - failedTag: 'Не удалось', - moduleLabel: 'Модуль', - fromPreset: 'От', - condition: 'Отключено, когда', - configuration: 'Конфигурация', - runtime: 'Статус', - unobserved: 'Не работает', - pending: 'Ожидание зависимостей', - loadingPhase: 'Загрузка', - active: 'Бег', - failed: 'Не удалось запустить', - unloading: 'Разгрузка', -} satisfies Record - -/** Portuguese dictionary, checked against the English keys. */ -export const pt = { - tab: 'Lista de plug-ins', - loading: 'Lendo plug-ins…', - clientSyncing: 'Sincronizando plug-ins nesta página…', - clientSyncFailed: 'Alguns plug-ins não puderam ser sincronizados nesta página. A ativação do host permanece inalterada.', - clientSyncRetry: 'Tente esta página novamente', - error: 'Os plug-ins estão temporariamente indisponíveis.', - metadataError: 'Erro de metadados do pacote: {error}', - retry: 'Tentar novamente', - search: 'Plug-ins de pesquisa', - empty: 'Nenhum plug-in está disponível.', - emptySearch: 'Nenhum plug-in correspondente.', - presetTitle: 'Plug-ins de sessão', - presetSubtitle: 'Composto por sessão por predefinições de agente', - switcherLabel: 'Escolha a predefinição do agente para inspecionar', - presetOptionDefault: '{name} (padrão)', - presetOptionBroken: '{name} (falha ao carregar)', - globalTitle: 'Plug-ins globais', - globalSubtitle: 'Compartilhado pelo sistema e por cada sessão', - presetProvidedDetail: 'Desativado globalmente; predefinições de agente fornecem isso por sessão', - enabledIn: 'Habilitado em', - matchesInOtherPresets: '{count} mais correspondências em outras predefinições: ', - enabledTag: 'Habilitado', - disabledTag: 'Desativado', - conditionalTag: 'Condicional', - presetEnabledTag: 'Por meio de predefinições', - failedTag: 'Falha', - moduleLabel: 'Módulo', - fromPreset: 'De', - condition: 'Desativado quando', - configuration: 'Configuração', - runtime: 'Estado', - unobserved: 'Não está em execução', - pending: 'Esperando por dependências', - loadingPhase: 'Carregando', - active: 'Correndo', - failed: 'Falha ao iniciar', - unloading: 'Descarregando', -} satisfies Record diff --git a/packages/client/ui-settings-plugin-inventory/src/index.ts b/packages/client/ui-settings-plugin-inventory/src/index.ts deleted file mode 100644 index 473386a9ec..0000000000 --- a/packages/client/ui-settings-plugin-inventory/src/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -/** Host loader entry for the inventory-tab browser implementation exported from `./client`. */ - -/** Host plugin body — no host-side behavior for the plugin inventory tab. */ -export function apply(): void {} diff --git a/packages/client/ui-settings-plugin-inventory/tests/browser-plugin.client.spec.tsx b/packages/client/ui-settings-plugin-inventory/tests/browser-plugin.client.spec.tsx deleted file mode 100644 index ea3d8ade8c..0000000000 --- a/packages/client/ui-settings-plugin-inventory/tests/browser-plugin.client.spec.tsx +++ /dev/null @@ -1,120 +0,0 @@ -// @vitest-environment jsdom -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { ClientModuleLoader } from '@deepseek-ai/dsh-client-modules/client' -import { Context, Service } from '@deepseek-ai/cordis' -import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' -import { cleanup } from '@testing-library/react' -import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' -import { usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' -import { apply, inject, NS } from '../src/client/index.ts' -import { PluginInventorySettingsTab } from '../src/client/PluginInventorySettingsTab.tsx' -import type { PluginInventorySettingsTabInjected } from '../src/client/PluginInventorySettingsTab.tsx' -import { apply as hostApply } from '../src/index.ts' - -usePinnedBrowserLanguages('zh-CN') -afterEach(cleanup) - -const EMPTY = { entries: [] } -type ListResult = - | { readonly ok: true; readonly value: typeof EMPTY } - | { readonly ok: false; readonly error: { readonly code: string; readonly message: string } } - -async function bench() { - const ctx = new Context() - onTestFinished(async () => { await ctx.fiber.dispose() }) - const retryClient = vi.fn(async () => {}) - ctx.provide('modules', { entries: { state: createSnapshotStore({ syncing: false, failures: [] }), retry: retryClient } } as unknown as ClientModuleLoader) - await ctx.plugin(SlotRegistry).await() - const locale = new LocaleRuntime(ctx) - ctx.provide('locale', locale) - class RemoteService extends Service { - constructor(serviceCtx: Context) { - super(serviceCtx, 'remote') - } - } - new RemoteService(ctx) - const list = vi.fn<() => Promise>() - .mockResolvedValue({ ok: true, value: EMPTY }) - ctx.provide('remote.pluginInventory', { list }) - return { ctx, retryClient, slots: ctx.get('slots') as SlotRegistry, locale, list } -} - -function declare(slots: SlotRegistry): () => void { - return slots.register({ - name: 'root', - children: { 'settings.plugins.tab': { kind: 'list', scope: 'root' } }, - } as never, () => null) -} - -describe('ui-settings-plugin-inventory browser plugin', () => { - it('keeps the host Loader entry inert', () => { - expect(hostApply).not.toThrow() - }) - - it('declares only the services used by the Settings Remote contribution', () => { - expect(inject).toEqual(['slots', 'locale', 'remote', 'remote.pluginInventory', 'modules']) - }) - - it('registers a localized tab without reading the Remote eagerly', async () => { - const b = await bench() - declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() - - const entry = b.slots.entries('settings.plugins.tab')[0]! - expect(entry.component).toBe(PluginInventorySettingsTab) - expect(entry.options).toMatchObject({ id: 'all', order: 10 }) - expect(entry.locale).toBe(NS) - expect(resolveSlotLabel(entry.options.label)).toBe('插件列表') - expect(b.list).not.toHaveBeenCalled() - - const injected = (entry.inject as unknown as () => PluginInventorySettingsTabInjected)() - const text = { en: 'Local tools', zh: '本地工具' } - expect(injected.resolveText(text)).toBe('本地工具') - b.locale.setLocale('en') - expect(injected.resolveText(text)).toBe('Local tools') - b.locale.setLocale('zh') - injected.retryClient() - const retryError = vi.spyOn(b.ctx.logger, 'error').mockImplementation(() => {}) - b.retryClient.mockRejectedValueOnce(new Error('retry unavailable')) - injected.retryClient() - await vi.waitFor(() => { expect(retryError).toHaveBeenCalled() }) - retryError.mockRestore() - await expect(injected.list()).resolves.toEqual(EMPTY) - expect(b.list).toHaveBeenCalledOnce() - b.list.mockResolvedValueOnce({ ok: false, error: { code: 'REMOTE_ERROR', message: 'unavailable' } }) - await expect(injected.list()).rejects.toThrow('pluginInventory.list failed: REMOTE_ERROR: unavailable') - - // Shipped preset names resolve over the agent-preset dictionaries the - // real plugin registers; user-authored metadata stays untranslated. - b.locale.register('settings.agentPreset', 'zh', { presetStandardName: '标准模式' } as never) - expect(injected.presetName({ id: 'standard', isDefault: true, rows: [] })).toBe('标准模式') - expect(injected.presetName({ id: 'mine', name: '我自己的', isDefault: false, rows: [] })).toBe('我自己的') - await b.ctx.fiber.dispose() - }) - - it('follows locale and recovers across late declaration and declarer reload', async () => { - const b = await bench() - const fiber = b.ctx.plugin({ inject: [...inject], apply }) - await fiber.await() - expect(b.slots.entries('settings.plugins.tab')).toHaveLength(0) - - const stop = declare(b.slots) - await vi.waitFor(() => { expect(b.slots.entries('settings.plugins.tab')).toHaveLength(1) }) - b.locale.setLocale('en') - expect(resolveSlotLabel(b.slots.entries('settings.plugins.tab')[0]!.options.label)).toBe('Plugin list') - - stop() - expect(b.slots.entries('settings.plugins.tab')).toHaveLength(0) - declare(b.slots) - await vi.waitFor(() => { - expect(b.slots.entries('settings.plugins.tab')[0]?.component).toBe(PluginInventorySettingsTab) - }) - - await fiber.dispose() - expect(b.slots.entries('settings.plugins.tab')).toHaveLength(0) - expect(() => b.locale.register(NS, 'zh', {})).not.toThrow() - await b.ctx.fiber.dispose() - }) -}) diff --git a/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx b/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx deleted file mode 100644 index cd4e5acd14..0000000000 --- a/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx +++ /dev/null @@ -1,663 +0,0 @@ -// @vitest-environment jsdom -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { ClientEntryState } from '@deepseek-ai/dsh-client-modules/client' -import type { PluginEntryId } from '@deepseek-ai/dsh-api-remotes/client' -import { Context } from '@deepseek-ai/cordis' -import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' -import { PluginInventorySettingsTab } from '../src/client/PluginInventorySettingsTab.tsx' -import type { - PluginInventorySettingsTabInjected, - PluginInventorySettingsTabProps, -} from '../src/client/PluginInventorySettingsTab.tsx' -import { en, zh, type PluginInventoryLocaleKey } from '../src/client/locales.ts' - -afterEach(cleanup) - -type Snapshot = Awaited> -const t = ((key: PluginInventoryLocaleKey, params?: Record): string => - Object.entries(params ?? {}).reduce( - (text, [name, value]) => text.replaceAll(`{${name}}`, value), - en[key], - )) as PluginInventorySettingsTabProps['t'] - -function props( - list: PluginInventorySettingsTabInjected['list'], - presetName: PluginInventorySettingsTabInjected['presetName'] = preset => preset.name ?? preset.id, - resolveText: PluginInventorySettingsTabInjected['resolveText'] = text => typeof text === 'string' ? text : text.en, -): PluginInventorySettingsTabProps { - return { - t, - list, - presetName, - resolveText, - useClientSync: bindSnapshotSelector(createSnapshotStore({ syncing: false, failures: [] })), - retryClient: vi.fn(), - } as PluginInventorySettingsTabProps -} - -function localizedProps(list: PluginInventorySettingsTabInjected['list']) { - const ctx = new Context() - onTestFinished(async () => { await ctx.fiber.dispose() }) - const locale = new LocaleRuntime(ctx) - ctx.effect(() => locale.register('settings.pluginInventory', 'en', en), 'test: English inventory dictionary') - ctx.effect(() => locale.register('settings.pluginInventory', 'zh', zh), 'test: Chinese inventory dictionary') - locale.setLocale('en') - const pageProps: PluginInventorySettingsTabProps = { - ...props(list, preset => preset.name ?? preset.id, text => locale.resolveText(text)), - t: locale.bind('settings.pluginInventory'), - } - return { locale, pageProps } -} - -/** A deployment with a roster: one failed global row, two preset-provided rows. */ -const SNAPSHOT = { - entries: [ - { entryId: 'telemetry', moduleName: '@fixture/telemetry', enabled: true, fiberPhase: 'failed' }, - { entryId: 'timer', moduleName: 'cordis:timer', enabled: true, fiberPhase: 'active' }, - { entryId: '8a1b2c3d', moduleName: '@deepseek-ai/cordis-plugin-hmr', enabled: true, fiberPhase: 'active' }, - { entryId: 'unobserved', moduleName: '@fixture/unobserved-name', enabled: true, fiberPhase: null }, - { entryId: 'bash-host', moduleName: '@deepseek-ai/dsh-tool-bash', enabled: false, fiberPhase: null }, - { entryId: 'fs-host', moduleName: '@deepseek-ai/dsh-tool-fs', enabled: false, fiberPhase: null }, - { entryId: 'dormant', moduleName: '@fixture/dormant', enabled: false, fiberPhase: null }, - ], - agentPresets: [ - { - id: 'standard', - name: '标准模式', - isDefault: true, - rows: [ - { entryId: 'bash', moduleName: '@deepseek-ai/dsh-tool-bash', enabled: true, fiberPhase: 'active' }, - { entryId: 'fs', moduleName: '@deepseek-ai/dsh-tool-fs', enabled: true, fiberPhase: null }, - { - entryId: 'pwsh', - moduleName: '@fixture/pwsh', - enabled: 'conditional', - condition: 'process.platform === \'win32\'', - fiberPhase: null, - }, - { entryId: 'codex', moduleName: '@fixture/codex', enabled: false, fiberPhase: null }, - { entryId: 'crashy', moduleName: '@fixture/crashy', enabled: true, fiberPhase: 'failed' }, - { entryId: null, moduleName: '@fixture/anonymous', enabled: true, fiberPhase: null }, - ], - }, - { - id: 'ptc', - isDefault: false, - rows: [ - { entryId: 'bash', moduleName: '@deepseek-ai/dsh-tool-bash', enabled: true, fiberPhase: null }, - { entryId: 'bash-fork', moduleName: '@deepseek-ai/dsh-tool-bash', enabled: true, fiberPhase: null }, - { entryId: 'fs', moduleName: '@deepseek-ai/dsh-tool-fs', enabled: 'conditional', fiberPhase: null }, - ], - }, - { id: 'shattered', name: '坏预设', isDefault: false, broken: 'the composition file is missing', rows: [] }, - ], -} as unknown as Snapshot - -async function renderReady(snapshot: Snapshot = SNAPSHOT): Promise> { - const view = render( snapshot)} />) - await screen.findByRole('searchbox', { name: en.search }) - return view -} - -const globalToggle = (): HTMLElement => - screen.getByRole('button', { name: (name: string) => name.startsWith(en.globalTitle) }) -const presetToggle = (): HTMLElement => screen.getByRole('button', { name: en.presetTitle }) - -describe('PluginInventorySettingsTab', () => { - it.each(['global', 'preset'])('shortens package and module name fallbacks in the %s inventory', async (scope) => { - const names = [ - ['@deepseek-ai/dsh-tool-subagent', 'tool-subagent'], - ['@deepseek-ai/dsh-host-web', 'web'], - ['@deepseek-ai/dsh-client-tabs', 'tabs'], - ['@deepseek-ai/cordis-plugin-hmr', 'hmr'], - ['cordis:timer', 'timer'], - ['@acme/dsh-sidebar/navigation', 'sidebar/navigation'], - ['plain-plugin', 'plain-plugin'], - ] as const - const rows = names.flatMap(([moduleName], index) => [false, true].map(fromManifest => ({ - entryId: `include:short-${String(index)}-${String(fromManifest)}` as PluginEntryId, - moduleName, - enabled: true, - fiberPhase: null, - ...fromManifest ? { meta: { title: moduleName, description: 'Package description.' } } : {}, - }))) - const snapshot: Snapshot = scope === 'global' - ? { entries: rows } - : { entries: [], agentPresets: [{ id: 'custom', isDefault: true, rows }] } - const view = await renderReady(snapshot) - if (scope === 'global') fireEvent.click(globalToggle()) - for (const [index, [moduleName, title]] of names.entries()) { - for (const fromManifest of [false, true]) { - const entryId = `include:short-${String(index)}-${String(fromManifest)}` - const card = screen.getByRole('button', { name: `${title}, ${entryId}, Enabled` }) - if (fromManifest) { - expect(document.getElementById(card.getAttribute('aria-describedby')!)?.textContent).toBe('Package description.') - } - fireEvent.click(card) - expect(screen.getByText(en.moduleLabel).nextElementSibling?.textContent).toBe(moduleName) - expect(view.container.querySelector('[data-loader-entry]')?.textContent).toBe(entryId) - fireEvent.click(card) - } - } - fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { - target: { value: '@deepseek-ai/dsh-tool-subagent' }, - }) - expect(screen.getAllByRole('listitem')).toHaveLength(2) - expect(screen.getAllByRole('button', { name: /^tool-subagent, include:short-0-/ })).toHaveLength(2) - }) - - it('keeps authored locale titles verbatim when they resemble module names', async () => { - const { locale, pageProps } = localizedProps(async () => ({ - entries: [{ - entryId: 'include:navigation' as PluginEntryId, moduleName: '@acme/dsh-navigation', enabled: true, fiberPhase: null, - meta: { title: { en: 'dsh-Navigation', zh: 'dsh-导航' } }, - }], - })) - const view = render() - await screen.findByRole('searchbox', { name: en.search }) - fireEvent.click(globalToggle()) - expect(screen.getByRole('button', { name: 'dsh-Navigation, include:navigation, Enabled' })).toBeTruthy() - locale.setLocale('zh') - view.rerender() - expect(screen.getByRole('button', { name: 'dsh-导航, include:navigation, 已启用' })).toBeTruthy() - }) - - it('localizes global and preset metadata at render time while preserving identities and query state', async () => { - const globalError = 'locale/zh.json: invalid title' - const presetError = 'locale/fr.json: invalid description' - const snapshot: Snapshot = { - entries: [{ - entryId: 'include:global-navigation' as PluginEntryId, moduleName: '@acme/navigation', enabled: true, fiberPhase: 'active', - meta: { - title: { en: 'Navigation', zh: '导航' }, - description: { en: 'Global navigation controls', zh: '全局导航控件' }, - error: globalError, - }, - }], - agentPresets: [{ - id: 'custom', name: 'My preset', isDefault: true, - rows: [{ - entryId: 'include:preset-runner', moduleName: '@acme/runner', enabled: true, fiberPhase: null, - meta: { - title: { en: 'Session runner', zh: '会话执行器' }, - description: { en: 'Run per session', zh: '运行会话命令' }, - error: presetError, - }, - }], - }], - } - const list = vi.fn(async () => snapshot) - const { locale, pageProps } = localizedProps(list) - const view = render() - await screen.findByRole('searchbox', { name: en.search }) - expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) - expect(screen.getByText(en.globalSubtitle).textContent).toBe(en.globalSubtitle) - fireEvent.click(globalToggle()) - const global = screen.getByRole('button', { name: 'Navigation, include:global-navigation, Enabled' }) - const preset = screen.getByRole('button', { name: 'Session runner, include:preset-runner, Enabled' }) - expect(document.getElementById(global.getAttribute('aria-describedby')!)?.textContent).toBe('Global navigation controls') - expect(document.getElementById(preset.getAttribute('aria-describedby')!)?.textContent).toBe('Run per session') - expect(screen.getByText(en.metadataError.replace('{error}', globalError))).toBeTruthy() - expect(screen.getByText(en.metadataError.replace('{error}', presetError))).toBeTruthy() - expect(global.closest('li')?.getAttribute('data-failed')).toBeNull() - fireEvent.click(global) - expect(screen.getByText(en.moduleLabel).nextElementSibling?.textContent).toBe('@acme/navigation') - fireEvent.click(preset) - expect(screen.getByText(en.moduleLabel).nextElementSibling?.textContent).toBe('@acme/runner') - expect(view.container.querySelector('[data-loader-entry]')?.textContent).toBe('include:preset-runner') - - locale.setLocale('zh') - view.rerender() - expect(screen.getByText(zh.presetSubtitle).textContent).toBe(zh.presetSubtitle) - expect(screen.getByText(zh.globalSubtitle).textContent).toBe(zh.globalSubtitle) - expect(screen.getByRole('button', { name: '导航, include:global-navigation, 已启用' })).toBeTruthy() - expect(screen.getByRole('button', { name: '会话执行器, include:preset-runner, 已启用' })).toBeTruthy() - expect(screen.getByText('全局导航控件')).toBeTruthy() - expect(screen.getByText('运行会话命令')).toBeTruthy() - expect(screen.getByText(zh.metadataError.replace('{error}', presetError))).toBeTruthy() - expect(view.container.querySelector('[data-loader-entry]')?.textContent).toBe('include:preset-runner') - const search = screen.getByRole('searchbox', { name: zh.search }) - for (const query of ['导航', '全局导航控件', '@acme/navigation', 'include:global-navigation']) { - fireEvent.change(search, { target: { value: query } }) - expect(screen.getAllByRole('listitem')).toHaveLength(1) - expect(screen.getByRole('button', { name: '导航, include:global-navigation, 已启用' })).toBeTruthy() - } - fireEvent.change(search, { target: { value: '运行会话命令' } }) - expect(screen.getAllByRole('listitem')).toHaveLength(1) - expect(screen.getByRole('button', { name: '会话执行器, include:preset-runner, 已启用' })).toBeTruthy() - fireEvent.change(search, { target: { value: 'Run per session' } }) - expect(screen.getByText(zh.emptySearch)).toBeTruthy() - locale.setLocale('en') - view.rerender() - expect(screen.getByRole('button', { name: 'Session runner, include:preset-runner, Enabled' })).toBeTruthy() - expect(screen.getByRole('searchbox', { name: en.search })).toHaveProperty('value', 'Run per session') - expect(list).toHaveBeenCalledOnce() - }) - - it.each(['global', 'preset'])('resolves each %s row field independently and hides empty English descriptions', async (scope) => { - const rows: Snapshot['entries'] = [ - { - entryId: 'include:navigation' as PluginEntryId, moduleName: '@acme/dsh-sidebar/navigation', enabled: true, fiberPhase: null, - meta: { description: { en: 'Navigation description.' } }, - }, - { - entryId: 'include:commands' as PluginEntryId, moduleName: '@acme/dsh-sidebar/commands', enabled: true, fiberPhase: null, - meta: { title: { en: 'English title' }, description: { en: 'Package description.', zh: '中文命令说明。' } }, - }, - { - entryId: 'include:theme' as PluginEntryId, moduleName: '@acme/dsh-theme/client', enabled: true, fiberPhase: null, - meta: { title: { en: '@acme/dsh-theme', zh: '主题插件' }, description: { en: '', zh: '中文主题说明。' } }, - }, - ] - const snapshot: Snapshot = scope === 'global' - ? { entries: rows } - : { entries: [], agentPresets: [{ id: 'custom', isDefault: true, rows }] } - const list = vi.fn(async () => snapshot) - const { locale, pageProps } = localizedProps(list) - const view = render() - await screen.findByRole('searchbox', { name: en.search }) - if (scope === 'global') fireEvent.click(globalToggle()) - expect(screen.getByRole('button', { name: 'sidebar/navigation, include:navigation, Enabled' })).toBeTruthy() - expect(screen.getByText('Navigation description.')).toBeTruthy() - expect(screen.getByRole('button', { name: 'English title, include:commands, Enabled' })).toBeTruthy() - expect(screen.getByText('Package description.')).toBeTruthy() - const theme = screen.getByRole('button', { name: '@acme/dsh-theme, include:theme, Enabled' }) - expect(theme.getAttribute('aria-describedby')).toBeNull() - expect(screen.queryByText('中文主题说明。')).toBeNull() - - locale.setLocale('zh') - view.rerender() - for (const [name, description] of [ - ['sidebar/navigation, include:navigation, 已启用', 'Navigation description.'], - ['English title, include:commands, 已启用', '中文命令说明。'], - ['主题插件, include:theme, 已启用', '中文主题说明。'], - ] as const) { - const card = screen.getByRole('button', { name }) - expect(screen.getByText(description)).toBeTruthy() - expect(document.getElementById(card.getAttribute('aria-describedby')!)?.textContent).toBe(description) - } - expect(screen.queryByText('Package description.')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: '主题插件, include:theme, 已启用' })) - expect(view.container.querySelector('[data-loader-entry]')?.textContent).toBe('include:theme') - expect(screen.getByText(zh.moduleLabel).nextElementSibling?.textContent).toBe('@acme/dsh-theme/client') - - fireEvent.change(screen.getByRole('searchbox', { name: zh.search }), { target: { value: '中文主题说明。' } }) - expect(screen.getAllByRole('listitem')).toHaveLength(1) - locale.setLocale('en') - view.rerender() - expect(screen.getByText(en.emptySearch)).toBeTruthy() - fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { target: { value: '@acme/dsh-theme/client' } }) - expect(screen.getAllByRole('listitem')).toHaveLength(1) - expect(screen.getByRole('button', { name: '@acme/dsh-theme, include:theme, Enabled' }).getAttribute('aria-describedby')).toBeNull() - expect(list).toHaveBeenCalledOnce() - }) - - it('keeps metadata-error-only rows inspectable by their full module specifier', async () => { - const error = 'locale/zh.json: invalid title' - await renderReady({ - entries: [{ - entryId: 'include:legacy' as PluginEntryId, moduleName: '@acme/dsh-legacy', enabled: false, fiberPhase: null, - meta: { error }, - }], - }) - fireEvent.click(globalToggle()) - expect(screen.getByText(en.metadataError.replace('{error}', error))).toBeTruthy() - const card = screen.getByRole('button', { name: 'legacy, Disabled' }) - expect(card).toHaveProperty('disabled', false) - expect(card.closest('li')?.getAttribute('data-failed')).toBeNull() - fireEvent.click(card) - expect(screen.getByText(en.moduleLabel).nextElementSibling?.textContent).toBe('@acme/dsh-legacy') - }) - - it('shows the default preset first with its group open and the global plane folded', async () => { - const view = await renderReady() - - const switcher = screen.getByRole('button', { name: en.switcherLabel }) - expect(switcher.textContent).toBe('标准模式 (default)') - fireEvent.click(switcher) - expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - '标准模式 (default)', - 'ptc', - '坏预设 (failed to load)', - ]) - fireEvent.keyDown(document, { key: 'Escape' }) - expect(screen.queryAllByRole('menuitem')).toHaveLength(0) - expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) - - // The preset group starts open with its rows while the larger global plane stays folded. - expect(presetToggle().getAttribute('aria-expanded')).toBe('true') - expect(screen.getAllByRole('listitem')).toHaveLength(6) - // Only the states that depart from plainly enabled carry a tag. - expect(screen.queryByText(en.enabledTag)).toBeNull() - expect(screen.getByText(en.conditionalTag)).toBeTruthy() - expect(screen.getByText(en.disabledTag)).toBeTruthy() - expect(screen.getByText(en.failedTag)).toBeTruthy() - // A settled row carries no phase dot: an active fiber and a row with no live - // fiber both render without one. - expect(screen.queryByRole('img', { name: en.active })).toBeNull() - expect(screen.queryByRole('img', { name: en.unobserved })).toBeNull() - - expect(globalToggle().getAttribute('aria-expanded')).toBe('false') - expect(screen.getByText(en.globalSubtitle).textContent).toBe(en.globalSubtitle) - - // A preset row expands into its source facts. - fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' })) - expect(screen.getByText(en.fromPreset)).toBeTruthy() - expect(screen.getByText('标准模式')).toBeTruthy() - expect(screen.getByText(en.condition)).toBeTruthy() - expect(screen.getByText('process.platform === \'win32\'')).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' })) - expect(screen.queryByText(en.condition)).toBeNull() - - // A failed preset row names its runtime state instead of a condition. - fireEvent.click(screen.getByRole('button', { name: 'crashy, Failed' })) - expect(screen.getByText(en.runtime)).toBeTruthy() - expect(screen.getByText('Failed to start')).toBeTruthy() - - // A row declaring no id has no Loader identity line, only its module. - fireEvent.click(screen.getByRole('button', { name: 'anonymous, Enabled' })) - expect(view.container.querySelector('[data-loader-entry]')).toBeNull() - expect(screen.getByText(en.moduleLabel).nextElementSibling?.textContent).toBe('@fixture/anonymous') - }) - - it('marks a live phase with a dot on an untagged enabled row', async () => { - await renderReady({ - entries: [ - { entryId: 'booting', moduleName: '@fixture/booting', enabled: true, fiberPhase: 'loading' }, - { entryId: 'waiting', moduleName: '@fixture/waiting', enabled: true, fiberPhase: 'pending' }, - { entryId: 'running', moduleName: '@fixture/running', enabled: true, fiberPhase: 'active' }, - { entryId: 'unobserved', moduleName: '@fixture/unobserved', enabled: true, fiberPhase: null }, - ], - agentPresets: [{ - id: 'standard', - isDefault: true, - rows: [ - { entryId: 'stopping', moduleName: '@fixture/stopping', enabled: true, fiberPhase: 'unloading' }, - { entryId: 'preset-running', moduleName: '@fixture/preset-running', enabled: true, fiberPhase: 'active' }, - ], - }], - } as unknown as Snapshot) - - fireEvent.click(globalToggle()) - expect(screen.getAllByRole('listitem')).toHaveLength(6) - expect(screen.queryByText(en.enabledTag)).toBeNull() - expect(screen.getByRole('img', { name: en.loadingPhase })).toBeTruthy() - expect(screen.getByRole('img', { name: en.pending })).toBeTruthy() - expect(screen.getByRole('img', { name: en.unloading })).toBeTruthy() - expect(screen.queryByRole('img', { name: en.active })).toBeNull() - expect(screen.queryByRole('img', { name: en.unobserved })).toBeNull() - }) - - it('distinguishes collapsed same-module rows by stable entry id', async () => { - const longId = 'include:agent-presets:tool-subagent-secondary-with-a-complete-stable-identity' - const subtitle = 'agent-presets:tool-subagent-secondary-with-a-complete-stable-identity' - await renderReady({ - entries: [], - agentPresets: [{ - id: 'same-module', - isDefault: true, - rows: [ - { entryId: 'tool-subagent-primary', moduleName: '@deepseek-ai/dsh-tool-subagent', enabled: true, fiberPhase: null }, - { entryId: longId, moduleName: '@deepseek-ai/dsh-tool-subagent', enabled: false, fiberPhase: null }, - ], - }], - }) - - expect(screen.getByRole('button', { name: 'tool-subagent, tool-subagent-primary, Enabled' }) - .getAttribute('aria-expanded')).toBe('false') - const secondary = screen.getByRole('button', { name: `tool-subagent, ${longId}, Disabled` }) - expect(secondary.getAttribute('aria-expanded')).toBe('false') - expect(secondary.children).toHaveLength(2) - expect(secondary.children[0]?.textContent).toContain('tool-subagent') - expect(secondary.children[0]?.textContent).toContain('Disabled') - expect(secondary.children[1]?.textContent).toBe(subtitle) - expect(screen.getByTitle(longId).textContent).toBe(subtitle) - - fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { target: { value: 'include:agent-presets:tool-subagent-secondary' } }) - expect(screen.queryByRole('button', { name: 'tool-subagent, tool-subagent-primary, Enabled' })).toBeNull() - const filteredSecondary = screen.getByRole('button', { name: `tool-subagent, ${longId}, Disabled` }) - fireEvent.click(filteredSecondary) - expect(filteredSecondary.getAttribute('aria-expanded')).toBe('true') - }) - - it('shows the entry id only where it adds to the title', async () => { - await renderReady({ - entries: [ - { entryId: 'timer' as PluginEntryId, moduleName: 'cordis:timer', enabled: true, fiberPhase: 'active' }, - { entryId: 'include:hmr' as PluginEntryId, moduleName: '@deepseek-ai/cordis-plugin-hmr', enabled: true, fiberPhase: 'active' }, - { entryId: 'typert' as PluginEntryId, moduleName: '@fixture/typert-registry', enabled: true, fiberPhase: null }, - ], - }) - fireEvent.click(globalToggle()) - - // An id equal to the title leaves both the card and its accessible name. - expect(screen.getByRole('button', { name: 'timer, Enabled' }).querySelector('code')).toBeNull() - // A composition id that matches the title once its include: marker drops is left out the same way. - expect(screen.getByRole('button', { name: 'hmr, Enabled' }).querySelector('code')).toBeNull() - const typert = screen.getByRole('button', { name: 'typert-registry, typert, Enabled' }).querySelector('code') - expect(typert?.textContent).toBe('typert') - expect(typert?.getAttribute('title')).toBe('typert') - }) - - it('expands the global plane with failures first and preset-provided rows inline', async () => { - const view = await renderReady() - - expect(screen.queryByText(en.presetEnabledTag)).toBeNull() - fireEvent.click(globalToggle()) - expect(globalToggle().getAttribute('aria-expanded')).toBe('true') - const failed = view.container.querySelector('[data-plugin-scope="global"] [data-failed="true"]') - expect(failed?.getAttribute('data-plugin-entry')).toBe('telemetry') - // Failures float above the Loader-ordered remainder. - expect(view.container.querySelector('[data-plugin-scope="global"] li')).toBe(failed) - - // Rows the presets took over sit inline, marked instead of plainly disabled. - expect(screen.getAllByText(en.presetEnabledTag)).toHaveLength(2) - - fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash-host, Via presets' })) - expect(screen.getByText(en.presetProvidedDetail)).toBeTruthy() - expect(screen.getByText(en.enabledIn)).toBeTruthy() - expect(screen.getByText('标准模式 · ptc')).toBeTruthy() - - // The failed global card reports its runtime state. - fireEvent.click(screen.getByRole('button', { name: 'telemetry, Failed' })) - expect(screen.getByText('Failed to start')).toBeTruthy() - - // An enabled entry with no live fiber says so in its details, dot-free. - fireEvent.click(screen.getByRole('button', { name: 'unobserved-name, unobserved, Enabled' })) - expect(screen.getByText('Not running')).toBeTruthy() - - // A disabled row outside every preset stays plainly disabled. - fireEvent.click(screen.getByRole('button', { name: 'dormant, Disabled' })) - expect(screen.queryByText(en.presetProvidedDetail)).toBeNull() - - fireEvent.click(globalToggle()) - expect(globalToggle().getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText(en.presetEnabledTag)).toBeNull() - }) - - it('switches the inspected preset in place, including broken ones', async () => { - const view = await renderReady() - const pickPreset = (label: string): void => { - fireEvent.click(screen.getByRole('button', { name: en.switcherLabel })) - fireEvent.click(screen.getByRole('menuitem', { name: label })) - } - - pickPreset('ptc') - expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(3) - fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash, Enabled' })) - // An unnamed preset labels its source by id. - expect(screen.getByText(en.fromPreset).nextElementSibling?.textContent).toBe('ptc') - - pickPreset('坏预设 (failed to load)') - expect(screen.getByRole('alert').textContent).toBe('the composition file is missing') - expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) - }) - - it('folds the preset group on demand and reopens it for a search', async () => { - const view = await renderReady() - const toggle = presetToggle() - - expect(toggle.getAttribute('aria-expanded')).toBe('true') - expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(6) - // The explanatory subtitle remains visible while the rows are folded away. - fireEvent.click(toggle) - expect(toggle.getAttribute('aria-expanded')).toBe('false') - expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) - expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) - - fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { target: { value: 'pwsh' } }) - expect(toggle.getAttribute('aria-expanded')).toBe('true') - expect(screen.getByText(en.conditionalTag)).toBeTruthy() - - fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { target: { value: '' } }) - expect(toggle.getAttribute('aria-expanded')).toBe('false') - fireEvent.click(toggle) - expect(toggle.getAttribute('aria-expanded')).toBe('true') - }) - - it('routes every preset name through the display resolver', async () => { - // The resolver stands in for presetDisplayText: shipped presets localize, - // user-authored ones keep their own metadata. - const localized: PluginInventorySettingsTabInjected['presetName'] = preset => - ['standard', 'ptc'].includes(preset.id) ? `Localized ${preset.id}` : preset.name ?? preset.id - render( SNAPSHOT, localized)} />) - await screen.findByRole('searchbox', { name: en.search }) - - const switcher = screen.getByRole('button', { name: en.switcherLabel }) - expect(switcher.textContent).toBe('Localized standard (default)') - fireEvent.click(switcher) - expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - 'Localized standard (default)', - 'Localized ptc', - '坏预设 (failed to load)', - ]) - fireEvent.keyDown(document, { key: 'Escape' }) - - fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' })) - expect(screen.getByText(en.fromPreset).nextElementSibling?.textContent).toBe('Localized standard') - - fireEvent.click(globalToggle()) - fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash-host, Via presets' })) - expect(screen.getByText('Localized standard · Localized ptc')).toBeTruthy() - }) - - it('searches across scopes and points at matches in other presets', async () => { - const view = await renderReady() - const search = screen.getByRole('searchbox', { name: en.search }) - - fireEvent.change(search, { target: { value: 'tool-bash' } }) - // Searching forces the collapsed global plane and drawer open. - expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(1) - expect(view.container.querySelectorAll('[data-plugin-scope="global"] li')).toHaveLength(1) - expect(screen.getByText(en.presetEnabledTag)).toBeTruthy() - const hint = screen.getByText((text: string) => text.startsWith('2 more matches')) - expect(hint).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: 'ptc' })) - expect(screen.getByRole('button', { name: en.switcherLabel }).textContent).toBe('ptc') - - // A match visible only in another preset keeps the pointer without rows. - fireEvent.change(search, { target: { value: 'crashy' } }) - expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) - expect(screen.getByText((text: string) => text.startsWith('1 more matches'))).toBeTruthy() - expect(screen.queryByText(en.emptySearch)).toBeNull() - - // A match on a Loader entry id only reaches the global plane. - fireEvent.change(search, { target: { value: '8a1b2c3d' } }) - expect(view.container.querySelectorAll('[data-plugin-scope="global"] li')).toHaveLength(1) - expect(screen.queryByText((text: string) => text.includes('more matches'))).toBeNull() - - fireEvent.change(search, { target: { value: 'not-a-plugin' } }) - expect(screen.getByText(en.emptySearch)).toBeTruthy() - expect(screen.queryAllByRole('listitem')).toHaveLength(0) - }) - - it('renders a rosterless deployment as one global list, folded until opened', async () => { - const view = await renderReady({ - entries: [ - { entryId: 'hmr', moduleName: '@deepseek-ai/cordis-plugin-hmr', enabled: true, fiberPhase: 'active' }, - { entryId: 'off', moduleName: '@fixture/off', enabled: false, fiberPhase: null }, - ], - } as unknown as Snapshot) - - expect(screen.queryByRole('button', { name: en.switcherLabel })).toBeNull() - expect(globalToggle().getAttribute('aria-expanded')).toBe('false') - expect(screen.queryAllByRole('listitem')).toHaveLength(0) - fireEvent.click(globalToggle()) - expect(globalToggle().getAttribute('aria-expanded')).toBe('true') - expect(screen.getAllByRole('listitem')).toHaveLength(2) - - fireEvent.click(screen.getByRole('button', { name: 'hmr, Enabled' })) - expect(screen.getByText(en.runtime)).toBeTruthy() - expect(view.container.querySelector('[data-loader-entry]')?.textContent).toBe('hmr') - fireEvent.click(screen.getByRole('button', { name: 'off, Disabled' })) - expect(screen.getAllByText(en.moduleLabel).length).toBeGreaterThan(0) - expect(screen.queryByText(en.runtime)).toBeNull() - }) - - it('renders a preset-only snapshot without the global section', async () => { - await renderReady({ - entries: [], - agentPresets: [{ - id: 'solo', - isDefault: false, - rows: [{ entryId: 'one', moduleName: '@fixture/one', enabled: true, fiberPhase: null }], - }], - }) - - expect(screen.queryByRole('button', { name: (name: string) => name.startsWith(en.globalTitle) })).toBeNull() - expect(screen.queryByText(en.empty)).toBeNull() - expect(screen.getAllByRole('listitem')).toHaveLength(1) - }) - - it('shows a generic failure and retries into the empty state', async () => { - const list = vi.fn() - .mockRejectedValueOnce(new Error('private transport detail')) - .mockResolvedValueOnce({ entries: [] }) - render() - - expect((await screen.findByRole('alert')).querySelector('[data-state="error"]')).not.toBeNull() - expect(screen.queryByText('private transport detail')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: en.retry })) - await waitFor(() => { expect(list).toHaveBeenCalledTimes(2) }) - expect(await screen.findByText(en.empty)).toBeTruthy() - }) - - it('contains a synchronous Remote failure and ignores a result after unmount', async () => { - const syncFailure = vi.fn(() => { throw new Error('namespace unavailable') }) as PluginInventorySettingsTabInjected['list'] - const failed = render() - expect((await screen.findByRole('alert')).textContent).toBe(en.error) - failed.unmount() - - const deferred = Promise.withResolvers() - const pending = render( deferred.promise)} />) - // Loading shows skeleton cards; the status region announces the label as visually hidden text. - expect(screen.getByRole('status').textContent).toBe(en.loading) - pending.unmount() - await act(async () => { deferred.resolve(SNAPSHOT) }) - - const deferredFailure = Promise.withResolvers() - const pendingFailure = render( deferredFailure.promise)} />) - pendingFailure.unmount() - await act(async () => { deferredFailure.reject(new Error('late failure')) }) - }) -}) - -it('shows current-page sync errors and retries without re-reading Host inventory', async () => { - const list = vi.fn(async () => ({ entries: [] })) - const sync = createSnapshotStore({ syncing: true, failures: [] }) - const retryClient = vi.fn() - render() - expect(screen.getByText(en.clientSyncing).closest('[role="status"]')?.querySelector('[data-state="ongoing"]')).not.toBeNull() - await waitFor(() => { expect(list).toHaveBeenCalledOnce() }) - act(() => { sync.set({ syncing: false, failures: [{ id: 'client-addon', message: 'download failed' }] }) }) - expect(screen.getByRole('alert').querySelector('[data-state="error"]')).not.toBeNull() - expect(screen.getByText('client-addon: download failed')).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: 'Retry this page' })) - expect(retryClient).toHaveBeenCalledOnce() - expect(list).toHaveBeenCalledOnce() - act(() => { sync.set({ syncing: false, failures: [] }) }) - expect(screen.queryByRole('alert')).toBeNull() -}) diff --git a/packages/client/ui-settings-plugin-inventory/tests/touch-styles.client.spec.ts b/packages/client/ui-settings-plugin-inventory/tests/touch-styles.client.spec.ts deleted file mode 100644 index 579edfcdca..0000000000 --- a/packages/client/ui-settings-plugin-inventory/tests/touch-styles.client.spec.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Built-in plugin inventory touch rules, asserted against the CSS text on disk. - * - * jsdom resolves neither `pointer` nor `hover` media features, so these gates read - * the sheet instead: a `:hover` rule outside `@media (hover: hover)` latches onto a - * tap and strands the card in its pointer-only state, and the 13px search field - * makes iOS Safari zoom the visual viewport when it takes focus. - */ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' - -const css = readFileSync(fileURLToPath(new URL('../src/client/PluginInventorySettingsTab.module.css', import.meta.url)), 'utf8') -/** Comment bodies blanked, so prose about `:hover` is not read as a rule. */ -const rules = css.replace(/\/\*[\s\S]*?\*\//g, text => ' '.repeat(text.length)) - -/** Every `:hover` selector sitting in the media query that encloses it. */ -function hovers(source: string): { line: string; hoverMedia: boolean }[] { - const stack: (string | null)[] = [] - const found: { line: string; hoverMedia: boolean }[] = [] - for (const token of source.matchAll(/@media[^{]*\{|@container[^{]*\{|:hover|\{|\}/g)) { - const text = token[0] - if (text === '}') { - stack.pop() - continue - } - if (text === '{') { - stack.push(null) - continue - } - if (text.startsWith('@')) { - // The matched text includes the block's opening brace, which the frame stands for. - stack.push(text.slice(0, -1)) - continue - } - const start = source.lastIndexOf('\n', token.index ?? 0) + 1 - const end = source.indexOf('\n', token.index ?? 0) - found.push({ - line: source.slice(start, end === -1 ? undefined : end).trim(), - hoverMedia: stack.some(frame => frame !== null && /hover:\s*hover/.test(frame)), - }) - } - return found -} - -/** The declarations inside every `@media (hover: hover)` block, joined. */ -function hoverBlock(): string { - return [...rules.matchAll(/@media \(hover: hover\) \{([\s\S]*?)\n\}/g)].map(match => match[1] ?? '').join('\n') -} - -/** The declarations of one rule, by its literal selector. */ -function ruleBody(selector: string): string { - const start = rules.indexOf(`${selector} {`) - if (start === -1) throw new Error(`PluginInventorySettingsTab.module.css has no \`${selector}\` rule`) - const open = rules.indexOf('{', start) - return rules.slice(open + 1, rules.indexOf('}', open)) -} - -describe('built-in plugin inventory touch rules', () => { - it('fences every hover affordance behind a hover-capable pointer', () => { - // The card background and the preset switcher are the tab's only hover states; - // unguarded, a single tap leaves the card painted as hovered. - const unguarded = hovers(rules).filter(state => !state.hoverMedia) - expect(unguarded.map(state => state.line)).toEqual([]) - expect(rules).toContain('.cardContent:hover') - expect(rules).toContain('.switcher:hover') - }) - - it('keeps the open card painted without a pointer', () => { - // An expanded card shows the same surface as a hovered one, and it must hold on - // a touch client: it belongs outside the hover fence, not inside it. - expect(ruleBody(".card[data-open='true'] > .cardContent")) - .toContain('background: var(--dsw-alias-interactive-bg-hover)') - expect(hoverBlock()).not.toContain('data-open') - }) - - it('gives touch clients a press state where the hover state is fenced off', () => { - expect(ruleBody('.cardContent:active')).toContain('background: var(--dsw-alias-interactive-bg-active)') - expect(ruleBody('.switcher:active')).toContain('background: var(--dsw-alias-interactive-bg-active)') - }) - - it('keeps the focused search field at 16px under a coarse pointer', () => { - const coarse = /@media \(pointer: coarse\) \{([\s\S]*?)\n\}/.exec(rules)?.[1] ?? '' - expect(coarse).toMatch(/\.search input \{[^}]*font-size: 16px/) - }) -}) diff --git a/packages/client/ui-settings-plugins/README.i18n.yaml b/packages/client/ui-settings-plugins/README.i18n.yaml deleted file mode 100644 index a783ce1ee9..0000000000 --- a/packages/client/ui-settings-plugins/README.i18n.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# 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-settings-plugins/README.md -/: - en: 06bd505cb0147b05 - zh: 8d7646e22faac71b -/deepseek-ai-dsh-client-ui-settings-plugins: - en: 3ceabe2cdb5492f6 - zh: 6ea0cb3f93e5bdf5 -/deepseek-ai-dsh-client-ui-settings-plugins/summary: - en: d9b27f1dd9713b4f - zh: 3ec674429179ae7d -/deepseek-ai-dsh-client-ui-settings-plugins/table-of-contents: - en: d152484eb41ac6b4 - zh: 09388d293f9be9cb -/deepseek-ai-dsh-client-ui-settings-plugins/use-this-package: - en: b4deec821244f970 - zh: 49b3afedc992b7fe -/deepseek-ai-dsh-client-ui-settings-plugins/understand-the-implementation: - en: c5cfef002b32c7c1 - zh: 0249b45a28c16b61 -/deepseek-ai-dsh-client-ui-settings-plugins/further-exploration: - en: 54ba782a2b26f615 - zh: fee9148d9658d83f -/deepseek-ai-dsh-client-ui-settings-plugins/model-experience: - en: 6b7c6f82ab6c8435 - zh: 4517689c899abcbe -/deepseek-ai-dsh-client-ui-settings-plugins/model-experience/kv-cache-effect: - en: ca75c51c89c2c9b0 - zh: 6e1c9a8fdde89577 -/deepseek-ai-dsh-client-ui-settings-plugins/known-limitations-and-deferred-work: - en: 4950e959be39bc0c - zh: 8f0703f3304d9336 -/deepseek-ai-dsh-client-ui-settings-plugins/known-limitations-and-deferred-work/dev-note: - en: e67f633dc6fe7773 - zh: e88aeb617ffb74ea diff --git a/packages/client/ui-settings-plugins/README.md b/packages/client/ui-settings-plugins/README.md deleted file mode 100644 index ac0d69210f..0000000000 --- a/packages/client/ui-settings-plugins/README.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -description: "Built-in plugins settings section for the dsh web client: the Settings navigation entry and the tab chrome that feature-owned tabs register into." -kind: "package-reference" ---- - -# @deepseek-ai/dsh-client-ui-settings-plugins - -English | [中文](README.zh.md) - -## Summary - -Use the **Built-in plugins** settings section to inspect the plugins this deployment ships. The section is a shell: it owns the navigation entry and the tab row, and every tab in it is registered by another plugin — the read-only inventory ships one. Configuring a built-in plugin happens on the sidebar's Plugins page, where each official plugin's own companion package registers its page. - -## 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 - -Open **Built-in plugins** in Settings. [ui-settings-plugin-inventory](../ui-settings-plugin-inventory/README.md) contributes the inventory as the section's one tab, shown as the page itself; a second registered tab turns the row into tabs. A deployment whose composition contributes no tab shows the section's empty line. - -To contribute a tab, register into `settings.plugins.tab` with an `id`, an `order`, and a localized `label`; the section renders the entries in order and mounts a tab on its first selection. Feature copy stays in the registering plugin's dictionary. - ------ - - -## Understand the implementation - -
      -Implementation internals — click to expand - -The section declares `settings.plugins.tab`, a root list slot whose labels become ordered tabs; a lone contribution renders as the page itself, and a tab stays mounted after its first selection so search and the inventory snapshot survive switching. The section's `inject` projects the slot's ledger into ordered rows whose labels follow the active locale, cached until the ledger version or the locale revision moves. The Host half is an empty `apply`, present only so the package holds a Loader row the client module system serves the browser half for. - -
      - ------ - - -## Further Exploration - -- [ui-settings-plugin-inventory](../ui-settings-plugin-inventory/README.md) — the read-only inventory tab. -- [ui-settings](../ui-settings/README.md) — the domain base declaring `settings.section`. -- [ui-plugin-manager](../ui-plugin-manager/README.md) — the Plugins page where official plugins are configured. -- [ui-settings-shell](../ui-settings-shell/README.md), [ui-settings-agent-loop](../ui-settings-agent-loop/README.md), [ui-settings-subagent](../ui-settings-subagent/README.md), [ui-settings-web-search](../ui-settings-web-search/README.md) — the official configuration pages, one companion package each. - ------ - - -## Model Experience - -None, as the package is a browser-side settings surface that registers no model surface. - -#### KV Cache effect - -None; this package neither assembles nor sends a provider request. - -## Known Limitations and Deferred Work - - - -- **The section has no tab of its own** — it renders its empty line until a feature plugin registers one; the shell cannot fill the section alone. - - -### Dev Note - -
      -Working context for maintainers — click to expand - -None. - -
      diff --git a/packages/client/ui-settings-plugins/README.zh.md b/packages/client/ui-settings-plugins/README.zh.md deleted file mode 100644 index 44a16ec015..0000000000 --- a/packages/client/ui-settings-plugins/README.zh.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -description: "dsh Web 客户端的「内置插件」设置分区:设置导航项与供功能插件注册标签页的标签行。" -kind: "package-reference" ---- - -# @deepseek-ai/dsh-client-ui-settings-plugins - -[English](README.md) | 中文 - -## 概述 - -使用**内置插件**设置分区查看本部署随附的插件。该分区只是一个壳:它拥有导航项和标签行,里面的每个标签页都由其他插件注册——只读清单注册了一个。配置内置插件在侧栏的插件页上进行,每个官方插件自己的伴生包把页面注册到那里。 - -## 目录 - -- [使用本包](#use-this-package) -- [理解实现](#understand-the-implementation) -- [进一步探索](#further-exploration) -- [模型体验](#model-experience) -- [已知限制与延期工作](#known-limitations-and-deferred-work) -- [开发备注](#dev-note) - ------ - - -## 使用本包 - -在设置里打开**内置插件**。[ui-settings-plugin-inventory](../ui-settings-plugin-inventory/README.zh.md) 把清单作为分区唯一的标签页贡献进来,直接显示为页面本身;注册第二个标签页后这一行就变成标签行。组合里没有任何标签页贡献的部署会显示分区的空提示。 - -要贡献一个标签页,带 `id`、`order` 和本地化的 `label` 注册进 `settings.plugins.tab`;分区按序渲染条目,标签页在首次被选中时挂载。功能文案留在注册方自己的字典里。 - ------ - - -## 理解实现 - -
      -实现细节——点击展开 - -分区声明 `settings.plugins.tab`,一个根级 list slot,其标签成为有序的标签页;只有一个贡献时直接渲染为页面本身,标签页在首次被选中后保持挂载,搜索词和清单快照因此在切换间不丢失。分区的 `inject` 把 slot 账本投影成按序排列、标签随当前语言的行,在账本版本或语言修订变化前保持缓存。宿主半侧是一个空的 `apply`,只为让本包占一条 Loader 行,客户端模块系统据此送出浏览器半侧。 - -
      - ------ - - -## 进一步探索 - -- [ui-settings-plugin-inventory](../ui-settings-plugin-inventory/README.zh.md)——只读清单标签页。 -- [ui-settings](../ui-settings/README.zh.md)——声明 `settings.section` 的领域基座。 -- [ui-plugin-manager](../ui-plugin-manager/README.zh.md)——配置官方插件的插件页。 -- [ui-settings-shell](../ui-settings-shell/README.zh.md)、[ui-settings-agent-loop](../ui-settings-agent-loop/README.zh.md)、[ui-settings-subagent](../ui-settings-subagent/README.zh.md)、[ui-settings-web-search](../ui-settings-web-search/README.zh.md)——官方配置页,每个一个伴生包。 - ------ - - -## 模型体验 - -无,本包是浏览器侧的设置界面,不注册任何模型面。 - -#### KV 缓存影响 - -无;本包既不组装也不发送提供方请求。 - -## 已知限制与延期工作 - - - -- **分区没有自己的标签页**——在功能插件注册标签页之前它只显示空提示;壳自己填不满分区。 - - -### 开发备注 - -
      -维护者工作上下文——点击展开 - -无。 - -
      diff --git a/packages/client/ui-settings-plugins/locale/de.json b/packages/client/ui-settings-plugins/locale/de.json deleted file mode 100644 index 9b3e3dbeb2..0000000000 --- a/packages/client/ui-settings-plugins/locale/de.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Integrierter Plug-in-Einstellungseingang", - "description": "Bietet den integrierten Plug-in-Eingang und seine Funktionsregisterkarte in den Einstellungen." - } -} diff --git a/packages/client/ui-settings-plugins/locale/en.json b/packages/client/ui-settings-plugins/locale/en.json deleted file mode 100644 index bbe7eea9a3..0000000000 --- a/packages/client/ui-settings-plugins/locale/en.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "meta": { - "title": "ui-settings-plugins" - } -} diff --git a/packages/client/ui-settings-plugins/locale/es.json b/packages/client/ui-settings-plugins/locale/es.json deleted file mode 100644 index f06cce9794..0000000000 --- a/packages/client/ui-settings-plugins/locale/es.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Entrada de configuración de complementos incorporados", - "description": "Proporciona la entrada del complemento integrado y su pestaña de función en la configuración." - } -} diff --git a/packages/client/ui-settings-plugins/locale/fr.json b/packages/client/ui-settings-plugins/locale/fr.json deleted file mode 100644 index 762ba220ef..0000000000 --- a/packages/client/ui-settings-plugins/locale/fr.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Entrée des paramètres du plug-in intégré", - "description": "Fournit l'entrée du plug-in intégré et sa page à onglet de fonction dans les paramètres." - } -} diff --git a/packages/client/ui-settings-plugins/locale/ja.json b/packages/client/ui-settings-plugins/locale/ja.json deleted file mode 100644 index e25c087ef7..0000000000 --- a/packages/client/ui-settings-plugins/locale/ja.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "組み込みプラグイン設定", - "description": "設定内の組み込みプラグイン項目と機能タブを提供します。" - } -} diff --git a/packages/client/ui-settings-plugins/locale/pt.json b/packages/client/ui-settings-plugins/locale/pt.json deleted file mode 100644 index 4af280898e..0000000000 --- a/packages/client/ui-settings-plugins/locale/pt.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Entrada de configurações de plug-in integradas", - "description": "Fornece a entrada do plug-in integrada e sua guia de função nas configurações." - } -} diff --git a/packages/client/ui-settings-plugins/locale/ru.json b/packages/client/ui-settings-plugins/locale/ru.json deleted file mode 100644 index 4fdd139aa0..0000000000 --- a/packages/client/ui-settings-plugins/locale/ru.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Вход в настройки встроенного плагина", - "description": "Обеспечивает вход встроенного плагина и вкладку его функций в настройках." - } -} diff --git a/packages/client/ui-settings-plugins/locale/zh.json b/packages/client/ui-settings-plugins/locale/zh.json deleted file mode 100644 index 71ab797452..0000000000 --- a/packages/client/ui-settings-plugins/locale/zh.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "内置插件设置入口", - "description": "提供设置中的内置插件入口及其功能标签页。" - } -} diff --git a/packages/client/ui-settings-plugins/src/client/PluginsSettingsSection.module.css b/packages/client/ui-settings-plugins/src/client/PluginsSettingsSection.module.css deleted file mode 100644 index 5a524b709b..0000000000 --- a/packages/client/ui-settings-plugins/src/client/PluginsSettingsSection.module.css +++ /dev/null @@ -1,113 +0,0 @@ -/* Plugins section: compact tabs plus the configurable plugin card list. */ - -.section { - display: flex; - flex-direction: column; - gap: 12px; - max-width: 760px; - color: var(--dsw-alias-label-primary); -} - -.heading { - margin: 0; - font-size: 18px; - font-weight: 600; -} - -.intro { - margin: 0; - font-size: 13px; - color: var(--dsw-alias-label-tertiary); -} - -.tabs { - display: flex; - align-items: flex-end; - gap: 22px; - border-bottom: 0.5px solid var(--dsw-alias-border-l2); - margin-top: 2px; -} - -.tab { - position: relative; - border: 0; - padding: 7px 1px 9px; - background: transparent; - color: var(--dsw-alias-label-tertiary); - font: inherit; - font-size: 13px; - line-height: 20px; - cursor: pointer; -} - -.tab[data-active='true'] { - color: var(--dsw-alias-label-primary); -} - -@media (hover: hover) { - .tab:hover { - color: var(--dsw-alias-label-primary); - } -} - -.tab[data-active='true']::after, -.tab:focus-visible::after { - position: absolute; - right: 0; - bottom: -1px; - left: 0; - height: 2px; - border-radius: 2px 2px 0 0; - background: var(--dsw-alias-label-primary); - content: ''; -} - -.tab:focus-visible { - outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - outline-offset: 2px; - border-radius: 2px; - color: var(--dsw-alias-label-primary); -} - -.panel { - min-width: 0; - padding-top: 2px; -} - -.cards { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; - gap: 10px; -} - -.empty { - margin: 0; - font-size: 13px; - color: var(--dsw-alias-label-tertiary); -} - -/* Configurable tab: the card list. */ - -.configurable { - display: flex; - flex-direction: column; - gap: 10px; -} - -/* Preset detail page: the settings section over the same cards. */ - -.presetSettings { - display: flex; - flex-direction: column; - gap: 8px; -} - -.presetSettingsTitle { - margin: 0; - font-size: 15px; - line-height: 22px; - font-weight: 600; -} diff --git a/packages/client/ui-settings-plugins/src/client/PluginsSettingsSection.tsx b/packages/client/ui-settings-plugins/src/client/PluginsSettingsSection.tsx deleted file mode 100644 index 1c8148c654..0000000000 --- a/packages/client/ui-settings-plugins/src/client/PluginsSettingsSection.tsx +++ /dev/null @@ -1,126 +0,0 @@ -/** Plugins settings section: localized tabs around feature-owned pages. */ - -import { useEffect, useId, useRef, useState } from 'react' -import type { - HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, -} from '@deepseek-ai/dsh-client-ui-slots' -import type { PluginsSettingsLocaleKey } from './locales.ts' -import css from './PluginsSettingsSection.module.css' - -/** One tab projected from a `settings.plugins.tab` contribution. */ -export interface PluginsSettingsTabEntry { - id: string - order: number - label: string -} - -/** Registration-side business face for the section. */ -export interface PluginsSettingsSectionInjected { - hooks: { - /** Ordered, locale-aware projection of the Plugins tab ledger. */ - tabs: HostObservable - } -} - -/** Props the renderer binds for the section. */ -export type PluginsSettingsSectionProps = - PropsRuntime<'settings.section'> - & PropsLocale<'settings.plugins'> - & PropsRenderSlots<'settings.plugins.tab'> - & InjectFace - -/** Render one Plugins page whose contents arrive from feature-owned tabs; one contribution shows as the page itself. */ -export function PluginsSettingsSection({ t, renderSlot, useTabs }: PluginsSettingsSectionProps) { - const tabsId = useId() - const tabRefs = useRef>([]) - const rows = useTabs(value => value) - const [activeId, setActiveId] = useState() - const [visitedIds, setVisitedIds] = useState>(() => new Set()) - const active = rows.find(row => row.id === activeId)?.id ?? rows[0]?.id - const single = rows.length === 1 ? rows[0] : undefined - - // A tab mounts only when first selected, then stays mounted while hidden so - // local drafts, disclosure state, search, and the inventory snapshot survive - // switching between the two views. - useEffect(() => { - if (active === undefined) return - setVisitedIds((previous) => { - if (previous.has(active)) return previous - return new Set([...previous, active]) - }) - }, [active]) - - return ( -
      -

      {t('title')}

      -

      {t('intro')}

      - {rows.length === 0 ?

      {t('empty')}

      : single !== undefined ? ( -
      {renderSlot('settings.plugins.tab', {}, { only: single.id })}
      - ) : ( - <> -
      - {rows.map((row, index) => { - const selected = row.id === active - return ( - - ) - })} -
      - {rows - .filter(row => row.id === active || visitedIds.has(row.id)) - .map((row) => { - const selected = row.id === active - return ( - - ) - })} - - )} -
      - ) -} - -declare module '@deepseek-ai/dsh-client-ui-slots' { - interface LocaleNamespaceMap { - /** Built-in plugins section and plugin configuration page copy. */ - 'settings.plugins': PluginsSettingsLocaleKey - } -} diff --git a/packages/client/ui-settings-plugins/src/client/index.ts b/packages/client/ui-settings-plugins/src/client/index.ts deleted file mode 100644 index b9db73a850..0000000000 --- a/packages/client/ui-settings-plugins/src/client/index.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Built-in plugins settings section, browser half: the shell around the - * feature-owned tabs registered into `settings.plugins.tab` (the read-only - * inventory ships one). The configuration pages of the host-plane plugins - * live in their own companion packages, which register into the Plugins - * page; this section owns the Settings navigation entry and the tab chrome - * only. - */ - -// Type-only: pulls the locale plugin's Context merge (ctx.locale). -import type {} from '@deepseek-ai/dsh-client-locale/client' -// Type-only: the settings shell's SlotMap merge (the 'settings.section' -// entry). Cross-plugin collaboration goes through slots, never a value import -// (client bundle purity gate). -import type {} from '@deepseek-ai/dsh-client-ui-settings/client' -import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { Context as ClientContext } from '@deepseek-ai/cordis' -import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' -import { PluginsSettingsSection } from './PluginsSettingsSection.tsx' -import type { PluginsSettingsSectionInjected, PluginsSettingsTabEntry } from './PluginsSettingsSection.tsx' -import { en, ja, es, fr, de, ru, pt, zh } from './locales.ts' - -export type { PluginsSettingsSectionInjected, PluginsSettingsSectionProps } from './PluginsSettingsSection.tsx' - -/** Dictionary namespace owned by this plugin. */ -const NS = 'settings.plugins' - -/** Required services (cordis fiber inject). */ -export const inject = ['slots', 'locale'] - -/** - * Mount the built-in plugins section. - * @param ctx - the browser plugin context. - */ -export function apply(ctx: ClientContext): void { - const t = ctx.locale.bind(NS) - ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-settings-plugins: section dictionaries') - - let tabsVersion = -1 - let tabsRevision = -1 - let tabs: readonly PluginsSettingsTabEntry[] = [] - const sectionInjected = (): PluginsSettingsSectionInjected => ({ - hooks: { - tabs: { - getSnapshot: () => { - const version = ctx.slots.getVersion('settings.plugins.tab') - const revision = ctx.locale.getSnapshot().revision - if (version !== tabsVersion || revision !== tabsRevision) { - tabsVersion = version - tabsRevision = revision - tabs = ctx.slots.entries('settings.plugins.tab') - .map(entry => ({ - /* v8 ignore next -- list-slot registration requires id */ - id: entry.options.id ?? '', - order: entry.options.order ?? 0, - label: resolveSlotLabel(entry.options.label) ?? '', - })) - .sort((a, b) => a.order - b.order) - } - return tabs - }, - subscribe: (listener) => { - const offLedger = ctx.slots.subscribe('settings.plugins.tab', listener) - const offLocale = ctx.locale.subscribe(listener) - return () => { - offLedger() - offLocale() - } - }, - }, - }, - }) - - // This package owns the one Built-in plugins navigation entry and the tab - // chrome; feature plugins contribute pages without competing for Settings nav rows. - ctx.slots.inject('settings.section', () => ctx.slots.register({ - name: 'settings.section', - id: 'plugins', - order: 15, - label: () => t('nav'), - locale: NS, - inject: sectionInjected, - children: { 'settings.plugins.tab': { kind: 'list', scope: 'root' } }, - }, PluginsSettingsSection)) -} diff --git a/packages/client/ui-settings-plugins/src/client/locales.ts b/packages/client/ui-settings-plugins/src/client/locales.ts deleted file mode 100644 index 723b596309..0000000000 --- a/packages/client/ui-settings-plugins/src/client/locales.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** Locale bundles for the built-in plugins settings section. */ - -/** Locale keys the section renders. */ -export type PluginsSettingsLocaleKey = 'nav' | 'title' | 'intro' | 'tabs' | 'empty' - -/** English copy. */ -export const en: Record = { - nav: 'Built-in plugins', - title: 'Built-in plugins', - intro: 'Inspect the plugins this deployment ships.', - tabs: 'Plugin views', - empty: 'This deployment exposes no plugin views.', -} - -/** Simplified Chinese copy. */ -export const zh: Record = { - nav: '内置插件', - title: '内置插件', - intro: '查看内置部署的插件列表', - tabs: '插件视图', - empty: '本部署没有开放任何插件视图。', -} - -/** Japanese copy, checked against the English keys. */ -export const ja = { - 'nav': '組み込みプラグイン', - 'title': '組み込みプラグイン', - 'intro': 'このデプロイメントに含まれるプラグインを確認します。', - 'tabs': 'プラグインビュー', - 'empty': 'このデプロイメントにはプラグインビューがありません。', -} satisfies Record - -/** Spanish dictionary, checked against the English keys. */ -export const es = { - nav: 'Complementos integrados', - title: 'Complementos integrados', - intro: 'Inspeccione los complementos que incluye esta implementación.', - tabs: 'Vistas de complementos', - empty: 'Esta implementación no expone vistas de complementos.', -} satisfies Record - -/** French dictionary, checked against the English keys. */ -export const fr = { - nav: 'Plugins intégrés', - title: 'Plugins intégrés', - intro: 'Inspectez les plugins fournis par ce déploiement.', - tabs: 'Vues des plugins', - empty: "Ce déploiement n'expose aucune vue de plugin.", -} satisfies Record - -/** German dictionary, checked against the English keys. */ -export const de = { - nav: 'Integrierte Plugins', - title: 'Integrierte Plugins', - intro: 'Überprüfen Sie die Plugins, die mit dieser Bereitstellung geliefert werden.', - tabs: 'Plugin-Ansichten', - empty: 'Diese Bereitstellung stellt keine Plugin-Ansichten bereit.', -} satisfies Record - -/** Russian dictionary, checked against the English keys. */ -export const ru = { - nav: 'Встроенные плагины', - title: 'Встроенные плагины', - intro: 'Проверьте плагины, поставляемые в этом развертывании.', - tabs: 'Просмотры плагинов', - empty: 'Это развертывание не предоставляет никаких представлений плагинов.', -} satisfies Record - -/** Portuguese dictionary, checked against the English keys. */ -export const pt = { - nav: 'Plug-ins integrados', - title: 'Plug-ins integrados', - intro: 'Inspecione os plug-ins fornecidos por esta implantação.', - tabs: 'Visualizações de plug-in', - empty: 'Esta implantação não expõe visualizações de plug-ins.', -} satisfies Record diff --git a/packages/client/ui-settings-plugins/src/index.ts b/packages/client/ui-settings-plugins/src/index.ts deleted file mode 100644 index ce0f6e034d..0000000000 --- a/packages/client/ui-settings-plugins/src/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Plugins settings surface, node half. The empty apply exists so the plugin - * appears in the host cordis.yml / Loader; the browser half owns the section - * and its configurable tab through exports["./client"], discovered from the - * package.json dsh.client declaration. Every section this page edits is owned - * by the Host plugin that registered it, so this package registers no - * namespace of its own. - */ - -/** Host plugin body — no host-side behavior for this surface plugin. */ -export function apply(): void {} diff --git a/packages/client/ui-settings-plugins/tests/apply.client.spec.ts b/packages/client/ui-settings-plugins/tests/apply.client.spec.ts deleted file mode 100644 index 63ba773884..0000000000 --- a/packages/client/ui-settings-plugins/tests/apply.client.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** What the browser half registers, and that it all leaves with the fiber. */ - -import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, vi } from 'vitest' -import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' -import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-plugins/client' -import type { PluginsSettingsSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-plugins/client' -import { apply as hostApply } from '../src/index.ts' - -// These specs assert the shipped Chinese copy. The lane has no jsdom `window`, -// so browser-language detection never runs and a fresh LocaleRuntime opens on -// FALLBACK_LOCALE (en); bench stages zh explicitly on the locale instead. - -async function bench() { - const ctx = new Context() - await ctx.plugin(SlotRegistry).await() - const locale = new LocaleRuntime(ctx) - locale.setLocale('zh') - ctx.provide('locale', locale) - return { ctx, slots: ctx.get('slots') as SlotRegistry } -} - -/** The Settings shell's section slot, as its owner declares it. */ -function declareRoot(slots: SlotRegistry): () => void { - return slots.register({ - name: 'root', - children: { 'settings.section': { kind: 'list', scope: 'root' } }, - } as never, () => null) -} - -describe('ui-settings-plugins apply', () => { - it('keeps the host Loader entry inert', () => { - expect(hostApply).not.toThrow() - }) - - it('declares the services it uses', () => { - expect(inject).toEqual(['slots', 'locale']) - }) - - it('registers one Built-in plugins section and declares its tab slot, contributing no tab of its own', async () => { - const { ctx, slots } = await bench() - declareRoot(slots) - - await ctx.plugin({ inject: [...inject], apply }).await() - - const section = slots.entries('settings.section')[0]! - expect(section.options).toMatchObject({ id: 'plugins', order: 15 }) - // The nav label is a locale-following thunk; owners resolve it at read time. - expect(resolveSlotLabel(section.options.label)).toBe('内置插件') - expect(slots.spec('settings.plugins.tab')).toMatchObject({ kind: 'list', scope: 'root' }) - expect(slots.entries('settings.plugins.tab')).toHaveLength(0) - }) - - it('injects a live tab projection ordered by the contributions', async () => { - const { ctx, slots } = await bench() - declareRoot(slots) - await ctx.plugin({ inject: [...inject], apply }).await() - - const section = slots.entries('settings.section')[0]! - const sectionFace = (section.inject as () => Pick)() - const initialTabs = sectionFace.hooks.tabs.getSnapshot() - expect(initialTabs).toEqual([]) - expect(sectionFace.hooks.tabs.getSnapshot()).toBe(initialTabs) - - const unsubscribe = sectionFace.hooks.tabs.subscribe(vi.fn()) - slots.register({ name: 'settings.plugins.tab', id: 'plain' } as never, () => null) - slots.register({ name: 'settings.plugins.tab', id: 'first', order: -1 } as never, () => null) - // Tabs follow their contribution's order, whatever order they registered in. - expect(sectionFace.hooks.tabs.getSnapshot()).toEqual([ - { id: 'first', order: -1, label: '' }, - { id: 'plain', order: 0, label: '' }, - ]) - unsubscribe() - }) - - it('registers into a declaration that arrives after apply', async () => { - const { ctx, slots } = await bench() - await ctx.plugin({ inject: [...inject], apply }).await() - - declareRoot(slots) - - await vi.waitFor(() => { expect(slots.entries('settings.section')).toHaveLength(1) }) - }) - - it('collapses the section on teardown', async () => { - const { ctx, slots } = await bench() - declareRoot(slots) - const fiber = ctx.plugin({ inject: [...inject], apply }) - await fiber.await() - expect(slots.entries('settings.section')).toHaveLength(1) - - await fiber.dispose() - - expect(slots.entries('settings.section')).toHaveLength(0) - }) -}) diff --git a/packages/client/ui-settings-plugins/tests/section.client.spec.tsx b/packages/client/ui-settings-plugins/tests/section.client.spec.tsx deleted file mode 100644 index 7b4f0001ef..0000000000 --- a/packages/client/ui-settings-plugins/tests/section.client.spec.tsx +++ /dev/null @@ -1,93 +0,0 @@ -// @vitest-environment jsdom -/** The Built-in plugins section: its heading, its tab row, and which tab is mounted. */ - -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it } from 'vitest' -import { PluginsSettingsSection } from '../src/client/PluginsSettingsSection.tsx' -import type { PluginsSettingsSectionProps, PluginsSettingsTabEntry } from '../src/client/PluginsSettingsSection.tsx' -import { en } from '../src/client/locales.ts' - -afterEach(cleanup) - -const t = (key: keyof typeof en) => en[key] - -function renderSection(rows: readonly PluginsSettingsTabEntry[]) { - const props = { - t, - useTabs: (selector: (value: readonly PluginsSettingsTabEntry[]) => unknown) => selector(rows), - renderSlot: (_name: string, _owner: unknown, options: { only?: string }) => ( - {options.only} - ), - } as PluginsSettingsSectionProps - render() -} - -describe('PluginsSettingsSection', () => { - it('says so when no plugin contributed a tab', () => { - renderSection([]) - - expect(screen.getByText(en.empty)).toBeTruthy() - expect(screen.queryByRole('tab')).toBeNull() - }) - - it('defaults to the first ordered tab and mounts another only after selection', () => { - renderSection([ - { id: 'configurable', order: 0, label: 'Configurable' }, - { id: 'all', order: 10, label: 'Plugin list' }, - ]) - - const configurable = screen.getByRole('tab', { name: 'Configurable' }) - const all = screen.getByRole('tab', { name: 'Plugin list' }) - expect(configurable.getAttribute('aria-selected')).toBe('true') - expect(screen.getByText('configurable')).toBeTruthy() - expect(screen.queryByText('all')).toBeNull() - - fireEvent.click(all) - expect(all.getAttribute('aria-selected')).toBe('true') - expect(screen.getByText('all')).toBeTruthy() - expect(screen.getByText('configurable').closest('[role="tabpanel"]')).toHaveProperty('hidden', true) - - fireEvent.click(configurable) - expect(configurable.getAttribute('aria-selected')).toBe('true') - expect(screen.getByText('all').closest('[role="tabpanel"]')).toHaveProperty('hidden', true) - }) - - it('leads with its own heading and intro', () => { - renderSection([{ id: 'configurable', order: 0, label: 'Configurable' }]) - - expect(screen.getByRole('heading', { name: en.title })).toBeTruthy() - expect(screen.getByText(en.intro)).toBeTruthy() - }) - - it('moves focus and selection with standard horizontal tab keys', () => { - renderSection([ - { id: 'configurable', order: 0, label: 'Configurable' }, - { id: 'all', order: 10, label: 'Plugin list' }, - { id: 'diagnostics', order: 20, label: 'Diagnostics' }, - ]) - - const configurable = screen.getByRole('tab', { name: 'Configurable' }) - const all = screen.getByRole('tab', { name: 'Plugin list' }) - const diagnostics = screen.getByRole('tab', { name: 'Diagnostics' }) - expect(configurable.getAttribute('tabindex')).toBe('0') - expect(all.getAttribute('tabindex')).toBe('-1') - - configurable.focus() - fireEvent.keyDown(configurable, { key: 'ArrowRight' }) - expect(document.activeElement).toBe(all) - expect(all.getAttribute('aria-selected')).toBe('true') - - fireEvent.keyDown(all, { key: 'End' }) - expect(document.activeElement).toBe(diagnostics) - fireEvent.keyDown(diagnostics, { key: 'ArrowRight' }) - expect(document.activeElement).toBe(configurable) - fireEvent.keyDown(configurable, { key: 'ArrowLeft' }) - expect(document.activeElement).toBe(diagnostics) - fireEvent.keyDown(diagnostics, { key: 'Home' }) - expect(document.activeElement).toBe(configurable) - - fireEvent.keyDown(configurable, { key: 'Escape' }) - expect(document.activeElement).toBe(configurable) - expect(configurable.getAttribute('aria-selected')).toBe('true') - }) -}) diff --git a/packages/client/ui-settings-plugins/tsconfig.json b/packages/client/ui-settings-plugins/tsconfig.json deleted file mode 100644 index 92b5591b1f..0000000000 --- a/packages/client/ui-settings-plugins/tsconfig.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "extends": "../../../tsconfig.base.client.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], - "references": [ - { - "path": "../locale/tsconfig.client.json" - }, - { - "path": "../../../vendor/cordis" - }, - { - "path": "../../test-support/client-runtime" - }, - { - "path": "../ui-renderer" - }, - { - "path": "../ui-settings/tsconfig.client.json" - }, - { - "path": "../ui-slots" - }, - { - "path": "../../util/values" - } - ] -} diff --git a/packages/client/ui-settings-session-log/package.json b/packages/client/ui-settings-session-log/package.json index 3ffdcf5953..e2eb9d5130 100644 --- a/packages/client/ui-settings-session-log/package.json +++ b/packages/client/ui-settings-session-log/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-session-log", "description": "General settings control for Session-log upload with DeepSeek API requests", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-shell/package.json b/packages/client/ui-settings-shell/package.json index 5aea5a0ad6..99a79d4bc2 100644 --- a/packages/client/ui-settings-shell/package.json +++ b/packages/client/ui-settings-shell/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-shell", "description": "Settings page of the shell executor on the dsh web client's Plugins page: the command timeout and the per-stream output cap of the shell namespace", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-subagent/package.json b/packages/client/ui-settings-subagent/package.json index 8bc89487d0..e9bf2018d3 100644 --- a/packages/client/ui-settings-subagent/package.json +++ b/packages/client/ui-settings-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-subagent", "description": "Settings page of Subagent delegation on the dsh web client's Plugins page: recursion depth, parallel capacity, and the models agents may choose for subagents", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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-web-search/package.json b/packages/client/ui-settings-web-search/package.json index 5371a10782..f9c36218bf 100644 --- a/packages/client/ui-settings-web-search/package.json +++ b/packages/client/ui-settings-web-search/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-web-search", "description": "Settings page for web search and fetch on the dsh web client's Plugins page: the Search and Fetch provider menus, the DeepSeek Search API result count, DeepSeek Search and Fetch API billing, and legacy Messages search settings", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index c830f51312..6c4ca00638 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -9,8 +9,8 @@ en: 720600abd76a4a91 zh: 822bda08efbfc3e4 /deepseek-ai-dsh-client-ui-settings/summary: - en: 0404ff8b4ec867e0 - zh: 9c3f03dfd1306cc9 + en: 1075b65d5fc8a89b + zh: 9da621629ee1db6f /deepseek-ai-dsh-client-ui-settings/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -24,14 +24,14 @@ en: f9963d1af2293fdd zh: dd221380e737c1d6 /deepseek-ai-dsh-client-ui-settings/use-this-package/filling-the-settings-slots: - en: a6506a37bdb03ac9 - zh: 6b7d74f1d60c6fd8 + en: e35f91d6e1dec279 + zh: e9a8a70953e0cccb /deepseek-ai-dsh-client-ui-settings/use-this-package/observable-success-and-failures: 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 @@ -42,8 +42,8 @@ en: 34872bda24dc50c6 zh: dcccef423906c408 /deepseek-ai-dsh-client-ui-settings/further-exploration: - en: 57e3fe18940ecc83 - zh: 165bd696250de5dc + en: 8775a7a24b986ed6 + zh: 938c7a0ef74dabd0 /deepseek-ai-dsh-client-ui-settings/model-experience: en: 3120df665299c634 zh: 1d9f365d091d0d2a diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index 51ef808ec7..6cb716d1dc 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package lets web-client features expose editable preferences backed by the Host settings document without implementing their own transport or schema handling. Each feature gets namespace-scoped reads and writes, atomic multi-field updates, schema validation, and protection against silently overwriting concurrent changes. It also provides the standard extension points for settings chrome, pages, header actions, plugin tabs, and onboarding while rendering no interface itself. Any preference-owning feature can use it without depending on a presentation package; a separate package provides the settings shell. +This package lets web-client features expose editable preferences backed by the Host settings document without implementing their own transport or schema handling. Each feature gets namespace-scoped reads and writes, atomic multi-field updates, schema validation, and protection against silently overwriting concurrent changes. It also provides the standard extension points for settings chrome, pages, header actions, and onboarding while rendering no interface itself. Any preference-owning feature can use it without depending on a presentation package; a separate package provides the settings shell. ## Table of Contents @@ -42,7 +42,7 @@ A page that edits a namespace another plugin owns registers through `ctx.configF ### Filling the settings slots -A settings surface registers into the slot types this package declares. The shell (`sidebar.settings` occupant, navigation, chrome) lives in ui-settings-general; feature pages register `settings.section` contributions; the Plugins section hosts `settings.plugins.tab` pages; onboarding steps register `settings.onboarding`. Cross-namespace surfaces (schema introspection, the served-namespace directory, `hasDocument`) read the same mirror through `ctx.configForms.describe()`. +A settings surface registers into the slot types this package declares. The shell (`sidebar.settings` occupant, navigation, chrome) lives in ui-settings-general; Settings pages, including a plugin's own settings page, register `settings.section` contributions; the `settings.section.view` Component Factory, registered by ui-settings-general, declares that slot and renders the entry whose `id` the caller passes, with the caller's `close` action, both in Settings and on the [Plugins page](../ui-plugin-manager/README.md#configuration-pages); onboarding steps register `settings.onboarding`. Cross-namespace surfaces (schema introspection, the served-namespace directory, `hasDocument`) read the same mirror through `ctx.configForms.describe()`. To customize a page's navigation icon, use `ctx.slots.inject('settings.section.icon', ...)` and register an icon component with the same `id` as its `settings.section` contribution. Unmatched ids never render, and the icon's `label` option is not displayed. The component receives `size` in pixels and `active`; the shell owns the button, label, and decorative icon wrapper. Without a matching icon registration, the shell renders its default glyph. Disposing the icon contribution restores that glyph. @@ -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 @@ -84,7 +84,7 @@ The provider owns one controller per Host entry, including its subscription and These pages cover the settings surface family and the durable seam behind it. - [ui-settings-general](../ui-settings-general/README.md) — the settings shell: trigger chrome, navigation, General section, onboarding projection. -- [ui-settings-plugins](../ui-settings-plugins/README.md) — the Built-in plugins section shell around the inventory tab. +- [ui-plugin-manager](../ui-plugin-manager/README.md) — the Plugins page, which also shows a plugin's `settings.section` entry on that plugin's bundle row. - [ui-settings-shell](../ui-settings-shell/README.md), [ui-settings-agent-loop](../ui-settings-agent-loop/README.md), [ui-settings-subagent](../ui-settings-subagent/README.md), [ui-settings-web-search](../ui-settings-web-search/README.md) — the official configuration pages on the Plugins page, each following its namespaces through `whileServed`. - [ui-settings-models](../ui-settings-models/README.md) — the Models page and DeepSeek onboarding over this base. - [settings](../../settings/README.md) — the durable user-settings seam and its file provider. diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index fff25c57ec..ba4e030086 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -本包使 Web 客户端功能能够公开由宿主设置文档支持的可编辑偏好设置,而无需自行实现传输或 schema 处理。每项功能都可按命名空间读写、原子更新多个字段、校验 schema,并避免静默覆盖并发更改。它还为设置界面框架、页面、标题栏操作、插件标签页和引导流程提供标准扩展点,但自身不渲染任何界面。任何持有偏好设置的功能都可在不依赖呈现包的情况下使用它;设置外壳由单独的包提供。 +本包使 Web 客户端功能能够公开由宿主设置文档支持的可编辑偏好设置,而无需自行实现传输或 schema 处理。每项功能都可按命名空间读写、原子更新多个字段、校验 schema,并避免静默覆盖并发更改。它还为设置界面框架、页面、标题栏操作和引导流程提供标准扩展点,但自身不渲染任何界面。任何持有偏好设置的功能都可在不依赖呈现包的情况下使用它;设置外壳由单独的包提供。 ## 目录 @@ -42,7 +42,7 @@ kind: "package-reference" ### 填充设置 slot -设置界面会注册进本包声明的 slot 类型。外壳(`sidebar.settings` 占位方、导航、界面框架)位于 ui-settings-general;功能页面注册 `settings.section` 贡献;「插件」分区承载 `settings.plugins.tab` 页面;首次使用引导步骤注册 `settings.onboarding`。跨命名空间的表面(schema 内省、已服务命名空间目录、`hasDocument`)通过 `ctx.configForms.describe()` 读同一面镜像。 +设置界面会注册进本包声明的 slot 类型。外壳(`sidebar.settings` 占位方、导航、界面框架)位于 ui-settings-general;设置页面(包括插件自己的设置页面)注册 `settings.section` 贡献;由 ui-settings-general 注册的 `settings.section.view` Component Factory 声明该 slot,按调用方传入的 `id` 渲染对应条目,并传入调用方的 `close` 操作,设置与[插件页面](../ui-plugin-manager/README.zh.md#configuration-pages)都经由它渲染;首次使用引导步骤注册 `settings.onboarding`。跨命名空间的表面(schema 内省、已服务命名空间目录、`hasDocument`)通过 `ctx.configForms.describe()` 读同一面镜像。 要自定义页面的导航图标,使用 `ctx.slots.inject('settings.section.icon', ...)`,并以与其 `settings.section` 贡献相同的 `id` 注册图标组件。不匹配的 id 不会渲染,图标的 `label` 选项不会显示。组件接收以像素为单位的 `size` 和 `active`;外壳负责按钮、标签和装饰性图标容器。没有匹配的图标注册时,外壳渲染默认图标。释放图标贡献后恢复该默认图标。 @@ -55,7 +55,7 @@ kind: "package-reference" ## 理解实现 -可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。 +可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。可选的 `settings.notice` 贡献接收 openSettings,渲染在入口行上方零高度的满宽行中,浮在侧栏列表之上;折叠轨道中外壳隐藏该行但不卸载它。
      实现细节——点击展开 @@ -84,7 +84,7 @@ kind: "package-reference" 以下页面覆盖设置界面家族及其背后的持久化 seam。 - [ui-settings-general](../ui-settings-general/README.zh.md)——设置外壳:触发控件、导航、「通用」分区、引导投影。 -- [ui-settings-plugins](../ui-settings-plugins/README.zh.md)——围绕清单标签页的「内置插件」分区壳。 +- [ui-plugin-manager](../ui-plugin-manager/README.zh.md)——插件页面,也在插件所在的组合包行上显示其 `settings.section` 条目。 - [ui-settings-shell](../ui-settings-shell/README.zh.md)、[ui-settings-agent-loop](../ui-settings-agent-loop/README.zh.md)、[ui-settings-subagent](../ui-settings-subagent/README.zh.md)、[ui-settings-web-search](../ui-settings-web-search/README.zh.md)——插件页上的官方配置页,各自通过 `whileServed` 跟随其命名空间。 - [ui-settings-models](../ui-settings-models/README.zh.md)——建立在本底座之上的 Models 页面与 DeepSeek 引导。 - [settings](../../settings/README.zh.md)——持久化用户设置 seam 及其文件提供方。 diff --git a/packages/client/ui-settings/package.json b/packages/client/ui-settings/package.json index 06ba6ab951..516def03fe 100644 --- a/packages/client/ui-settings/package.json +++ b/packages/client/ui-settings/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings", "description": "Settings domain base plugin: shared configuration forms and the canonical settings slot-type contract", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts index dbab0c7df1..7c2c5aedcf 100644 --- a/packages/client/ui-settings/src/client/contract/slots.ts +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -12,9 +12,30 @@ import type {} from '@deepseek-ai/dsh-client-ui-slots' declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotFactoryMap { + /** + * One `settings.section` entry, rendered wherever a surface shows that + * page: the Settings panel and the Plugins page. Props: `id` (the entry's + * id) and `close` (the surface's leave action, passed to the entry). + * Registered by the settings shell, which therefore declares + * `settings.section`. + */ + 'settings.section.view': { + scope: 'root' + props: SettingsSectionViewProps + children: { 'settings.section': { kind: 'list'; scope: 'root' } } + } + } + 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 @@ -44,12 +65,15 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { */ 'settings.close': { kind: 'single'; scope: 'root'; owner: SettingsHeaderOwnerProps } /** - * One settings page per list entry. Registrant options carry the nav + * One settings page per list entry, rendered through the + * `settings.section.view` Factory. Settings lists every entry in its + * navigation; the Plugins page also shows an entry on the listed bundle row + * (or bundle) whose module is the registering package, when that row (or + * bundle) registers no configuration of its own. Registrant options carry the nav * identity: `id` (section key, drives `only` filtering), `order` (nav - * position), `label` (registrant-localized display text — the registrant - * re-registers with fresh text on locale change, so the shell never - * subscribes locale state; the ledger bump doubles as the shell's - * re-render trigger). Sections render inside the panel content column. + * position), `label` (registrant-localized display text, usually a thunk + * that each projection re-reads on locale change). An entry renders + * wherever a caller renders `settings.section.view` with its id. * (`settings.general.item`, declared by ui-settings-general's General * entry, is typed in the locale package — the common dependency of every * item registrant; the shell neither declares nor renders it.) @@ -63,15 +87,6 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * no icon is registered for that id. */ 'settings.section.icon': { kind: 'list'; scope: 'root'; inline: true; owner: SettingsSectionIconOwnerProps } - /** - * One page inside the Plugins settings section. The section owner renders - * localized entry labels as tabs and mounts each contribution inside its - * corresponding tab panel. Options: `id` (tab key), `order` (tab order), - * and `label` (registrant-localized tab text). Declared at runtime by the - * feature that owns the Plugins section; the type lives here so inventory - * and configuration plugins collaborate without depending on one another. - */ - 'settings.plugins.tab': { kind: 'list'; scope: 'root'; owner: SettingsPluginsTabOwnerProps } /** * Root-scoped onboarding steps contributed by settings features. The * shell mounts one ordered step at a time; the active registrant either @@ -106,10 +121,12 @@ export interface SettingsGeneralItemOwnerProps { children?: never } -/** Owner share of a Plugins tab (the section supplies nothing). */ -export interface SettingsPluginsTabOwnerProps { - /** Marker field: tab owner props are intentionally empty. */ - children?: never +/** Caller props of the `settings.section.view` Factory. */ +export interface SettingsSectionViewProps { + /** The `settings.section` entry id to render. */ + id: string + /** The rendering surface's leave action. */ + close: () => void } /** Owner share of the trigger content seat: the sidebar column state. */ @@ -132,7 +149,7 @@ export interface SettingsHeaderOwnerProps { * onboarding coordinator's `openSection`/`complete` precedent, inverted. */ export interface SettingsSectionOwnerProps { - /** Close the settings panel (the shell owns the open state). */ + /** Leave the page: close the settings panel, or on the Plugins page return to the view the page was opened from. */ close: () => void } @@ -156,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 706aa6935f..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, - SettingsPluginsTabOwnerProps, SettingsSectionIconOwnerProps, SettingsSectionOwnerProps, 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/package.json b/packages/client/ui-shortcuts/package.json index 58b6d5815c..1bab33a446 100644 --- a/packages/client/ui-shortcuts/package.json +++ b/packages/client/ui-shortcuts/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-shortcuts", "description": "Keyboard shortcut reference, recording, and local preference editing", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -58,7 +58,8 @@ "@deepseek-ai/dsh-brand": "workspace:*", "clsx": "^2.1.1", "react": "^18.2.0", - "@deepseek-ai/dsh-client-test-runtime": "workspace:*" + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-util-text-search": "workspace:*" }, "files": [ "locale/*.json", 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-shortcuts/src/client/Reference.tsx b/packages/client/ui-shortcuts/src/client/Reference.tsx index 1235b27631..8a63b237d5 100644 --- a/packages/client/ui-shortcuts/src/client/Reference.tsx +++ b/packages/client/ui-shortcuts/src/client/Reference.tsx @@ -1,6 +1,7 @@ /** Searchable editable shortcut reference and its General Settings row. */ -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' -import { Button, IconCloseOutlineRegular, IconRefreshOutlineRegular, Modal, ShortcutKeys, Tooltip, Toast, focusWithoutRing, isBehindModal, rankByName } from '@deepseek-ai/dsh-client-ui-primitives' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { Button, IconCloseOutlineRegular, IconRefreshOutlineRegular, Modal, ShortcutKeys, Tooltip, Toast, focusWithoutRing, isBehindModal } from '@deepseek-ai/dsh-client-ui-primitives' +import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { ObservableSnapshot, PropsStore } from '@deepseek-ai/dsh-client-store' import type { ShortcutCatalogEntry, ShortcutPlatform, Shortcuts } from '@deepseek-ai/dsh-client-shortcuts/client' @@ -133,7 +134,7 @@ export function ShortcutReference({ if (open && input !== null && !isBehindModal(input)) focusWithoutRing(input) }, [open, focusRequest]) // Stop stays after the other fixed input actions. - const entries = [ + const entryIndex = useMemo(() => new TextSearchIndex([ ...catalog.map(row => ({ ...row, names: [...row.aliases, row.keys.filter(key => key !== '+').join('+'), row.keys.filter(key => key !== '+').join(''), row.aria ?? '', row.aria?.replace('Meta', 'Cmd') ?? ''], @@ -142,9 +143,8 @@ export function ShortcutReference({ ...fixedCatalog.map(row => ({ ...row, names: [row.id, row.keys.join(' ')] })), ].sort((left, right) => Number(left.id === 'response.stop') - Number(right.id === 'response.stop') || (coreActionOrder.get(left.id) ?? coreActionOrder.size) - (coreActionOrder.get(right.id) ?? coreActionOrder.size) - || Number(left.id > right.id) - Number(left.id < right.id)) - const ranked = rankByName(entries.flatMap(row => row.names.map(name => ({ name, label: row.label, row }))), query.trim()) - const matches = [...new Set(ranked.map(match => match.row))] + || Number(left.id > right.id) - Number(left.id < right.id)), row => ({ fuzzy: [row.label, ...row.names] })), [catalog, fixedCatalog]) + const matches = entryIndex.search(query) const modifiedCount = Object.keys(config.document.profiles[`${runtime}:${platform}`] ?? {}).length useLayoutEffect(() => { const input = search.current diff --git a/packages/client/ui-shortcuts/tsconfig.json b/packages/client/ui-shortcuts/tsconfig.json index 79242fd4a6..e5284feae0 100644 --- a/packages/client/ui-shortcuts/tsconfig.json +++ b/packages/client/ui-shortcuts/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../../util/text-search" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/client/ui-sidebar-browser/package.json b/packages/client/ui-sidebar-browser/package.json index 1f006bfda3..9a8afd696f 100644 --- a/packages/client/ui-sidebar-browser/package.json +++ b/packages/client/ui-sidebar-browser/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-browser", "description": "Sandboxed Web browser tabs for the right Sidebar", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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..78b9098005 100644 --- a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml +++ b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml @@ -24,11 +24,11 @@ en: 26c4fa4d4bbaa6ac zh: e889b67cb167092b /deepseek-ai-dsh-client-ui-sidebar-documentpreview/excel-preview: - en: 595499992ceea693 - zh: 83c6147c46a80dca + en: 3bbbb4e0ca7786a3 + zh: 6206ad42b48f5991 /deepseek-ai-dsh-client-ui-sidebar-documentpreview/office-preview: - en: c683150a3c92be68 - zh: 65b63c0961a8b2fb + en: fe553ccae747bc4e + zh: d0894886ab8a0ad0 /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..c7aba71ff0 100644 --- a/packages/client/ui-sidebar-documentpreview/README.md +++ b/packages/client/ui-sidebar-documentpreview/README.md @@ -78,7 +78,7 @@ XLSX preview omits DrawingML parts from an in-memory copy before parsing and ign CSV and TSV default to the spreadsheet viewer and also offer Plain text; CSV additionally offers syntax-highlighted Code. Commas and tabs delimit their fields respectively; quoted separators, escaped quotes, multiline fields, empty fields, and unequal row lengths are supported. The first row remains data. Values remain literal strings, including leading zeros, dates, booleans, and formula-looking text. Text files accept UTF-8 or BOM-marked UTF-16; invalid encoding receives conversion guidance. Malformed quoted fields fail the table preview rather than silently dropping data. -Configure `excel` on the same `ui-sidebar-documentpreview` entry. These limits complement the Host's complete-file read limit; they do not cap browser process memory or decompression allocations. +Configure `excel` on the same `ui-sidebar-documentpreview` entry. These limits complement the Host's complete-file read limit; they do not cap browser process memory or decompression allocations. The browser applies them as described for [`office`](#office-preview). | Field | Default | Meaning | |---|---|---| @@ -97,7 +97,7 @@ The pinned [ExcelJS patch](../../../patches/exceljs@4.4.0.patch) resolves the wo Open `.doc`, `.docx`, `.ppt`, and `.pptx` as PDF previews with the same loading state, zoom controls, cancellation, and selectable text as PDF files. The [Host provider](../../document/office-kit/README.md) performs local conversion and retains its spreadsheet conversion API for other consumers. Invalid supported files, conversion failures, and timeouts receive localized messages. Missing Host services show configuration guidance. -The [Web bundle](../../bundle/web-app/README.md) mounts this package as `ui-sidebar-documentpreview`. Configure its transient Office cache through that entry's `office` settings; the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-client-ui-sidebar-documentpreview) defines accepted values. Settings are embedded in each served page; reload the browser page after changing YAML. +The [Web bundle](../../bundle/web-app/README.md) mounts this package as `ui-sidebar-documentpreview`. Configure its transient Office cache through that entry's `office` settings; the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-client-ui-sidebar-documentpreview) defines accepted values. The `office` and `excel` objects reach the browser through the plugin's [synced Config](../modules/README.md#synced-plugin-configuration); the browser reads both once when the plugin activates, so a change takes effect on the next page load or plugin reactivation. A page that receives no value uses the defaults below. | Field | Default | Meaning | |---|---|---| @@ -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..2bebc96bf2 100644 --- a/packages/client/ui-sidebar-documentpreview/README.zh.md +++ b/packages/client/ui-sidebar-documentpreview/README.zh.md @@ -78,7 +78,7 @@ XLSX 预览在解析前从内存副本中移除 DrawingML 部件,并忽略工 CSV 和 TSV 默认使用表格查看器,也可选择纯文本;CSV 还提供带语法高亮的 Code 预览。两者分别以逗号和制表符分隔字段,支持引号内分隔符、转义引号、多行字段、空字段和不等长行。首行仍作为数据。值保持为字面字符串,包括前导零、日期、布尔值和类似公式的文本。文本文件支持 UTF-8 或带 BOM 的 UTF-16;无效编码会显示转换提示。引号字段格式错误会使表格预览失败,不会静默丢弃数据。 -在同一个 `ui-sidebar-documentpreview` 条目上配置 `excel`。这些限制补充 Host 的完整文件读取限制,但不限制浏览器进程内存或解压分配量。 +在同一个 `ui-sidebar-documentpreview` 条目上配置 `excel`。这些限制补充 Host 的完整文件读取限制,但不限制浏览器进程内存或解压分配量。浏览器应用这些限制的方式与 [`office`](#office-preview) 相同。 | 字段 | 默认值 | 含义 | |---|---|---| @@ -97,7 +97,7 @@ CSV 和 TSV 默认使用表格查看器,也可选择纯文本;CSV 还提供 将 `.doc`、`.docx`、`.ppt` 和 `.pptx` 打开为 PDF 预览,使用与 PDF 文件相同的加载状态、缩放控件、取消和文本选择能力。[Host 提供方](../../document/office-kit/README.zh.md)负责本地转换,并为其他消费者保留电子表格转换 API。受支持的无效文件、转换失败和超时会显示本地化消息。缺少 Host 服务时显示配置引导。 -[Web bundle](../../bundle/web-app/README.zh.md) 以 `ui-sidebar-documentpreview` 挂载本包。通过该条目的 `office` 设置配置临时 Office 缓存;[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-client-ui-sidebar-documentpreview)定义可接受的值。设置注入到每个页面;修改 YAML 后重新加载浏览器页面。 +[Web bundle](../../bundle/web-app/README.zh.md) 以 `ui-sidebar-documentpreview` 挂载本包。通过该条目的 `office` 设置配置临时 Office 缓存;[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-client-ui-sidebar-documentpreview)定义可接受的值。`office` 和 `excel` 两个对象通过插件的[同步配置](../modules/README.zh.md#synced-plugin-configuration)送达浏览器;浏览器在插件激活时各读取一次,因此修改在下次页面加载或插件重新激活时生效。未收到值的页面使用下表默认值。 | 字段 | 默认值 | 含义 | |---|---|---| @@ -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/package.json b/packages/client/ui-sidebar-documentpreview/package.json index 030414f29a..7e7f7f738c 100644 --- a/packages/client/ui-sidebar-documentpreview/package.json +++ b/packages/client/ui-sidebar-documentpreview/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-documentpreview", "description": "Extensible Sidebar previews for Office documents, spreadsheets, Markdown, code, images, PDF, HTML, and plain text", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -90,7 +90,8 @@ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz", "yaml": "^2.9.0", "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", - "@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-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/src/client/excel/index.ts b/packages/client/ui-sidebar-documentpreview/src/client/excel/index.ts index 28a2336475..9ea663abd4 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/excel/index.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/excel/index.ts @@ -1,7 +1,7 @@ /** Excel previews use ordinary authorized file bytes without Office conversion. */ import type { Context } from '@deepseek-ai/cordis' import type {} from '../index.ts' -import type { Config } from '../../config.ts' +import type { ExcelLimits } from '../../types.ts' import { LazyExcelBody } from './LazyExcelBody.tsx' import { en, ja, es, fr, de, ru, pt, zh } from './locales.ts' @@ -10,7 +10,7 @@ import { en, ja, es, fr, de, ru, pt, zh } from './locales.ts' * @param ctx - Preview and locale registries. * @param limits - Resolved parser limits. */ -export function apply(ctx: Context, limits: Config['excel']): void { +export function apply(ctx: Context, limits: ExcelLimits): void { const id = '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/excel' ctx.effect(() => ctx.locale.register('sidebarExcel', { zh, en, ja, es, fr, de, ru, pt })) const t = ctx.locale.bind('sidebarExcel') diff --git a/packages/client/ui-sidebar-documentpreview/src/client/index.ts b/packages/client/ui-sidebar-documentpreview/src/client/index.ts index be88ecf06b..171e36dd5c 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/index.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/index.ts @@ -39,7 +39,9 @@ import { apply as registerPdf } from './pdf/index.ts' import { apply as registerCode } from './code/index.ts' import { apply as registerOffice } from './office/index.ts' import { apply as registerExcel } from './excel/index.ts' -import { Config } from '../config.ts' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { DocumentPreviewConfig } from '../types.ts' +import { EXCEL_DEFAULTS, OFFICE_DEFAULTS } from '../defaults.ts' // Values stay package-private unless another package needs them; the plugin // surface is `apply`, `inject`, and the store factory another registration may @@ -85,9 +87,9 @@ export const inject = ['slots', 'locale', 'sidebarRightTabs', 'remote', 'remote. /** * Client plugin body: register the type, its dictionaries, its body, and its chip title. * @param ctx - client root context carrying the registry, slots, copy, and file readers. + * @param config - Host-synced Office and Excel limits, read once here; an absent value uses the schema defaults. */ -export function apply(ctx: ClientContext): void { - const config = Config((globalThis as { __DSH_DOCUMENT_PREVIEW_CONFIG__?: unknown }).__DSH_DOCUMENT_PREVIEW_CONFIG__ ?? {}) +export function apply(ctx: ClientContext, config: SyncedConfig): void { const previews = new DocumentPreviewRegistry() const disposePreviews = ctx.reflect.provide('documentPreviews', previews) ctx.effect(() => disposePreviews) @@ -126,7 +128,7 @@ export function apply(ctx: ClientContext): void { registerHtml(ctx) registerImage(ctx) registerPdf(ctx) - registerOffice(ctx, config.office) - registerExcel(ctx, config.excel) + registerOffice(ctx, config.office.get() ?? OFFICE_DEFAULTS) + registerExcel(ctx, config.excel.get() ?? EXCEL_DEFAULTS) registerCode(ctx) } diff --git a/packages/client/ui-sidebar-documentpreview/src/client/office/index.ts b/packages/client/ui-sidebar-documentpreview/src/client/office/index.ts index 3de4a48be2..a8cf082014 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/office/index.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/office/index.ts @@ -15,7 +15,7 @@ import { OfficeBody, type OfficeBodyInjected } from './OfficeBody.tsx' import { OfficeFontAction } from './OfficeFontAction.tsx' import { officeFace } from './face.ts' import { createOfficeStore } from './store.ts' -import type { Config } from '../../config.ts' +import type { OfficeLimits } from '../../types.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { @@ -28,7 +28,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * @param ctx - Client renderer registry, localized copy, and optional Host Remotes. * @param config - Resolved Office preview cache limits. */ -export function apply(ctx: Context, config: Config['office']): void { +export function apply(ctx: Context, config: OfficeLimits): void { const id = '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/office' const extensions = ['doc', 'docx', 'ppt', 'pptx'] ctx.effect(() => ctx.locale.register('sidebarOffice', { zh, en, ja, es, fr, de, ru, pt })) diff --git a/packages/client/ui-sidebar-documentpreview/src/config.ts b/packages/client/ui-sidebar-documentpreview/src/config.ts deleted file mode 100644 index 67fab69d44..0000000000 --- a/packages/client/ui-sidebar-documentpreview/src/config.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** Cache limits shared by the Host configuration and browser document previews. */ -import z from '@deepseek-ai/schemastery' - -/** Transient Office conversion reuse within one Client connection. */ -export interface Config { - /** Retained PDF limits; pending conversions share cancellation by reader lifetime. */ - office: { - /** Maximum retained completed PDFs. */ - maxCachedEntries: number - /** Maximum retained PDF bytes, counted by each binary buffer's byteLength. */ - maxCachedBytes: number - /** Maximum unsettled Host conversion RPCs, including cancellation teardown. */ - maxPending: number - /** Maximum readers including source and renderer metadata lookups. */ - maxReaders: number - } - /** Browser spreadsheet parser and dense cell allocation limits. */ - excel: { - /** Maximum source file bytes. */ - maxBytes: number - /** Maximum combined rectangular cell area across worksheets. */ - maxCells: number - /** Maximum parser Worker lifetime in milliseconds. */ - timeoutMs: number - } -} - -/** Deployment limits applied before Office preview registration. */ -export const Config: z<{ office?: Partial; excel?: Partial }, Config> = z.object({ - office: z.object({ - maxCachedEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8), - maxCachedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(64 * 1024 * 1024), - maxPending: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8), - maxReaders: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(32), - }), - excel: z.object({ - maxBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(16 * 1024 * 1024), - maxCells: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(250_000), - timeoutMs: z.natural().min(1).max(2_147_483_647).default(15_000), - }), -}) diff --git a/packages/client/ui-sidebar-documentpreview/src/defaults.ts b/packages/client/ui-sidebar-documentpreview/src/defaults.ts new file mode 100644 index 0000000000..f6109cf745 --- /dev/null +++ b/packages/client/ui-sidebar-documentpreview/src/defaults.ts @@ -0,0 +1,17 @@ +/** Default preview limits, shared by the Host schema and the browser's fallback for an absent synced value. */ +import type { ExcelLimits, OfficeLimits } from './types.ts' + +/** Office cache limits a Config without `office` keys resolves to. */ +export const OFFICE_DEFAULTS: Readonly = Object.freeze({ + maxCachedEntries: 8, + maxCachedBytes: 64 * 1024 * 1024, + maxPending: 8, + maxReaders: 32, +}) + +/** Spreadsheet parser limits a Config without `excel` keys resolves to. */ +export const EXCEL_DEFAULTS: Readonly = Object.freeze({ + maxBytes: 16 * 1024 * 1024, + maxCells: 250_000, + timeoutMs: 15_000, +}) diff --git a/packages/client/ui-sidebar-documentpreview/src/index.ts b/packages/client/ui-sidebar-documentpreview/src/index.ts index 0cb5d067a4..ea51ade359 100644 --- a/packages/client/ui-sidebar-documentpreview/src/index.ts +++ b/packages/client/ui-sidebar-documentpreview/src/index.ts @@ -1,17 +1,31 @@ -/** Host configuration for browser document previews. */ +/** Host Loader entry declaring the browser document preview limits; previews belong to the Client. */ import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-host-webserver' -import type { Config } from './config.ts' +import z from '@deepseek-ai/schemastery' +import { EXCEL_DEFAULTS, OFFICE_DEFAULTS } from './defaults.ts' +import type { DocumentPreviewConfig, ExcelLimits, OfficeLimits } from './types.ts' -export { Config } from './config.ts' +/** Preview limits synced to the browser. */ +export type Config = DocumentPreviewConfig + +/** Deployment limits synced to the browser, which applies them when the plugin activates. */ +export const Config: z<{ office?: Partial; excel?: Partial }, Config> = z.object({ + office: z.object({ + maxCachedEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(OFFICE_DEFAULTS.maxCachedEntries), + maxCachedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(OFFICE_DEFAULTS.maxCachedBytes), + maxPending: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(OFFICE_DEFAULTS.maxPending), + maxReaders: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(OFFICE_DEFAULTS.maxReaders), + }).default({}).volatile(), + excel: z.object({ + maxBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(EXCEL_DEFAULTS.maxBytes), + maxCells: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(EXCEL_DEFAULTS.maxCells), + timeoutMs: z.natural().min(1).max(2_147_483_647).default(EXCEL_DEFAULTS.timeoutMs), + }).default({}).volatile(), +}) /** - * Embed validated preview settings in browser pages. - * @param ctx - Host context serving browser pages. - * @param config - Cache limits adopted when the page loads. + * Register the browser plugin without Host behavior; the Loader validates the entry's Config, and the browser face + * receives its volatile fields. + * @param _ctx - Host context; unused. + * @param _config - validated Config; unused on the Host. */ -export function apply(ctx: Context, config: Config): void { - ctx.on('webserver/index-inject', (table) => { - table.push({ kind: 'global', name: '__DSH_DOCUMENT_PREVIEW_CONFIG__', value: config }) - }) -} +export function apply(_ctx: Context, _config: Config): void {} diff --git a/packages/client/ui-sidebar-documentpreview/src/types.ts b/packages/client/ui-sidebar-documentpreview/src/types.ts new file mode 100644 index 0000000000..33dc533cad --- /dev/null +++ b/packages/client/ui-sidebar-documentpreview/src/types.ts @@ -0,0 +1,32 @@ +/** Document preview configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' + +/** Retained PDF limits; pending conversions share cancellation by reader lifetime. */ +export interface OfficeLimits { + /** Maximum retained completed PDFs. */ + maxCachedEntries: number + /** Maximum retained PDF bytes, counted by each binary buffer's byteLength. */ + maxCachedBytes: number + /** Maximum unsettled Host conversion RPCs, including cancellation teardown. */ + maxPending: number + /** Maximum readers including source and renderer metadata lookups. */ + maxReaders: number +} + +/** Browser spreadsheet parser and dense cell allocation limits. */ +export interface ExcelLimits { + /** Maximum source file bytes. */ + maxBytes: number + /** Maximum combined rectangular cell area across worksheets. */ + maxCells: number + /** Maximum parser Worker lifetime in milliseconds. */ + timeoutMs: number +} + +/** Preview limits; the browser receives each object through its synced Config and reads it once when the plugin activates. */ +export interface DocumentPreviewConfig { + /** Transient Office conversion reuse within one Client connection. */ + office: Volatile + /** Browser spreadsheet parser limits. */ + excel: Volatile +} diff --git a/packages/client/ui-sidebar-documentpreview/tests/apply.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/apply.client.spec.ts index efdcaad691..b5316755c5 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/apply.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/apply.client.spec.ts @@ -8,7 +8,8 @@ * makes a reload safe. */ import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' -import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { RemoteError, syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' +import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -34,6 +35,8 @@ import { CodeBody } from '../src/client/code/CodeBody.tsx' import { en, ja, zh, es, fr, de, ru, pt } from '../src/client/locales.ts' import type { textFace } from '../src/client/face.ts' import type { TextStore } from '../src/client/store.ts' +import { EXCEL_DEFAULTS, OFFICE_DEFAULTS } from '../src/defaults.ts' +import type { DocumentPreviewConfig } from '../src/types.ts' import { FILE, SESSION, TAB_ID, byteResult, createResources, page } from './fixtures.client.ts' interface Recorded { @@ -46,7 +49,7 @@ interface Recorded { children?: Record } -async function boot() { +async function boot(values: SyncedConfigValues = { office: OFFICE_DEFAULTS, excel: EXCEL_DEFAULTS }) { const ctx = new Context() ctx.provide('fileDrag', { actions: { prepare: async () => ({ start: () => true, release: () => {} }), reportFailure: () => {} }, read: () => undefined } satisfies import('@deepseek-ai/cordis').Context['fileDrag']) ctx.provide('contextMenus', { open: vi.fn() } as never) @@ -77,7 +80,7 @@ async function boot() { ctx.provide('locale', locale as never) ctx.provide('remote', { workspaceFiles: { read, readBytes } } as never) ctx.provide('remote.workspaceFiles', { read, readBytes } as never) - const fiber = ctx.plugin({ inject: [...inject], apply }) + const fiber = ctx.plugin({ inject: [...inject], apply }, syncedConfig(values)) onTestFinished(async () => { await fiber.dispose() }) await fiber.await() return { ctx, tabs, registered, dictionaries, fiber, read, readBytes } @@ -113,6 +116,18 @@ describe('ui-sidebar-documentpreview apply', () => { expect(typeof registered[0]?.inject).toBe('function') }) + it('hands the synced Excel limits to the spreadsheet body, and the schema defaults while none arrived', async () => { + const excel = '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/excel' + const limits = { ...EXCEL_DEFAULTS, maxCells: 7 } + const synced = await boot({ office: { ...OFFICE_DEFAULTS, maxReaders: 2 }, excel: limits }) + const injected = synced.registered.find(entry => entry.key === excel)?.inject as () => unknown + expect(injected()).toEqual({ limits }) + await synced.fiber.dispose() + const absent = await boot({}) + const fallback = absent.registered.find(entry => entry.key === excel)?.inject as () => unknown + expect(fallback()).toEqual({ limits: EXCEL_DEFAULTS }) + }) + it('takes every registration back when the plugin is disposed', async () => { const { tabs, registered, dictionaries, fiber } = await boot() await fiber.dispose() diff --git a/packages/client/ui-sidebar-documentpreview/tests/config.host.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/config.host.spec.ts index 8a09bdd497..0362edce7c 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/config.host.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/config.host.spec.ts @@ -1,34 +1,25 @@ -/** Host configuration supplies bounded Office reuse settings to browser pages. */ +/** The Host entry declares the browser preview limits as synced Config and serves nothing itself. */ import { Context } from '@deepseek-ai/cordis' -import type { IndexInjection, WebServer } from '@deepseek-ai/dsh-host-webserver' import { expect, it, onTestFinished } from 'vitest' -import { Config } from '../src/config.ts' import * as host from '../src/index.ts' +import { EXCEL_DEFAULTS, OFFICE_DEFAULTS } from '../src/defaults.ts' -/** The Peer an index render speaks for; this listener reads no field of it. */ -const PAGE_PEER = { principal: { kind: 'owner' } } as Parameters[1] - -it('exposes Client cache and spreadsheet limits on the Host entry', () => { - expect(host.Config).toBe(Config) - expect(Config({})).toEqual({ office: { - maxCachedEntries: 8, maxCachedBytes: 64 * 1024 * 1024, maxPending: 8, maxReaders: 32, - }, excel: { maxBytes: 16 * 1024 * 1024, maxCells: 250_000, timeoutMs: 15_000 } }) - for (const key of ['maxCachedEntries', 'maxCachedBytes']) expect(() => Config({ office: { [key]: 0 } })).toThrow() - for (const key of ['maxBytes', 'maxCells', 'timeoutMs']) expect(() => Config({ excel: { [key]: 0 } })).toThrow() - expect(() => Config({ excel: { timeoutMs: 2_147_483_648 } })).toThrow() +it('resolves each limit object to the shared defaults and rejects out-of-range limits', () => { + const config = host.Config({}) + expect(config.office.get()).toEqual(OFFICE_DEFAULTS) + expect(config.excel.get()).toEqual(EXCEL_DEFAULTS) + expect(OFFICE_DEFAULTS).toEqual({ maxCachedEntries: 8, maxCachedBytes: 64 * 1024 * 1024, maxPending: 8, maxReaders: 32 }) + expect(EXCEL_DEFAULTS).toEqual({ maxBytes: 16 * 1024 * 1024, maxCells: 250_000, timeoutMs: 15_000 }) + expect(host.Config({ office: { maxCachedEntries: 2 } }).office.get()).toEqual({ ...OFFICE_DEFAULTS, maxCachedEntries: 2 }) + for (const key of ['maxCachedEntries', 'maxCachedBytes', 'maxPending', 'maxReaders']) expect(() => host.Config({ office: { [key]: 0 } })).toThrow() + for (const key of ['maxBytes', 'maxCells', 'timeoutMs']) expect(() => host.Config({ excel: { [key]: 0 } })).toThrow() + expect(() => host.Config({ excel: { timeoutMs: 2_147_483_648 } })).toThrow() }) -it('embeds YAML cache settings in browser pages and withdraws them on disposal', async () => { +it('activates without Host behavior', async () => { const ctx = new Context() onTestFinished(async () => { await ctx.fiber.dispose() }) - const config = Config({ office: { maxCachedEntries: 2 } }) - const fiber = ctx.plugin(host, config) + const fiber = ctx.plugin(host, {}) await fiber.await() - const rows: IndexInjection[] = [] - ctx.emit('webserver/index-inject', rows, PAGE_PEER) - expect(rows).toEqual([{ kind: 'global', name: '__DSH_DOCUMENT_PREVIEW_CONFIG__', value: config }]) await fiber.dispose() - const after: IndexInjection[] = [] - ctx.emit('webserver/index-inject', after, PAGE_PEER) - expect(after).toEqual([]) }) diff --git a/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx b/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx index 2053ab3659..a42055c3f9 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx +++ b/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom /** Document extension registration and dispatch through the production Sidebar and Slot renderer. */ -import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' +import { contextMenuHook, syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { byteResult } from './fixtures.client.ts' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -56,7 +56,7 @@ async function boot() { 'conversation.session.header.corner': { kind: 'single', scope: 'session' }, }) await rt.sessions.add({ id: SESSION }) - await rt.sessions.retainFor(rt.ctx, SESSION, { source: 'mainView' }).ready + await rt.sessions.retainFor(rt.ctx, SESSION, { source: 'mainView', facets: { conversation: true } }).ready await rt.mount({ inject: [...resourcesInject], apply: resourcesApply }) const read = vi.fn().mockImplementation(async (_sessionId, _path, range) => ({ ok: true, @@ -71,7 +71,7 @@ async function boot() { }, })) await rt.mount({ inject: [...sidebarInject], apply: sidebarApply }) - await rt.mount({ inject: [...inject], apply }) + await rt.mount({ inject: [...inject], apply }, syncedConfig({})) const view = rt.renderSlot('rightbar', { width: 600, viewportWidth: 1440, canShow: true }) const open = (name: string): void => { act(() => { rt.ctx.sidebarRight.openResource('dsh-resource://file/session/documents/' + name) }) diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-body.client.spec.tsx b/packages/client/ui-sidebar-documentpreview/tests/excel-body.client.spec.tsx index e23a2f19bd..95ee1f8e9f 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-body.client.spec.tsx +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-body.client.spec.tsx @@ -3,7 +3,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { en, zh } from '../src/client/excel/locales.ts' import type { ExcelBodyProps, LoadedExcelBodyProps } from '../src/client/excel/LazyExcelBody.tsx' @@ -14,7 +14,7 @@ import { ExcelBody } from '../src/client/excel/excel.tsx' import { LazyExcelBody } from '../src/client/excel/LazyExcelBody.tsx' import { LoadingIndicator } from '../src/client/LoadingIndicator.tsx' -const props = { content: { kind: 'bytes', data: new Uint8Array([1]) }, limits: Config({}).excel, t: makeTranslate(en), resourceAddress: 'dsh-resource://file/session/s1/book.xlsx' } as ExcelBodyProps +const props = { content: { kind: 'bytes', data: new Uint8Array([1]) }, limits: EXCEL_DEFAULTS, t: makeTranslate(en), resourceAddress: 'dsh-resource://file/session/s1/book.xlsx' } as ExcelBodyProps const loadedProps = { ...props, format: 'xlsx', loading: } satisfies LoadedExcelBodyProps const value = { sheets: [{ name: 'Budget', celldata: [] }], missingResults: 0, unsupportedFeatures: [] } const formulaValue = { sheets: [{ name: 'Budget', celldata: [{ r: 0, c: 0, v: { f: '=SUM(1,2)', m: '' } }] }], missingResults: 1, unsupportedFeatures: [] } diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-convert.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-convert.client.spec.ts index c4d7babea6..6fe3cc0f58 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-convert.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-convert.client.spec.ts @@ -3,10 +3,10 @@ import ExcelJS from 'exceljs' import { strToU8, unzipSync, zipSync } from 'fflate' import { describe, expect, it } from 'vitest' import { convertExcel } from '../src/client/excel/convert.ts' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { excelFixture, meetingMinutesFixture } from './excel-fixture.ts' -const limits = Config({}).excel +const limits = EXCEL_DEFAULTS describe('Excel conversion', () => { it('keeps values, dates, cached formulas, styles, merges, dimensions, visibility, and frozen headings', async () => { diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-drawings.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-drawings.client.spec.ts index 4e7bd510c6..01afd68769 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-drawings.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-drawings.client.spec.ts @@ -2,13 +2,13 @@ import ExcelJS from 'exceljs' import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate' import { expect, it } from 'vitest' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { convertExcel } from '../src/client/excel/convert.ts' import { XlsxPreviewArchive } from '../src/client/excel/xlsx-archive.ts' import { excelDrawingFixture } from './excel-drawing-fixture.ts' import { excelFixture, excelHtmlFixture } from './excel-fixture.ts' -const limits = Config({}).excel +const limits = EXCEL_DEFAULTS const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=' it.each(['', 'xdr', 'drawing'])('opens charts with DrawingML prefix %j while retaining every displayed cell', async (prefix) => { diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-formats.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-formats.client.spec.ts index b84c2b9ca2..acba6f4d18 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-formats.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-formats.client.spec.ts @@ -2,13 +2,13 @@ import { readFileSync } from 'node:fs' import { utils, write } from 'xlsx' import { expect, it } from 'vitest' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { convertExcel } from '../src/client/excel/convert.ts' import { excelFormat } from '../src/client/excel/format.ts' import { mapXlsWorkbook } from '../src/client/excel/xls.ts' import { legacyWorkbook, xlsFixture } from './xls-fixture.ts' -const limits = Config({}).excel +const limits = EXCEL_DEFAULTS const encode = (text: string) => new TextEncoder().encode(text) it.each(['xlsx', 'xls', 'csv', 'tsv'] as const)('resolves mixed-case %s paths and enforces byte limits', async (format) => { diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-opc.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-opc.client.spec.ts index 476bb4bac9..543df37d0f 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-opc.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-opc.client.spec.ts @@ -3,7 +3,7 @@ import { createRequire } from 'node:module' import ExcelJS from 'exceljs' import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate' import { describe, expect, it } from 'vitest' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { convertExcel } from '../src/client/excel/convert.ts' import { XlsxPreviewArchive } from '../src/client/excel/xlsx-archive.ts' import { excelOpcCases, excelOpcFixture } from './excel-opc-fixture.ts' @@ -11,7 +11,7 @@ import { excelFixture, excelHtmlFixture } from './excel-fixture.ts' const require = createRequire(import.meta.url) const browserExcel = require('exceljs/dist/exceljs.js') as typeof ExcelJS -const limits = Config({}).excel +const limits = EXCEL_DEFAULTS const relsPath = 'xl/worksheets/_rels/budget.xml.rels' describe.each([['Node', ExcelJS], ['browser bundle', browserExcel]] as const)('%s ExcelJS entry', (_name, parser) => { diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-opening.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-opening.client.spec.ts index e25c12e936..e21d1bf5d6 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-opening.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-opening.client.spec.ts @@ -4,7 +4,7 @@ import { createRequire } from 'node:module' import ExcelJS from 'exceljs' import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate' import { describe, expect, it } from 'vitest' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { convertExcel } from '../src/client/excel/convert.ts' import { XlsxPreviewArchive } from '../src/client/excel/xlsx-archive.ts' import { excelOpeningCases, excelOpeningFixture } from './excel-opening-fixture.ts' @@ -12,7 +12,7 @@ import { excelOpcFixture } from './excel-opc-fixture.ts' const require = createRequire(import.meta.url) const browserExcel = require('exceljs/dist/exceljs.js') as typeof ExcelJS -const limits = Config({}).excel +const limits = EXCEL_DEFAULTS describe.each([['Node', ExcelJS], ['browser bundle', browserExcel]] as const)('%s opening regressions', (_name, parser) => { it.each(excelOpeningCases)('opens %s with cells, styles, comments, Tables and hyperlinks', async (name) => { diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-parse.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-parse.client.spec.ts index 19c63bca7c..53a7b965a3 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-parse.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-parse.client.spec.ts @@ -1,9 +1,9 @@ /** Parser Worker allocation, cancellation, timeout, and message failures. */ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { parseExcel } from '../src/client/excel/parse.ts' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' -const limits = Config({}).excel +const limits = EXCEL_DEFAULTS const preview = { sheets: [{ name: 'Sheet', celldata: [] }], missingResults: 0, unsupportedFeatures: ['charts'] } let instance: ParserWorker const revokeUrl = vi.fn() diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-registration.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-registration.client.spec.ts index 9d8feb861b..10c8984437 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-registration.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-registration.client.spec.ts @@ -3,7 +3,7 @@ import { Context } from '@deepseek-ai/cordis' import { expect, it, vi } from 'vitest' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { binaryDocumentPath, DocumentPreviewRegistry } from '../src/client/document/registry.ts' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { apply } from '../src/client/excel/index.ts' import { LazyExcelBody } from '../src/client/excel/LazyExcelBody.tsx' import { en, ja, zh, es, fr, de, ru, pt } from '../src/client/excel/locales.ts' @@ -18,7 +18,7 @@ it('registers complete binary reads and removes the slot and locale on disposal' ctx.provide('documentPreviews', registry) ctx.provide('locale', { register: registerLocale, bind: () => makeTranslate(en) } as never) ctx.provide('slots', { inject: (_name: string, callback: () => () => void) => callback(), register } as never) - const limits = Config({}).excel + const limits = EXCEL_DEFAULTS const fiber = ctx.plugin({ apply: (scope) => { apply(scope, limits) } }) try { await fiber.await() diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-worker.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-worker.client.spec.ts index e6e6e743a0..5cca2776d2 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-worker.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-worker.client.spec.ts @@ -1,6 +1,6 @@ /** Worker entry translates parser failures into its private response protocol. */ import { afterEach, expect, it, vi } from 'vitest' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { excelFixture } from './excel-fixture.ts' afterEach(() => { vi.unstubAllGlobals(); vi.resetModules(); vi.doUnmock('../src/client/excel/convert.ts') }) @@ -12,7 +12,7 @@ it('returns parsed sheets and bounded failure categories', async () => { await import('../src/client/excel/worker.ts') const handle: (event: MessageEvent) => void = globalThis.onmessage! const message = (bytes: Uint8Array, maxCells = 250_000) => { - handle({ data: { bytes, format: 'xlsx', limits: { ...Config({}).excel, maxCells } } } as MessageEvent) + handle({ data: { bytes, format: 'xlsx', limits: { ...EXCEL_DEFAULTS, maxCells } } } as MessageEvent) } message(await excelFixture()) await vi.waitFor(() => { expect(post).toHaveBeenCalledWith(expect.objectContaining({ ok: true })) }) @@ -32,6 +32,6 @@ it('reports an unexpected parser failure as an invalid workbook', async () => { }) await import('../src/client/excel/worker.ts') const handle: (event: MessageEvent) => void = globalThis.onmessage! - handle({ data: { bytes: new Uint8Array(), format: 'xlsx', limits: Config({}).excel } } as MessageEvent) + handle({ data: { bytes: new Uint8Array(), format: 'xlsx', limits: EXCEL_DEFAULTS } } as MessageEvent) await vi.waitFor(() => { expect(post).toHaveBeenCalledWith({ ok: false, code: 'invalid' }) }) }) diff --git a/packages/client/ui-sidebar-documentpreview/tests/excel-xml.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/excel-xml.client.spec.ts index fb3c5e3c54..0c2b91ec8e 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/excel-xml.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/excel-xml.client.spec.ts @@ -3,14 +3,14 @@ import { createRequire } from 'node:module' import ExcelJS from 'exceljs' import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate' import { describe, expect, it } from 'vitest' -import { Config } from '../src/config.ts' +import { EXCEL_DEFAULTS } from '../src/defaults.ts' import { convertExcel } from '../src/client/excel/convert.ts' import { XlsxPreviewArchive } from '../src/client/excel/xlsx-archive.ts' import { excelXmlCases, excelXmlFixture } from './excel-xml-fixture.ts' const require = createRequire(import.meta.url) const browserExcel = require('exceljs/dist/exceljs.js') as typeof ExcelJS -const limits = Config({}).excel +const limits = EXCEL_DEFAULTS describe.each([['Node', ExcelJS], ['browser bundle', browserExcel]] as const)('%s XML reader', (_name, parser) => { it.each(excelXmlCases)('preserves comments and Tables in %s', async (name) => { diff --git a/packages/client/ui-sidebar-documentpreview/tests/office-registration.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/office-registration.client.spec.ts index 3c3c71889f..13539df6dc 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/office-registration.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/office-registration.client.spec.ts @@ -9,7 +9,8 @@ import { makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime import { DocumentPreviewRegistry } from '../src/client/document/registry.ts' import { apply } from '../src/client/office/index.ts' import { officeFace } from '../src/client/office/face.ts' -import { Config } from '../src/config.ts' +import { OFFICE_DEFAULTS } from '../src/defaults.ts' +import type { OfficeLimits } from '../src/types.ts' import { OfficeBody, type OfficeBodyInjected } from '../src/client/office/OfficeBody.tsx' import type { OfficeStore } from '../src/client/office/store.ts' import type { TabId } from '@deepseek-ai/dsh-client-ui-dockkit' @@ -53,7 +54,7 @@ it('retains Office view state across remounts and releases it on tab close or pl } finally { closed.abort(); retained.abort(); await h.close() } }) -async function harness(config: Partial = {}, missing?: 'remote' | 'render' | 'files') { +async function harness(config: Partial = {}, missing?: 'remote' | 'render' | 'files') { const ctx = new Context() const registry = new DocumentPreviewRegistry() const removeLocale = vi.fn() @@ -74,7 +75,7 @@ async function harness(config: Partial = {}, missing?: 'remote if (missing !== 'render') ctx.provide('remote.officeKit', { render, generation: rendererGeneration } as never) } const fiber = ctx.plugin({ apply: (scope: Context) => { - apply(scope, Config({ office: config }).office) + apply(scope, { ...OFFICE_DEFAULTS, ...config }) } }) await fiber.await() const entry = recorded.find(entry => entry.component === OfficeBody)!.options 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-documentpreview/tsconfig.client.json b/packages/client/ui-sidebar-documentpreview/tsconfig.client.json index 1656958ec0..b18d260d29 100644 --- a/packages/client/ui-sidebar-documentpreview/tsconfig.client.json +++ b/packages/client/ui-sidebar-documentpreview/tsconfig.client.json @@ -7,10 +7,14 @@ }, "include": [ "src/client", - "src/config.ts", + "src/defaults.ts", + "src/types.ts", "src/css-modules.d.ts" ], "references": [ + { + "path": "../config" + }, { "path": "../../api/gateway/tsconfig.client.json" }, @@ -62,9 +66,6 @@ { "path": "../connection/tsconfig.client.json" }, - { - "path": "../../../vendor/schemastery" - }, { "path": "../../document/office-kit" }, diff --git a/packages/client/ui-sidebar-documentpreview/tsconfig.host.json b/packages/client/ui-sidebar-documentpreview/tsconfig.host.json index b47a7b37ef..44aec3b3f3 100644 --- a/packages/client/ui-sidebar-documentpreview/tsconfig.host.json +++ b/packages/client/ui-sidebar-documentpreview/tsconfig.host.json @@ -7,7 +7,8 @@ }, "files": [ "src/index.ts", - "src/config.ts" + "src/defaults.ts", + "src/types.ts" ], "references": [ { @@ -15,9 +16,6 @@ }, { "path": "../../../vendor/schemastery" - }, - { - "path": "../../host/webserver" } ] } diff --git a/packages/client/ui-sidebar-files/README.i18n.yaml b/packages/client/ui-sidebar-files/README.i18n.yaml index dd3d34d879..468a6603e0 100644 --- a/packages/client/ui-sidebar-files/README.i18n.yaml +++ b/packages/client/ui-sidebar-files/README.i18n.yaml @@ -15,17 +15,17 @@ 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 /deepseek-ai-dsh-client-ui-sidebar-files/the-tree: - en: 3d71e50801761213 - zh: e4e9ab19dd22288d + en: 8f85cc7d1f4fec77 + zh: 67f19159054f0888 /deepseek-ai-dsh-client-ui-sidebar-files/search: - en: 275bc2aa20907881 - zh: 4dac902558cb29f5 + en: fe964bf291d46508 + zh: 019e91b2413bca95 /deepseek-ai-dsh-client-ui-sidebar-files/reusable-tree-factory: en: 76e4d93d65d3c50e zh: b611bba888f86b85 @@ -36,8 +36,8 @@ en: 39debadcc6cefd24 zh: cc212c8377851a91 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work: - en: f28a32e47e684f5c - zh: e5e38014048ebe59 + en: 14bd8ccb7c54ed17 + zh: cc2c3181d7859251 /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..3d618398aa 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). @@ -56,7 +56,7 @@ The tree marks the row of the current file with `aria-current`. While the tree i ## The tree -The root is the session's working directory, read from `useSessions().byId[sessionId].cwd`. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Entries whose name starts with `.` are left out until the reader [shows hidden entries](#search). +The root is the session's working directory, selected with `selectSessionDirectory` from the list snapshot: the projected `workingDirectory`, else the header directory. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Entries whose name starts with `.` are left out until the reader [shows hidden entries](#search). | Entry type | Row | |---|---| @@ -83,7 +83,7 @@ The eye starts closed. Closed, the tree leaves out every entry whose name starts The settings panel floats over the navigator below the search bar and lists the excluded files and directories, newest first: each rule has a checkbox that turns it on or off, its path, and a remove control. A rule without `/` names every file or directory of that name at any depth, and a rule with `/` names one workspace-relative path; an excluded directory takes its contents with it. The field that adds a rule stays above the list, which alone scrolls; Enter adds the typed name or path at the top, or names why it is refused below the field. The default list holds version-control, package-manager, and build output directories (`.git`, `.hg`, `.next`, `.pnpm-store`, `.svn`, `.turbo`, `.yarn`, `build`, `coverage`, `dist`, `node_modules`), then the metadata macOS and Windows write (`.DS_Store`, `.Spotlight-V100`, `.Trashes`, `.fseventsd`, `Thumbs.db`, `desktop.ini`, `$RECYCLE.BIN`, `System Volume Information`). The header ends with the restore control, shown while the list differs from the default list in any way, order included, which replaces the list with the default list, and the close control. Above the list, the "Respect ignore files (.gitignore, etc.)" checkbox, checked by default, leaves out entries that ripgrep's ignore rules ignore: `.gitignore` files inside a git repository, including those above the workspace root, `.ignore` files, and the global Git excludes; outside a git repository `.gitignore` does not apply; like the eye, it is saved as soon as it changes. Rule edits stay in the panel until it closes, by the magnifier, by its close control, by Escape, or by keyboard focus leaving it, as a press outside it does; closing saves them. Exclusion rules narrow only the search, never the tree. -The rules, the eye, and the `.gitignore` choice are kept per workspace root, the Session's working directory with trailing separators removed except the one a filesystem root needs, so every Session and pane rooted there shares them and other roots do not. They live in browser storage under `dsh.sidebar-files.workspace-search.v1`, one entry per root the reader changed, holding only the fields that differ from the defaults, so a later build's default list reaches a root whose rules the reader left alone; a root changed back to the defaults loses its entry, and a missing or malformed field reads as its default. A change while a pane's search text is not blank searches again at once. +The rules, the eye, and the `.gitignore` choice are kept per workspace root, with trailing separators removed except the one a filesystem root needs, so every Session and pane rooted there shares them and other roots do not. They live in browser storage under `dsh.sidebar-files.workspace-search.v1`, one entry per root the reader changed, holding only the fields that differ from the defaults, so a later build's default list reaches a root whose rules the reader left alone; a root changed back to the defaults loses its entry, and a missing or malformed field reads as its default. A change while a pane's search text is not blank searches again at once, and a Session that enters another checkout while its text is not blank searches that checkout with its own preferences. ↓ in the search field moves keyboard focus to the first row, ↑ and ↓ move between rows of the tree or the results, and ↑ on the first row returns to the field while the bar is shown; Enter on a row acts as a click does. Escape closes the settings panel first, then clears the search text even while the bar is collapsed, and only then reaches the overlaying navigator's close; clearing a hidden query keeps focus in the tree. On an existing docked files page or beside a docked preview, `workspace.files` shows the search field and gives it keyboard focus; other targets follow the [command's page-opening behavior](#what-it-registers). @@ -116,7 +116,7 @@ None; directory listings and searches travel over the Remote and assemble no mod - **A query with `/` highlights nothing across names.** Each name is highlighted on its own, so a query that spans a `/` marks no row. - **Names with glob characters cannot be excluded.** A rule may not contain `* ? [ ] { } !`, so a literal path such as Next.js `app/[slug]` cannot be named. - **Preferences do not follow other browser tabs.** Each tab reads browser storage once when the plugin loads and writes the preferences of every root back as one value, so a tab that writes overwrites the changes other tabs made since it loaded to any workspace's preferences, until it reloads. -- **One root.** The tree is rooted at the session's working directory; there is no way to browse above it, and the Host refuses paths outside the workspace root anyway. +- **One root.** The tree is rooted at the session's workspace root; there is no way to browse above it, and the Host refuses paths outside the workspace root anyway. ### Dev Note @@ -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..8cdc21c924 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。 @@ -56,7 +56,7 @@ kind: "package-reference" ## 树 -根是会话的工作目录,读自 `useSessions().byId[sessionId].cwd`。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。名称以 `.` 开头的条目,在读者[显示隐藏条目](#search)之前不显示。 +根是会话的工作目录,用 `selectSessionDirectory` 从列表快照选出:投影的 `workingDirectory`,否则为 header 目录。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。名称以 `.` 开头的条目,在读者[显示隐藏条目](#search)之前不显示。 | 条目类型 | 行 | |---|---| @@ -83,7 +83,7 @@ kind: "package-reference" 设置面板浮在导航栏中搜索栏的下方,列出排除的文件和目录,最新的在最前:每条规则有开关它的复选框、路径和删除按钮。不含 `/` 的规则指任意深度上所有同名的文件或目录,含 `/` 的规则指一个相对于工作区的路径;排除一个目录时其内容也一并排除。添加规则的输入框固定在列表上方,只有列表本身滚动;Enter 把输入的名称或路径添加到最上方,或在输入框下方说明拒绝的原因。默认列表先是版本控制、包管理器和构建输出目录(`.git`、`.hg`、`.next`、`.pnpm-store`、`.svn`、`.turbo`、`.yarn`、`build`、`coverage`、`dist`、`node_modules`),然后是 macOS 和 Windows 写入的元数据(`.DS_Store`、`.Spotlight-V100`、`.Trashes`、`.fseventsd`、`Thumbs.db`、`desktop.ini`、`$RECYCLE.BIN`、`System Volume Information`)。标题行末端是还原按钮和关闭按钮;列表与默认列表有任何不同(包括顺序不同)时显示还原按钮,点击后把列表重置为默认列表。列表上方的「尊重忽略文件(.gitignore 等)」(Respect ignore files (.gitignore, etc.))复选框默认勾选,此时略过 ripgrep 忽略规则忽略的条目:git 仓库内的 `.gitignore`(包括工作区根以上的)、`.ignore` 文件和全局 Git excludes;不在 git 仓库内时 `.gitignore` 不生效;它和眼睛一样,一改变就保存。规则的编辑留在面板内,直到面板通过放大镜、关闭按钮、Escape 或键盘焦点离开它(在面板外按下也是如此)而关闭;关闭即保存。排除规则只缩小搜索范围,从不影响目录树。 -规则、眼睛与 `.gitignore` 选择按工作区根保存,即去掉尾随分隔符的 Session 工作目录(文件系统根需要的那一个除外),因此根在同一目录的每个 Session 与分栏共享它们,其他根互不影响。它们保存在浏览器存储的 `dsh.sidebar-files.workspace-search.v1` 下,读者改过的每个根各占一项,只保存与默认值不同的字段,因此读者没改过规则的根能用上后续版本的默认列表;改回默认值的根删除其条目,缺失或格式不对的字段按默认值读取。分栏的搜索文字非空时发生的变化会立即重新搜索。 +规则、眼睛与 `.gitignore` 选择按工作区根保存,即去掉尾随分隔符的工作区根(文件系统根需要的那一个除外),因此根在同一目录的每个 Session 与分栏共享它们,其他根互不影响。它们保存在浏览器存储的 `dsh.sidebar-files.workspace-search.v1` 下,读者改过的每个根各占一项,只保存与默认值不同的字段,因此读者没改过规则的根能用上后续版本的默认列表;改回默认值的根删除其条目,缺失或格式不对的字段按默认值读取。分栏的搜索文字非空时发生的变化会立即重新搜索;Session 在搜索文字非空时进入另一个检出目录,会用该检出目录自己的偏好在那里重新搜索。 在搜索框中按 ↓ 把键盘焦点移到第一行,↑ 与 ↓ 在目录树或搜索结果的行之间移动,搜索栏显示时在第一行按 ↑ 回到搜索框;在行上按 Enter 与单击效果相同。Escape 先关闭设置面板,再清空搜索文字(搜索栏收起时也一样),之后才交给覆盖式导航栏的关闭行为;清空隐藏的查询时,焦点留在目录树内。在已有停靠文件页或停靠预览旁,`workspace.files` 显示搜索框并把键盘焦点移给它;其他位置遵循[命令的文件页打开行为](#what-it-registers)。 @@ -116,7 +116,7 @@ kind: "package-reference" - **含 `/` 的查询不会跨名称高亮。**每个名称单独高亮,因此跨越 `/` 的查询不会在任何行上标出。 - **含通配符的名称无法排除。**规则不能包含 `* ? [ ] { } !`,因此无法写出 Next.js `app/[slug]` 这类字面路径。 - **偏好不会同步到其他浏览器标签页。**每个标签页只在插件加载时读取一次浏览器存储,并把所有根的偏好作为一个整体写回,因此一个标签页写入时,会覆盖其他标签页在它加载之后对任何工作区偏好所做的修改,直到它重新加载。 -- **只有一个根。**树以会话工作目录为根;没有办法浏览到它之上,而 Host 本来也拒绝工作区根之外的路径。 +- **只有一个根。**树以会话工作区根为根;没有办法浏览到它之上,而 Host 本来也拒绝工作区根之外的路径。 ### 开发备注 @@ -124,6 +124,8 @@ kind: "package-reference"
      维护者工作上下文——点击展开 +每层子级图标框承接父级文字列;缩进包含父级图标框及图文间距,并保留图标内部留白。 + 无。 页面刷新快捷键在文件页上、目录树显示期间通过常规目录读取器刷新其树,在预览中重新载入预览。文件页的重新读取控件在悬停和键盘聚焦时显示有效绑定。 diff --git a/packages/client/ui-sidebar-files/package.json b/packages/client/ui-sidebar-files/package.json index 28a0d8fe27..9ce881822d 100644 --- a/packages/client/ui-sidebar-files/package.json +++ b/packages/client/ui-sidebar-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-files", "description": "The workspace files page and one workspace directory tree per pane beside docked and floating file previews, listed lazily over the workspaceFiles Remote namespace", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -50,10 +50,13 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-api-workspace-files": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-dockkit": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", @@ -64,11 +67,9 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@testing-library/react": "^16.3.3", - "react": "^18.2.0", "clsx": "^2.0.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx index dac8bb7f88..151699f78b 100644 --- a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx +++ b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx @@ -7,6 +7,7 @@ * follows `PUSH_FROM`, `FILL_BELOW`, and `FULLSCREEN_QUERY`; the package * README describes its behavior, search included. */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { CSSProperties, KeyboardEvent, ReactNode } from 'react' import clsx from 'clsx' @@ -173,9 +174,8 @@ export function FileNavigator({ const { tab, panel } = useTabInfo() const { getTriggerProps } = useContextMenu() const paneId = panel.id - // A Session's working directory comes from its header and never changes once - // known, so every search result the pane's store holds is rooted at it. - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + // The tree is rooted at the directory the Session works in; the face searches again when it changes. + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) const state = useStore(store => store.byPane[paneId]) const rowWidth = useRowWidth(paneId) const canOpen = useCanOpen(check => check) 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..962d3e319e 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx @@ -7,6 +7,7 @@ * it is and opens the file where the right Sidebar places it by default * (`FileNavigator`). */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback, useEffect } from 'react' import type { ReactNode } from 'react' import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' @@ -51,7 +52,7 @@ export function FilesBody(props: FilesBodyProps): ReactNode { () => tab.actions.bindCommands({ refresh: () => { refresh(panel.id) } }), [tab.actions, panel.id, refresh], ) - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) // The setting belongs to a listed tree, so there is nothing to set before one. const autoRefresh = useStore((store) => { const tree = store.byPane[panel.id]?.tree @@ -111,7 +112,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-files/src/client/NavigatorToggle.tsx b/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx index f30da3999d..a897b35074 100644 --- a/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx +++ b/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx @@ -5,6 +5,7 @@ * the pane reads, and registers itself with the face, which hands it the * keyboard when Escape closes the navigator. */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback } from 'react' import type { ReactNode } from 'react' import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' @@ -42,7 +43,7 @@ export function NavigatorToggle( { useTabInfo, sessionId, useSessions, useStore, actions, toggleDrawn, t }: FactoryComponentPropsOf<'sidebar.files.navigator.toggle'>, ): ReactNode { const { panel } = useTabInfo() - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) const open = useStore(store => store.byPane[panel.id]?.open) === true // Stable, so the control registers once per drawing rather than on every render. const toggleRef = useCallback((button: HTMLElement | null) => { toggleDrawn(panel.id, button) }, [toggleDrawn, panel.id]) diff --git a/packages/client/ui-sidebar-files/src/client/face.ts b/packages/client/ui-sidebar-files/src/client/face.ts index 3bdccb9337..0ca2b20206 100644 --- a/packages/client/ui-sidebar-files/src/client/face.ts +++ b/packages/client/ui-sidebar-files/src/client/face.ts @@ -194,8 +194,8 @@ export interface FilesInjected { * such text, a change to those preferences searches again. Blank text ends * the search, aborting a running one, and the pane draws its tree again. * @param paneId - the pane being drawn. - * @param cwd - the Session's working directory, the search's root; fixed for the Session once known, so a - * result always shares the pane's tree root. + * @param cwd - the Session's working directory, which the search and its result tree are rooted at; a + * `hold` with another directory searches the held text again there. * @param query - the text as typed. */ readonly setQuery: (paneId: PaneId, cwd: string, query: string) => void @@ -629,6 +629,11 @@ export function filesFace( pane.root = node node.open() if (kept !== undefined) batch(() => { relisting(paneId, kept.expanded) }) + // Text held while the Session entered another checkout searches that checkout with its preferences. + if (pane.searchQuery !== '' && pane.following?.cwd !== root) { + follow(paneId, pane, root) + runSearch(paneId, pane, root) + } step(paneId, pane) } // A navigation belongs to its target tab, not the tree that initiated it. diff --git a/packages/client/ui-sidebar-files/tests/mount.client.tsx b/packages/client/ui-sidebar-files/tests/mount.client.tsx index 32a4cc14aa..4f1991bac3 100644 --- a/packages/client/ui-sidebar-files/tests/mount.client.tsx +++ b/packages/client/ui-sidebar-files/tests/mount.client.tsx @@ -140,8 +140,12 @@ function harness(placement: Placement, controller: AbortController, book: Worksp openTab: vi.fn(), close: vi.fn(), } - const sessionsAt = (cwd: string | null): SessionListState => - ({ byId: cwd === null ? {} : { [SESSION]: { cwd } } } as unknown as SessionListState) + const sessionsAt = (cwd: string | null): SessionListState => ({ + ids: cwd === null ? [] : [SESSION], + byId: cwd === null ? {} : { [SESSION]: { id: SESSION, displayTitle: 'files', running: false, retainedBy: {}, blank: false, updatedAt: 0, cwd } }, + phase: 'ready', + projectionsBySession: {}, + }) const useTabInfo = (): SidebarRightTabInfo => ({ sidebar: { expanded: true, fullscreen: false }, panel: { id: PANE, isFloating: placement.isFloating ?? false }, diff --git a/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts index 2436eac12e..ca99a0de81 100644 --- a/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts @@ -194,6 +194,31 @@ describe('the face\'s search', () => { expect(two.search).toHaveBeenCalledTimes(4) }) + it('searches the checkout a held query\'s pane moves to, with that checkout\'s preferences', async () => { + const book = memoryBook() + const h = session('s-1', book) + h.face.setSearchPreferences('/work/other', { showHidden: true }) + const release = h.face.hold(PANE, ROOT) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + expect(h.search).toHaveBeenCalledOnce() + expect(h.result()).toMatchObject({ tree: { root: ROOT } }) + // The Session enters another checkout: the tree restarts there, and so does the held search. + const moved = h.face.hold(PANE, '/work/other') + release() + expect(h.search).toHaveBeenLastCalledWith('s-1', expect.objectContaining({ query: 'a', includeHidden: true }), expect.any(AbortSignal)) + await searchesSettled() + expect(h.result()).toMatchObject({ tree: { root: '/work/other' }, hiddenLeftOut: false }) + // Holding the same root again searches nothing new; the new root's preferences are followed now. + h.face.hold(PANE, '/work/other')() + expect(h.search).toHaveBeenCalledTimes(2) + h.face.setSearchPreferences(ROOT, { showHidden: true }) + expect(h.search).toHaveBeenCalledTimes(2) + h.face.setSearchPreferences('/work/other', { respectGitignore: false }) + expect(h.search).toHaveBeenCalledTimes(3) + moved() + }) + it('does not search again when the listed levels change under shown results', async () => { const h = session('s-1', memoryBook()) h.instance.actions.start(PANE, ROOT) diff --git a/packages/client/ui-sidebar-files/tsconfig.json b/packages/client/ui-sidebar-files/tsconfig.json index 47b76f17ba..716d7b6823 100644 --- a/packages/client/ui-sidebar-files/tsconfig.json +++ b/packages/client/ui-sidebar-files/tsconfig.json @@ -49,6 +49,9 @@ }, { "path": "../ui-context-menu" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" } ] } 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/package.json b/packages/client/ui-sidebar-right/package.json index 0de2aa4a47..0512e97ce7 100644 --- a/packages/client/ui-sidebar-right/package.json +++ b/packages/client/ui-sidebar-right/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-right", "description": "Right Sidebar: the docking surface's session-bound state, its panel and header expand control, and the navigation service over it", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-right/src/client/session-view.ts b/packages/client/ui-sidebar-right/src/client/session-view.ts index f36bb3f977..f2bcb5e7b5 100644 --- a/packages/client/ui-sidebar-right/src/client/session-view.ts +++ b/packages/client/ui-sidebar-right/src/client/session-view.ts @@ -30,7 +30,7 @@ export class SidebarSessionView { private readonly onDispose: (view: SidebarSessionView) => void, private readonly onTabRelease: (view: SidebarSessionView) => void, ) { - this.reference = sessions.retain(sessionId, { source: 'sidebarView' }) + this.reference = sessions.retain(sessionId, { source: 'sidebarView', facets: { conversation: true } }) void this.reference.ready.catch((error: unknown) => { console.error('Sidebar Session opening failed:', error) }) } 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..cecf30aa6f 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' }, @@ -89,7 +90,7 @@ async function mountSeat(viewportWidth = 1440, canShow = true, entryCount = 0, o 'conversation.session.header.corner': { kind: 'single', scope: 'session' }, }) await runtime.sessions.add({ id: SESSION }) - let reference = runtime.sessions.retainFor(runtime.ctx, SESSION, { source: 'mainView' }) + let reference = runtime.sessions.retainFor(runtime.ctx, SESSION, { source: 'mainView', facets: { conversation: true } }) const feature = await runtime.mount({ inject: [...inject], apply }) // The frame mounts the Conversation column before the right column, so a // Conversation component's mount effect runs before the seat's. The opener @@ -160,7 +161,7 @@ async function mountSeat(viewportWidth = 1440, canShow = true, entryCount = 0, o return controller.active()! } const selectSession = (id: SessionId): void => { - const next = runtime.sessions.retainFor(runtime.ctx, id, { source: 'mainView' }) + const next = runtime.sessions.retainFor(runtime.ctx, id, { source: 'mainView', facets: { conversation: true } }) reference.release() reference = next } 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/package.json b/packages/client/ui-sidebar-terminal/package.json index 8fbb67c504..8e21991f64 100644 --- a/packages/client/ui-sidebar-terminal/package.json +++ b/packages/client/ui-sidebar-terminal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-terminal", "description": "Interactive shell tabs for the right Sidebar", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, 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 5847e07229..0713c88064 100644 --- a/packages/client/ui-sidebar/README.i18n.yaml +++ b/packages/client/ui-sidebar/README.i18n.yaml @@ -21,23 +21,23 @@ en: 6bc49e22f0f73f07 zh: 10883997ccb7d145 /deepseek-ai-dsh-client-ui-sidebar/use-this-package/global-panel-entries: - en: 8a23eab217042cc6 - zh: 2d760de4c83f996c + en: e7cfc9a3d175045d + zh: 2bf0d5d6d0c64de8 /deepseek-ai-dsh-client-ui-sidebar/use-this-package/collapse-behavior: - en: 10381cbac96069a3 - zh: c5849741a0be2f00 + en: 61d563b0f82ff658 + zh: f27504350dd14d4c /deepseek-ai-dsh-client-ui-sidebar/use-this-package/macos-desktop: 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: 76a542d822e94fc9 - zh: da25857ead58df5c + 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 43cfe45193..0328dd05fa 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -39,7 +39,9 @@ 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`. While the root-scoped `sidebar.panellist.actions` list has registrations, a **More** button styled as a panel row follows the rows inside the navigation landmark; the collapsed rail shows its label as a tooltip. It opens a menu whose rows are that list's registrations. Each receives `entries` (customizable panels in registration order with `id`, `label`, `pinned`, and `active`; Plugins is never listed), `onOpen(id)`, which selects the panel, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The sidebar keeps one in-memory list of unpinned panel ids shared by every Session; Plugins always shows. While More shows, expanded rows other than Plugins show an unpin action on hover or keyboard focus; devices without hover show it continuously. Its resting color matches the Session pin marker, and its tooltip says “Unpin from left sidebar”. Both sidebar and More entries follow the same registration order rather than pin timing. The default More menu lists only unpinned panels before plugin browsing and creation; opening a panel does not pin it, while its separate pin icon returns the row to the sidebar and dismisses the menu. Choices reset when the plugin reloads and legacy localStorage values are ignored. Unpinning hides only the row, and only while More shows; without `sidebar.panellist.actions` registrations every registered row shows again. The main panel, its registration, and the current selection stay unchanged. Unregistered panel ids remain in the in-memory list until the plugin reloads. @@ -49,6 +51,8 @@ The sidebar and conversation-header toggles show the effective shortcut from the The top expand button hosts the optional, non-interactive `sidebar.toggle.badge` slot while collapsed. Its occupant supplies status and tooltip content without adding another action or changing the button's navigation behavior. +The root-scoped `sidebar.session.action` HOC layer wraps the New Session row's content: an occupant receives the row's Tooltip and button as `children` and returns them, possibly wrapped, together with its own controls, so it decorates the row without adding a wrapper element. It receives only `wide`, and an occupant that adds nothing must return `children`. Expanded, the controls share the New Session row and the button takes the remaining width; in the rail they stack below its icon. The row renders only while New Session renders, and each occupant still checks its own access. + Expanded content follows the frame's column width, including its transitions. During a live collapse, the content fades out at its frozen expanded width, the upper controls share one fade and leftward translation into the 56px rail, and the layout's column slide ends the motion. A page that starts collapsed renders the rail statically, and reduced-motion mode disables both transitions. The bottom-pinned `sidebar.settings` control shares the fade timing but has no horizontal translation. On Windows Electron, `html[data-windows-titlebar]` fixes the sidebar toggle in the caption's top-left corner in both states, aligned with New Session's left edge only when expanded. The expanded brand sits below the caption and above New Session, with 8px of extra space above that button. Collapsing hides the brand and sidebar content and places New Session between the sidebar toggle and the Desktop-owned menus. The sidebar sets the root `--dsh-windows-menu-start` to 84px when collapsed; the Desktop preload uses it to position its menu after New Session and defaults to 48px when expanded. Caption icon buttons use centered 16px glyphs in 28px controls with the compact control radius and exclude themselves from the window drag region. The sidebar toggle and New Session bubbles open below the caption, where the Desktop-owned menu text cannot cover them; an occupying `sidebar.toggle.badge` chooses its own bubble side. @@ -59,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 @@ -78,14 +82,16 @@ On Desktop, the official navigation controls report `sidebar_menu_click` with `m
      Implementation internals — click to expand -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; panel rows and the More menu render a panel's registered icon through that factory. 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. +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 2f0c507119..e68792963e 100644 --- a/packages/client/ui-sidebar/README.zh.md +++ b/packages/client/ui-sidebar/README.zh.md @@ -39,7 +39,9 @@ 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`。 root 作用域的 `sidebar.panellist.actions` list 有注册项时,导航区域的面板行之后显示面板行样式的**更多**按钮;收起的窄栏以提示框显示其名称。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的可自定义面板,含 `id`、`label`、`pinned` 与 `active`;不含插件管理)、选中面板的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。侧边栏在内存中保存所有会话共用的已收起面板 id 列表;插件管理入口始终显示。更多按钮显示时,展开态中除插件管理外的面板行在悬停或键盘聚焦时显示取消固定操作;不支持悬停的设备始终显示该操作。图标默认颜色与会话置顶标记一致,提示为“从左侧栏取消固定”。侧栏和更多菜单入口遵循相同的注册排序,不按固定时间重排。默认更多菜单在插件浏览和创建之前仅列出未固定的面板;打开面板不会将其固定,独立的固定图标则将该行放回侧边栏并关闭菜单。插件重新加载时选择重置,不读取旧 localStorage 值。收起只隐藏导航行,且仅在更多按钮显示时生效;`sidebar.panellist.actions` 没有注册项时,所有已注册的面板行重新显示。主面板、其注册和当前选中态不变。未注册面板的 id 保留在内存列表中,直到插件重新加载。 @@ -49,6 +51,8 @@ root 作用域的 `sidebar.panellist.actions` list 有注册项时,导航区 侧栏收起时,顶部展开按钮承载可选、不可交互的 `sidebar.toggle.badge` slot。占用方提供状态和提示内容,不增加操作,也不改变按钮的导航行为。 +root 作用域的 `sidebar.session.action` 是包裹新建会话行内容的 HOC 层:占用方以 `children` 收到该行的 Tooltip 与按钮,再把它们(可再包裹)连同自己的控件一起返回,因此无需新增包裹元素即可装饰该行。占用方只收到 `wide`;不添加任何内容时必须原样返回 `children`。展开态下这些控件与新建会话按钮同处一行,按钮占据剩余宽度;收起态下它们纵向排在新建会话图标下方。该行只在新建会话按钮渲染时渲染,各占用方仍自行检查访问权限。 + 展开内容跟随框架的列宽及其过渡。实时收起时,内容固定在展开宽度淡出,上方控件共用同一段透明度渐变,并向左平移进入 56px 轨道,由布局的栏滑动结束整段动画。页面初始即为收起状态时会静态渲染轨道;减少动态效果模式会禁用两段过渡。固定在底部的 `sidebar.settings` 控件共用相同的透明度渐变时序,但不发生横向位移。 在 Windows Electron 中,`html[data-windows-titlebar]` 将两种状态下的侧栏开关固定在顶栏左上角,仅在展开态与新建会话按钮左边缘对齐。展开态品牌位于顶栏下方、新建会话按钮上方,按钮上方额外留出 8px。收起后,品牌和侧栏内容隐藏,新建会话按钮排在侧栏开关与 Desktop 菜单之间。侧栏在收起态将根元素的 `--dsh-windows-menu-start` 设为 84px;Desktop preload 使用它将菜单放在新建会话之后,展开态默认为 48px。顶栏图标按钮采用紧凑控件圆角的 28px 控件,图标为居中 16px,并从窗口拖拽区域中排除。侧栏开关与新建会话的悬停提示在顶栏下方展开,Desktop 菜单文字不会盖住它们;占用 `sidebar.toggle.badge` 的控件自行决定气泡展开方向。 @@ -59,7 +63,7 @@ root 作用域的 `sidebar.panellist.actions` list 有注册项时,导航区 ### 滚动条 -栏内的滚动条是一种指针可供性:只要指针不在栏内,外壳就把滚动条间接层重新绑定为 `transparent`;指针离开后滑块再保留 2 秒,因此没人指向的列表不会带着滚动条。避免行位移的空间预留属于滚动区域本身(ui-workspace),所以显示滑块不会引起重排。 +栏内的滚动条是一种指针可供性:只要指针不在栏内,外壳就把滚动条间接层重新绑定为 `transparent`,因此没人指向的列表不会带着滚动条。指针离开后,滑块先保留 500ms,再在 200ms 内线性淡出;淡出结束前指针返回会立即重新显示滑块,减弱动态效果时保留延迟但不淡出。是否在栏内按栏的矩形范围判定,对每次到达该栏的指针移动都会判定,因此指针位于固定定位的设置面板或栏外的 portal 菜单上时,同样算作在栏外。避免行位移的空间预留属于滚动区域本身(ui-workspace),所以显示滑块不会引起重排。 ### 点击埋点 @@ -78,14 +82,16 @@ root 作用域的 `sidebar.panellist.actions` list 有注册项时,导航区
      实现细节——点击展开 -外壳是纯组合:`SidebarRootComponentProps` 组合布局 owner share、全局 `useSessions` 与 `useWorkspaces` 钩子、已声明的品牌、`sidebar.workspaces` 与 `sidebar.settings` 子 slot,以及注入的导航回调。侧边栏声明 `sidebar.panel.icon` Component Factory,由它拥有 `sidebar.panellist` list;面板行和更多菜单都通过该 factory 渲染面板注册的图标。面板元数据由列表注册和 locale 变化派生;选中态属于布局存储。注入的 `trackEntryClick(attributes)` 转发到 `ctx.get('productAnalytics')?.track('sidebar_menu_click', attributes)`;`selectPanel` 只负责选中,因此由各控件自行提供入口与位置。 +外壳是纯组合:`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/package.json b/packages/client/ui-sidebar/package.json index 536d17c8e6..208fcf4109 100644 --- a/packages/client/ui-sidebar/package.json +++ b/packages/client/ui-sidebar/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar", "description": "Sidebar plugin: session multi-level tree, search, grouping, state dots", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar/src/client/PanelIcon.tsx b/packages/client/ui-sidebar/src/client/PanelIcon.tsx index ba3ed5fc04..85b2fa9262 100644 --- a/packages/client/ui-sidebar/src/client/PanelIcon.tsx +++ b/packages/client/ui-sidebar/src/client/PanelIcon.tsx @@ -10,3 +10,12 @@ import type {} from './contract/slots.ts' export function PanelIcon({ id, size, active, renderSlot }: FactoryComponentPropsOf<'sidebar.panel.icon'>) { return renderSlot('sidebar.panellist', { size, active }, { only: id }) } + +/** + * Render the trailing content registered for one panel in its navigation row. + * @param props - Panel identity, row state, and the authorized child renderer. + * @returns The matching trailing content, or nothing without a registration. + */ +export function PanelTrailing({ id, wide, active, renderSlot }: FactoryComponentPropsOf<'sidebar.panel.trailing'>) { + return renderSlot('sidebar.panellist.trailing', { wide, active }, { only: id }) +} diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css index a9de41653f..023dd4a0c6 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css @@ -81,7 +81,7 @@ padding: 0; } -:global([data-windows-titlebar]) .root:not(.collapsed) .newSession { +:global([data-windows-titlebar]) .root:not(.collapsed) .newSessionRow { margin-top: 6px; } @@ -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 @@ -156,9 +165,14 @@ rail right edge over the remaining 150ms of the AppFrame track transition. The bottom-pinned settings seat shares their opacity timeline but stays horizontally fixed. Only a live collapse gets .railIn; a cold collapsed - render stays static. */ + render stays static. + The New Session row renders its content through the `sidebar.session.action` + HOC slot, whose `display: contents` outlet anchor sits between the row and + its content. The shell's New-session button and the occupant's own controls + are that anchor's children, so the fade targets them through the anchor; the + boxless anchor itself cannot carry an animation. */ .railIn .iconButton, -.railIn .newSession, +.railIn .newSessionRow > :global([data-slot='sidebar.session.action']) > *, .railIn .panelList, .railIn .regionArea { animation: rail-in 150ms var(--ds-ease-in-out) backwards; @@ -415,19 +429,29 @@ white-space: nowrap; } +/* New session fills the row; the session-action HOC layer renders it, then the occupant's controls. */ +.newSessionRow { + flex: none; + display: flex; + align-items: center; + gap: 6px; + margin: 0 calc(var(--dsh-sidebar-paint-inset) + 1px) 6px; +} + /* New Session: 38px bar, 12px radius (figma 133:7634 geometry, squared-off corners); collapsed it renders as the rail's plain icon control. */ .newSession { container-type: inline-size; position: relative; - flex: none; + flex: 1 1 auto; + min-width: 0; display: flex; align-items: center; justify-content: center; gap: 0; height: 38px; padding: 8px 12px; - margin: 0 calc(var(--dsh-sidebar-paint-inset) + 1px); + margin: 0; box-sizing: border-box; border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-md); @@ -459,12 +483,20 @@ } } +/* The rail stacks the occupant's controls under the New session icon. */ +.collapsed .newSessionRow { + flex-direction: column; + align-items: flex-start; + gap: 4px; + margin: 0 0 12px; +} + .collapsed .newSession { - align-self: flex-start; + flex: none; width: 36px; height: 36px; padding: 0; - margin: 0 0 12px; + margin: 0; gap: 0; border-color: transparent; background: transparent; @@ -661,6 +693,26 @@ outline-offset: -2px; } +/* A panel's trailing content follows the title in the row's flow, as a Session row's trailing icons do: a row without + content keeps its full title width, and the title yields room only to content that shows. On the collapsed rail it + sits over the icon's top trailing corner. */ +.panelTrailing { + flex: none; + display: inline-flex; + align-items: center; + margin-left: auto; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 18px; + font-variant-numeric: tabular-nums; +} + +.collapsed .panelTrailing { + position: absolute; + right: 5px; + top: 5px; +} + @media (hover: hover) { .panelUnpin { opacity: 0; } .panelEntry:hover { background-color: var(--dsw-alias-interactive-bg-hover); } @@ -811,11 +863,16 @@ .wide, .fading > *, .railIn .iconButton, - .railIn .newSession, + .railIn .newSessionRow > :global([data-slot='sidebar.session.action']) > *, .railIn .panelList, .railIn .footArea, .railIn .regionArea { 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 b573b19cc8..2be8c62182 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx @@ -18,7 +18,8 @@ * scrollbar indirection away while it is elsewhere, so a list the user is not * pointing at carries no bar. */ -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +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 @@ -74,6 +67,7 @@ function PanelRow({ id, label, wide, unpinLabel, unpinTooltip, canUnpin, usePanelInfo, selectPanel, setPinned, trackEntryClick, renderFactorySlot, }: PanelRowProps) { const active = usePanelInfo(info => info.activePanelId === id) + const trailing = useId() return (
      @@ -81,6 +75,7 @@ function PanelRow({ type="button" className={css.panelRow} aria-label={label} + aria-describedby={trailing} aria-current={active ? 'page' : undefined} onClick={() => { const entry = officialEntry(id) @@ -96,6 +91,7 @@ function PanelRow({ {label} )} + {renderFactorySlot('sidebar.panel.trailing', { id, wide, active })} {wide && canUnpin && @@ -210,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) @@ -228,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 @@ -318,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. */} @@ -380,25 +349,31 @@ export function SidebarRoot({ {/* The label fades before the hover/focus shortcut, including on translucent backgrounds. */} {canStartSession && ( - - - +
      + {renderSlot('sidebar.session.action', { wide }, { + children: ( + + + + ), + })} +
      )}
      diff --git a/packages/client/ui-sidebar/src/client/contract/slots.ts b/packages/client/ui-sidebar/src/client/contract/slots.ts index 1c36de4120..73c1a7b082 100644 --- a/packages/client/ui-sidebar/src/client/contract/slots.ts +++ b/packages/client/ui-sidebar/src/client/contract/slots.ts @@ -25,6 +25,12 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { props: SidebarPanelIconOwnerProps & { readonly id: string } children: { 'sidebar.panellist': { kind: 'list'; scope: 'root' } } } + /** Render a panel's trailing content in its navigation row. */ + 'sidebar.panel.trailing': { + scope: 'root' + props: SidebarPanelTrailingOwnerProps & { readonly id: string } + children: { 'sidebar.panellist.trailing': { kind: 'list'; scope: 'root'; inline: true } } + } } interface SlotMap { /** Non-interactive notification inside the collapsed sidebar expand button. */ @@ -45,6 +51,14 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * the sidebar owns the button and resolves its label from list metadata. */ 'sidebar.panellist': { kind: 'list'; scope: 'root'; owner: SidebarPanelIconOwnerProps } + /** + * Non-interactive inline content at the end of a panel's navigation row, registered with the panel's id, such as a + * count. The expanded row lays it out after its title, before the space its unpin action takes, so a row without + * content keeps its full title width; the collapsed rail shows it over the icon's top trailing corner. It renders + * inside the row's button: its text describes that button for assistive technology, so decorative parts are + * `aria-hidden`, and it holds no interactive elements. + */ + 'sidebar.panellist.trailing': { kind: 'list'; scope: 'root'; inline: true; owner: SidebarPanelTrailingOwnerProps } /** Rows of the panel list's More menu; the sidebar shows More only while this list has registrations. */ 'sidebar.panellist.actions': { kind: 'list'; scope: 'root'; owner: SidebarPanelActionsOwnerProps } /** @@ -73,6 +87,17 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * package's 'sidebar' entry; each action receives only the column state. */ 'sidebar.footer.action': { kind: 'list'; scope: 'root'; owner: SidebarFooterActionOwnerProps } + /** + * HOC layer around the inner content of the New-session row — the Tooltip + * and button the shell passes as `children`, rendered only while the Peer + * may create Sessions. An occupant receives that content and returns it, + * possibly wrapped, together with its own controls, so it decorates the + * row without adding a wrapper element. Occupants nest around the content + * instead of rendering beside it: one that adds nothing must return + * `children`, and with no occupant the content renders unchanged. + * Declared by this package's 'sidebar' entry. + */ + 'sidebar.session.action': { kind: 'hoc'; scope: 'root'; owner: SidebarSessionActionOwnerProps } } } @@ -96,6 +121,14 @@ export interface SidebarPanelIconOwnerProps { active: boolean } +/** Row state supplied to a panel's trailing content. */ +export interface SidebarPanelTrailingOwnerProps { + /** Whether the sidebar is expanded; the collapsed rail leaves room for a mark of a few pixels only. */ + wide: boolean + /** Whether this panel is selected in the main column. */ + active: boolean +} + /** Serializable metadata for one active global panel list registration. */ export interface SidebarPanelMetadata { /** List id and matching main panel key. */ @@ -189,6 +222,12 @@ export interface SidebarFooterActionOwnerProps { wide: boolean } +/** Owner share of the New-session row's HOC layer. */ +export interface SidebarSessionActionOwnerProps { + /** Whether the sidebar renders wide content (false = 56px rail). */ + wide: boolean +} + /** * Registrant-private injected share (arrives via the register inject * factory). The renderer binds the panel metadata source to usePanels. @@ -238,5 +277,6 @@ export type SidebarRootComponentProps = | 'sidebar.workspaces' | 'sidebar.settings' | 'sidebar.footer.action' + | 'sidebar.session.action' > & PropsRenderFactories & InjectFace & PropsLocale<'sidebar'> diff --git a/packages/client/ui-sidebar/src/client/index.ts b/packages/client/ui-sidebar/src/client/index.ts index 3bf2993dd2..8a31e46308 100644 --- a/packages/client/ui-sidebar/src/client/index.ts +++ b/packages/client/ui-sidebar/src/client/index.ts @@ -14,14 +14,14 @@ import type { SidebarPanelMetadata, SidebarRootInjected, SidebarSectionInjected import { createPanelPins } from './panel-pins.ts' import { HeaderLeadingControls } from './HeaderLeadingControls.tsx' import { SidebarRoot } from './SidebarRoot.tsx' -import { PanelIcon } from './PanelIcon.tsx' +import { PanelIcon, PanelTrailing } from './PanelIcon.tsx' import { en, ja, es, fr, de, ru, pt, zh, type SidebarKey } from './locales.ts' export type { SidebarBrandMarkOwnerProps, SidebarBrandNameOwnerProps, SidebarFooterActionOwnerProps, SidebarPanelActionEntry, SidebarPanelActionsOwnerProps, SidebarPanelIconOwnerProps, SidebarPanelMetadata, - SidebarRootComponentProps, SidebarRootInjected, SidebarSectionOwnerProps, SidebarSettingsOwnerProps, - SectionScroller, SidebarSectionHookContext, SidebarSectionInjected, UseSectionScroller, + SidebarRootComponentProps, SidebarRootInjected, SidebarSectionOwnerProps, SidebarSessionActionOwnerProps, + SidebarSettingsOwnerProps, SectionScroller, SidebarSectionHookContext, SidebarSectionInjected, UseSectionScroller, } from './contract/slots.ts' export type { SidebarKey } from './locales.ts' @@ -90,6 +90,10 @@ export function apply(ctx: ClientContext): void { name: 'sidebar.panel.icon', scope: 'root', children: { 'sidebar.panellist': { kind: 'list', scope: 'root' } }, }, PanelIcon) + yield ctx.slots.registerFactory({ + name: 'sidebar.panel.trailing', scope: 'root', + children: { 'sidebar.panellist.trailing': { kind: 'list', scope: 'root', inline: true } }, + }, PanelTrailing) yield ctx.slots.register({ name: 'sidebar', locale: NS, @@ -101,6 +105,7 @@ export function apply(ctx: ClientContext): void { 'sidebar.workspaces': { kind: 'single', scope: 'root', inject: SIDEBAR_SECTION_INJECT }, 'sidebar.settings': { kind: 'single', scope: 'root' }, 'sidebar.footer.action': { kind: 'list', scope: 'root' }, + 'sidebar.session.action': { kind: 'hoc', scope: 'root' }, }, inject: injectProps, }, SidebarRoot) 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/__snapshots__/sidebar-snapshot.client.spec.tsx.snap b/packages/client/ui-sidebar/tests/__snapshots__/sidebar-snapshot.client.spec.tsx.snap index 186d9ef6d9..ec09a73092 100644 --- a/packages/client/ui-sidebar/tests/__snapshots__/sidebar-snapshot.client.spec.tsx.snap +++ b/packages/client/ui-sidebar/tests/__snapshots__/sidebar-snapshot.client.spec.tsx.snap @@ -33,27 +33,36 @@ exports[`sidebar shell snapshots > renders Windows caption controls in expanded />
      - + + + + + + +
      +
      @@ -184,32 +193,41 @@ exports[`sidebar shell snapshots > renders Windows caption controls in expanded />
      - + +
      +
      @@ -306,27 +324,36 @@ exports[`sidebar shell snapshots > renders the collapsed rail after the crossfad />
      - + + + + + + + +
      @@ -457,32 +484,41 @@ exports[`sidebar shell snapshots > renders the expanded column (wordmark, capsul />
      - + + +
      @@ -614,32 +650,41 @@ exports[`sidebar shell snapshots > renders the expanded column in the default lo />
      - + + +
      diff --git a/packages/client/ui-sidebar/tests/apply.client.spec.tsx b/packages/client/ui-sidebar/tests/apply.client.spec.tsx index d03c19b4bb..5665077242 100644 --- a/packages/client/ui-sidebar/tests/apply.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/apply.client.spec.tsx @@ -75,6 +75,7 @@ describe('ui-sidebar apply', () => { expect(section.inject.hooks.sectionScroller({} as never, { useSectionScroller })).toBe(useSectionScroller) expect(b.slots.spec('sidebar.settings')).toEqual({ kind: 'single', scope: 'root' }) expect(b.slots.spec('sidebar.footer.action')).toEqual({ kind: 'list', scope: 'root' }) + expect(b.slots.spec('sidebar.session.action')).toEqual({ kind: 'hoc', scope: 'root' }) expect(b.slots.spec('sidebar.panellist')).toEqual({ kind: 'list', scope: 'root' }) // Copy rides the standard locale seat, not the inject face. expect(b.slots.entries('sidebar')[0]!.locale).toBe('sidebar') @@ -190,6 +191,7 @@ describe('ui-sidebar apply', () => { expect(b.slots.spec('sidebar.brand.name')).toBeUndefined() expect(b.slots.spec('sidebar.workspaces')).toBeUndefined() expect(b.slots.spec('sidebar.footer.action')).toBeUndefined() + expect(b.slots.spec('sidebar.session.action')).toBeUndefined() expect(b.slots.spec('sidebar.panellist')).toBeUndefined() expect(b.slots.entries('main')).toHaveLength(0) }) diff --git a/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx b/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx index 554192b591..84b73a5133 100644 --- a/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx @@ -511,3 +511,68 @@ describe('sidebar entry click analytics', () => { expect(layout.selectPanel).not.toHaveBeenCalled() }) }) + +/** Trailing content that names the row state it receives; its visible count is decorative and its text describes the row. */ +function Count({ wide, active }: PropsRuntime<'sidebar.panellist.trailing'>) { + return ( + + + 6 waiting + + ) +} + +async function mountCount(runtime: SlotTestRuntime, id: MainPanelId) { + return runtime.mount({ + inject: ['slots'], + apply(ctx: Context) { + ctx.slots.inject('sidebar.panellist.trailing', () => ctx.slots.register({ name: 'sidebar.panellist.trailing', id }, Count)) + }, + }) +} + +describe('sidebar panel trailing content', () => { + it('shows a panel registration in its own row only, describing the row button, and follows the selection', async () => { + const { runtime, locale, view } = await bench() + await mountPanels(runtime, locale) + await mountCount(runtime, ALPHA) + + const alpha = await view.findByRole('button', { name: 'Alpha panel' }) + const beta = view.getByRole('button', { name: 'Beta panel' }) + expect(alpha.getAttribute('aria-describedby')).not.toBeNull() + const described = document.getElementById(alpha.getAttribute('aria-describedby') ?? '') + expect(described?.textContent).toBe('66 waiting') + expect(within(described as HTMLElement).getByTestId('count').dataset).toMatchObject({ wide: 'true', active: 'false' }) + expect(document.getElementById(beta.getAttribute('aria-describedby') ?? '')?.textContent).toBe('') + expect(view.getAllByTestId('count')).toHaveLength(1) + // The content sits inside the row button after its title; the slot wrappers are inline spans, so nesting stays valid. + expect(alpha.contains(described)).toBe(true) + expect(described?.previousElementSibling?.textContent).toBe('Alpha panel') + const wrappers = [...(described?.querySelectorAll('[data-slot]') ?? [])] + expect(wrappers.length).toBeGreaterThan(0) + expect(wrappers.every(wrapper => wrapper.tagName === 'SPAN')).toBe(true) + expect(described?.querySelector('div')).toBeNull() + + fireEvent.click(alpha) + await waitFor(() => { expect(view.getByTestId('count').dataset.active).toBe('true') }) + }) + + it('tells the collapsed rail it is not wide', async () => { + const { runtime, locale, view } = await bench(true) + await mountPanels(runtime, locale) + await mountCount(runtime, BETA) + + await waitFor(() => { expect(view.getByTestId('count').dataset.wide).toBe('false') }) + }) + + it('removes the content when its registering fiber is disposed', async () => { + const { runtime, locale, view } = await bench() + await mountPanels(runtime, locale) + const count = await mountCount(runtime, ALPHA) + await view.findByTestId('count') + + await act(async () => { await count.dispose() }) + expect(view.queryByTestId('count')).toBeNull() + expect(view.getByRole('button', { name: 'Alpha panel' })).toBeTruthy() + }) +}) 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-root.client.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.client.spec.tsx index f6b1b391c6..4ce129f5a9 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.client.spec.tsx @@ -10,6 +10,7 @@ import type { ReactNode } from 'react' import { useState } from 'react' import type { SidebarFooterActionOwnerProps, SidebarPanelMetadata, SidebarRootComponentProps, SidebarSectionHookContext, SidebarSectionOwnerProps, + SidebarSessionActionOwnerProps, SidebarSettingsOwnerProps, } from '../src/client/contract/slots.ts' import { HeaderLeadingControls, type HeaderLeadingControlsProps } from '../src/client/HeaderLeadingControls.tsx' @@ -65,6 +66,8 @@ function mountShell({ collapsed = false, width = 300, drawer = false, shortcuts let regionContext: SidebarSectionHookContext | undefined let settingsOwner: SidebarSettingsOwnerProps | undefined let footerActionOwner: SidebarFooterActionOwnerProps | undefined + let sessionActionOwner: SidebarSessionActionOwnerProps | undefined + let sessionActionChildren: ReactNode const brandMark = M const brandName = Custom Brand let current = { collapsed, width, drawer } @@ -82,8 +85,8 @@ function mountShell({ collapsed = false, width = 300, drawer = false, shortcuts renderFactorySlot={() => null} renderSlot={(( key: string, - owner: SidebarFooterActionOwnerProps | SidebarSectionOwnerProps | SidebarSettingsOwnerProps, - opts?: { hookContext?: SidebarSectionHookContext }, + owner: SidebarFooterActionOwnerProps | SidebarSectionOwnerProps | SidebarSessionActionOwnerProps | SidebarSettingsOwnerProps, + opts?: { hookContext?: SidebarSectionHookContext; children?: ReactNode }, ) => { if (key === 'sidebar.brand.mark') return brandMark if (key === 'sidebar.brand.name') return brandName @@ -97,6 +100,11 @@ function mountShell({ collapsed = false, width = 300, drawer = false, shortcuts footerActionOwner = owner return
      } + if (key === 'sidebar.session.action') { + sessionActionOwner = owner + sessionActionChildren = opts?.children + return <>{opts?.children}
      + } regionOwner = owner as SidebarSectionOwnerProps regionContext = opts?.hookContext return
      {content}
      @@ -124,6 +132,11 @@ function mountShell({ collapsed = false, width = 300, drawer = false, shortcuts if (footerActionOwner === undefined) throw new Error('footer action owner not rendered') return footerActionOwner }, + sessionActionOwner: () => { + if (sessionActionOwner === undefined) throw new Error('session action owner not rendered') + return sessionActionOwner + }, + sessionActionChildren: () => sessionActionChildren, rerender(next: Partial) { current = { ...current, ...next } view.rerender(root()) @@ -379,6 +392,12 @@ describe('SidebarRoot shell', () => { // The settings seat rides the same wide flag (ui-settings renders the row). expect(b.settingsOwner().wide).toBe(true) expect(b.footerActionOwner().wide).toBe(true) + expect(b.sessionActionOwner().wide).toBe(true) + // The HOC layer receives the New-session row content as its children. + expect(b.sessionActionChildren()).toBeTruthy() + // Session actions follow New session inside the same row. + const newSession = screen.getAllByRole('button', { name: 'New session' }).at(-1) + expect(newSession?.nextElementSibling).toBe(screen.getByTestId('session-action-seat')) // Expanded: the request is a no-op (no accidental collapse). b.regionOwner().expandSidebar() expect(b.toggleSidebar).not.toHaveBeenCalled() @@ -394,6 +413,7 @@ describe('SidebarRoot shell', () => { b.rerender({}) expect(b.regionOwner().wide).toBe(false) expect(b.footerActionOwner().wide).toBe(false) + expect(b.sessionActionOwner().wide).toBe(false) expect(screen.getByTestId('region')).toBeTruthy() b.regionOwner().expandSidebar() expect(b.toggleSidebar).toHaveBeenCalledOnce() diff --git a/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx index dfa756943b..8e43e112e2 100644 --- a/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx @@ -72,6 +72,18 @@ describe('sidebar shell snapshots', () => { await runtime.dispose() }) + it('renders the New-session content through the unoccupied session-action HOC layer', async () => { + const { runtime } = await bench({ locale: 'en' }) + const slot = runtime.renderSlot('sidebar', { collapsed: false, width: 300, drawer: false }) + const layer = slot.container.querySelector('[data-slot="sidebar.session.action"]') + // With no occupant the layer renders the owner's content unchanged, so the + // capsule keeps its box and no wrapper element joins the row. + expect(layer?.children).toHaveLength(1) + expect(layer?.firstElementChild?.getAttribute('aria-label')).toBe('New session') + expect(layer?.firstElementChild?.tagName).toBe('BUTTON') + await runtime.dispose() + }) + it('renders the collapsed rail after the crossfade settles, in place', async () => { const { runtime } = await bench({ locale: 'en' }) const slot = runtime.renderSlot('sidebar', { collapsed: false, width: 300, drawer: false }) 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 3ed16573ec..789c7cd550 100644 --- a/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts +++ b/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts @@ -1,6 +1,7 @@ /** Sidebar shell style contracts shared with its slot-owned controls. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' +import { JSDOM } from 'jsdom' import { describe, expect, it } from 'vitest' const css = readFileSync(fileURLToPath(new URL('../src/client/SidebarRoot.module.css', import.meta.url)), 'utf8') @@ -25,6 +26,28 @@ function declarations(selector: string): Map | undefined { return undefined } +/** + * Every declared selector, including those inside at-rule blocks. + * @returns the selector text of each comma-separated part. + */ +function declaredSelectors(): string[] { + const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, ' ') + return [...withoutComments.matchAll(/([^{}]+)\{([^{}]*)\}/g)] + .flatMap(([, selectorList = '']) => selectorList.split(',').map(value => value.trim())) +} + +/** Declarations of the reduced-motion block, which disables every rail animation. */ +function reducedMotion(): string { + return css.match(/@media \(prefers-reduced-motion: reduce\) \{([\s\S]*)\n\}/u)?.[1] ?? '' +} + +/** The renderer's `display: contents` anchor for the sidebar session action HOC slot. */ +const SLOT_ANCHOR = ":global([data-slot='sidebar.session.action'])" +/** The shell's New-session button and the occupant's controls: the anchor's children, each matched once. */ +const ROW_CONTENT = `.railIn .newSessionRow > ${SLOT_ANCHOR} > *` +/** The rail rule as a plain selector a DOM can match, with the CSS-module escape removed. */ +const ROW_CONTENT_SELECTOR = ROW_CONTENT.replace(SLOT_ANCHOR, "[data-slot='sidebar.session.action']") + describe('SidebarRoot.module.css', () => { it('uses a compact expanded navigation gap without shrinking the collapsed rail spacing', () => { expect(declarations('.panelList')?.get('gap')).toBe('2px') @@ -88,20 +111,22 @@ 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('.newSession')?.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)') expect(css).not.toContain(':not(.fading)') - expect(declarations(':global([data-windows-titlebar]) .root:not(.collapsed) .newSession')?.has('margin-left')).toBe(false) + expect(declarations(':global([data-windows-titlebar]) .root:not(.collapsed) .newSessionRow')?.get('margin-top')).toBe('6px') + expect(declarations(':global([data-windows-titlebar]) .root:not(.collapsed) .newSessionRow')?.has('margin-left')).toBe(false) expect(declarations('.topStrip')?.get('height')).toBe('52px') expect(declarations('.root.collapsed')?.get('padding')).toBe('18px 10px 6px') }) - it('moves the four upper controls while the settings seat only fades', () => { + it('moves the upper controls while the settings seat only fades', () => { const animation = 'rail-in 150ms var(--ds-ease-in-out) backwards' for (const selector of [ '.railIn .iconButton', - '.railIn .newSession', + ROW_CONTENT, '.railIn .regionArea', ]) { expect(declarations(selector)?.get('animation')).toBe(animation) @@ -115,9 +140,48 @@ describe('SidebarRoot.module.css', () => { expect(css).toMatch(/@keyframes rail-fade-in\s*\{\s*from\s*\{\s*opacity: 0;\s*}\s*}/) }) + it('fades the New Session row through its slot anchor without reaching into either button', () => { + // The row renders its content through the HOC slot, so the renderer's + // display:contents anchor is the row's only child; the shell's New-session + // button and the occupant's own controls are the anchor's children. + expect(declarations(ROW_CONTENT)?.get('animation')).toBe('rail-in 150ms var(--ds-ease-in-out) backwards') + expect(reducedMotion()).toContain(ROW_CONTENT) + for (const selector of declaredSelectors()) { + if (!selector.includes('.newSessionRow')) continue + // A bare star under the row matches the boxless anchor, so nothing animates. + expect(selector).not.toMatch(/\.newSessionRow\s*>\s*\*/u) + // A second bare star step also matches .newSessionLabelMask and + // .newSessionShortcut inside the button, which would run rail-in twice on it. + expect(selector).not.toMatch(/>\s*\*\s*>\s*\*/u) + expect(selector).not.toContain('.newSessionLabelMask') + expect(selector).not.toContain('.newSessionShortcut') + } + }) + + it('matches exactly the two buttons the slot anchor holds', () => { + // The renderer's outlet anchor is a display:contents div; the shell's + // New-session button and the occupant's control are its element children. + const { document } = new JSDOM(` +
      +
      +
      + + +
      +
      +
      `).window + const matched = [...document.querySelectorAll(ROW_CONTENT_SELECTOR)] + expect(matched.map(element => element.className)).toEqual(['newSession', 'trigger']) + // A bare child step matches only the boxless anchor, so nothing would animate. + expect(document.querySelectorAll('.railIn .newSessionRow > *')).toHaveLength(1) + }) + it('gives shell rail controls the same base anchor for their shared translation', () => { expect(declarations('.collapsed .logoRow')?.get('justify-content')).toBe('flex-start') - expect(declarations('.collapsed .newSession')?.get('align-self')).toBe('flex-start') + expect(declarations('.collapsed .newSessionRow')?.get('align-items')).toBe('flex-start') expect(declarations('.collapsed .newSession')?.get('width')).toBe('36px') }) @@ -130,4 +194,21 @@ describe('SidebarRoot.module.css', () => { expect(declarations('.fallbackBrandName')?.get('font-size')).toBe('17px') expect(declarations('.fallbackBrandName')?.get('white-space')).toBe('nowrap') }) + + it('lays panel trailing content out after the title like a Session row, reserving no room without content', () => { + const trailing = declarations('.panelTrailing') + expect(trailing?.get('flex')).toBe('none') + expect(trailing?.get('margin-left')).toBe('auto') + expect(trailing?.has('position')).toBe(false) + expect(declarations('.panelEntryWide .panelRow')?.get('padding-right')).toBe('38px') + expect(css).not.toMatch(/\.panelTrailing:(?:not\()?:?empty/) + expect(css).not.toMatch(/\.panelRow\s*\{[^}]*padding-right:\s*72px/) + }) + + it('pins panel trailing content over the collapsed rail icon\'s top trailing corner', () => { + const collapsed = declarations('.collapsed .panelTrailing') + expect(collapsed?.get('position')).toBe('absolute') + expect(collapsed?.get('right')).toBe('5px') + expect(collapsed?.get('top')).toBe('5px') + }) }) diff --git a/packages/client/ui-skill/README.i18n.yaml b/packages/client/ui-skill/README.i18n.yaml index 59386d4b39..fb293de270 100644 --- a/packages/client/ui-skill/README.i18n.yaml +++ b/packages/client/ui-skill/README.i18n.yaml @@ -18,8 +18,8 @@ en: 2f17d0875048ef3c zh: 6878ee4c75f2b2cf /deepseek-ai-dsh-client-ui-skill/use-this-package/what-the-source-offers: - en: 2ba1a6158c85b46e - zh: 9ab58ceef8743849 + en: fa23ec0de0463e30 + zh: 1772d637d96843b6 /deepseek-ai-dsh-client-ui-skill/use-this-package/the-skill-tool-row: en: 270bc37a226ed247 zh: 15a1c4c82c3a1f00 diff --git a/packages/client/ui-skill/README.md b/packages/client/ui-skill/README.md index fcc361b188..5de4da2a92 100644 --- a/packages/client/ui-skill/README.md +++ b/packages/client/ui-skill/README.md @@ -29,7 +29,7 @@ Type `/` in the composer and pick a skill from the suggestions, or type `/name` ### What the source offers -Ordinary-session candidates come from the `skills/list` Remote; the host serves every user-invocable skill, and a `modelInvocable: false` entry (a `disable-model-invocation` skill, whose only entry point is this path) wears the user-only marker as a description prefix in the active language. Results rank through the `/` menu's shared name ranker, `rankByName` from ui-primitives: the query matches a case-insensitive ordered subsequence of the skill name, prefix hits rank first, and ties keep the host order ([ranking decision](../../../.agents/notes/archived/feature/2026-08-04-web-slash-command-fuzzy-discovery.md)). A failed `skills/list` call is logged and folded into a silent menu-group drop — the menu shows only pending/ready states. +Ordinary-session candidates come from the `skills/list` Remote; the host serves every user-invocable skill, and a `modelInvocable: false` entry (a `disable-model-invocation` skill, whose only entry point is this path) wears the user-only marker as a description prefix in the active language. Results filter through the same [text search](../../util/text-search/README.md) as the command group: the skill name matches fuzzily and ties keep the host order. Descriptions do not match, because the `/` menu highlights its first row across all groups and a description hit in an earlier group would take Enter from the skill the user named. A failed `skills/list` call is logged and folded into a silent menu-group drop — the menu shows only pending/ready states. ### The skill tool row diff --git a/packages/client/ui-skill/README.zh.md b/packages/client/ui-skill/README.zh.md index 6594d3807d..f1a6ea5b93 100644 --- a/packages/client/ui-skill/README.zh.md +++ b/packages/client/ui-skill/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### source 提供什么 -普通会话的候选来自 `skills/list` Remote;宿主提供每一个用户可调用的 skill,`modelInvocable: false` 的条目(即 `disable-model-invocation` skill,此路径是其唯一入口)会以当前语言把仅限用户标记作为描述前缀带上。结果经 `/` 菜单共享的名字排序器(ui-primitives 的 `rankByName`)排名:查询作为不区分大小写的有序子序列匹配 skill 名,前缀命中排最前,同分保持宿主顺序([排名决策](../../../.agents/notes/archived/feature/2026-08-04-web-slash-command-fuzzy-discovery.md))。`skills/list` 调用失败时会被记录并静默丢弃该菜单组——菜单只显示 pending/ready 状态。 +普通会话的候选来自 `skills/list` Remote;宿主提供每一个用户可调用的 skill,`modelInvocable: false` 的条目(即 `disable-model-invocation` skill,此路径是其唯一入口)会以当前语言把仅限用户标记作为描述前缀带上。结果与命令组使用同一套[文本搜索](../../util/text-search/README.zh.md)筛选:skill 名称按模糊匹配,得分相同的结果保持宿主给出的顺序。描述不参与匹配,因为 `/` 菜单高亮的是所有分组合在一起的第一行;如果较前分组中有描述命中,Enter 会选中这一行,而不是用户输入名称对应的 skill。`skills/list` 调用失败时会被记录并静默丢弃该菜单组——菜单只显示 pending/ready 状态。 ### skill 工具行 diff --git a/packages/client/ui-skill/package.json b/packages/client/ui-skill/package.json index 9babd70d63..6edd35eca7 100644 --- a/packages/client/ui-skill/package.json +++ b/packages/client/ui-skill/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-skill", "description": "Web skill references and the dedicated skill tool row", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, @@ -69,7 +69,8 @@ "react-dom": "^18.2.0", "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", - "@deepseek-ai/dsh-util-workspace-path": "workspace:*" + "@deepseek-ai/dsh-util-workspace-path": "workspace:*", + "@deepseek-ai/dsh-util-text-search": "workspace:*" }, "files": [ "locale/*.json", 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-skill/src/client/index.ts b/packages/client/ui-skill/src/client/index.ts index db9b746dba..8206ffb419 100644 --- a/packages/client/ui-skill/src/client/index.ts +++ b/packages/client/ui-skill/src/client/index.ts @@ -42,7 +42,7 @@ import type {} from '@deepseek-ai/dsh-plugin-manager/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { InputTriggerServiceContract, InputTriggerSource } from '@deepseek-ai/dsh-client-ui-input-trigger/client' import { fileAddressFor } from '@deepseek-ai/dsh-util-workspace-path' -import { rankByName } from '@deepseek-ai/dsh-client-ui-primitives' +import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' // Type-only: pulls the locale plugin's Context merge (ctx.locale). import type {} from '@deepseek-ai/dsh-client-locale/client' // Type-only: pulls the SlotRegistry service merge (ctx.slots). @@ -173,9 +173,8 @@ export function apply(ctx: ClientContext): void { const skills = await fetchCatalog(session.sessionId).promise // Superseded keystroke: the shared fetch stays warm, this caller yields. if (signal.aborted) return [] - // The same ranking as the command group of this menu: case-insensitive - // ordered subsequence, prefix hits first. - return rankByName(skills, query) + // The same filter as the command group of this menu, over names only. + return new TextSearchIndex(skills, skill => ({ fuzzy: [skill.name] })).search(query) .map(skill => ({ name: skill.name, // The user-only marker rides the description (the menu's only diff --git a/packages/client/ui-skill/tests/browser-plugin.client.spec.ts b/packages/client/ui-skill/tests/browser-plugin.client.spec.ts index b160c954ad..193536a283 100644 --- a/packages/client/ui-skill/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-skill/tests/browser-plugin.client.spec.ts @@ -260,7 +260,7 @@ describe('candidates: sessionId addressing', () => { } }) - it('lists via {sessionId} and ranks case-insensitive subsequence matches with prefixes first', async () => { + it('lists via {sessionId} and ranks prefix, substring, then fuzzy name matches', async () => { const { list, payloads } = countingList() const { source } = await bench(list) const items = await source.candidates(proj('s1'), req('co')) @@ -271,10 +271,12 @@ describe('candidates: sessionId addressing', () => { { name: 'code-review', description: 'review flow' }, ]) const names = async (query: string) => (await source.candidates(proj('s1'), req(query))).map(c => c.name) - // 'de' prefixes deploy and is a subsequence of code-review: the prefix ranks first. + // 'de' prefixes deploy and occurs inside code-review: the prefix ranks first. await expect(names('de')).resolves.toEqual(['deploy', 'code-review']) await expect(names('REV')).resolves.toEqual(['code-review']) await expect(names('zzz')).resolves.toEqual([]) + // Descriptions do not match: 'flow' appears only in descriptions. + await expect(names('flow')).resolves.toEqual([]) }) it('rejects on a failed result (the slash shell owns the menu-side fold)', async () => { diff --git a/packages/client/ui-skill/tsconfig.json b/packages/client/ui-skill/tsconfig.json index cf3c43a1cd..3d7ccf727d 100644 --- a/packages/client/ui-skill/tsconfig.json +++ b/packages/client/ui-skill/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../../util/text-search" + }, { "path": "../../api/remotes/tsconfig.client.json" }, diff --git a/packages/client/ui-slots/package.json b/packages/client/ui-slots/package.json index 5a88f2967b..9a7a058e28 100644 --- a/packages/client/ui-slots/package.json +++ b/packages/client/ui-slots/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-slots", "description": "Slot registry pure core: typed ordinary Slots and reusable Component Factories, derived props, Store seats, and renderer installation", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.4", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-slots/src/index.ts b/packages/client/ui-slots/src/index.ts index a6f829e884..bf1200e5d1 100644 --- a/packages/client/ui-slots/src/index.ts +++ b/packages/client/ui-slots/src/index.ts @@ -906,6 +906,8 @@ export interface StoredEntry { locale?: string | undefined /** Diagnostics label of who registered. */ registrant?: string | undefined + /** Package name of the Loader entry that registered, absent outside a Loader entry. */ + module?: string | undefined } /** @@ -942,6 +944,7 @@ interface ErasedOptions { * against the per-declaration InjectParams tuples. */ inject?: ((...args: any) => Record) | undefined registrant?: string | undefined + module?: string | undefined } /** @@ -1346,6 +1349,7 @@ export class SlotCore { ...(options.store !== undefined ? { store: options.store } : {}), ...(options.locale !== undefined ? { locale: options.locale } : {}), ...(options.registrant !== undefined ? { registrant: options.registrant } : {}), + ...(options.module !== undefined ? { module: options.module } : {}), } const next = [...rec.entries, entry] // Stable sorts: priority ascending for every kind, ties keep registration 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 图标旋转,点击展开控件不会触发行导航或侧边栏导航。悬停展开控件仅高亮箭头;悬停导航主体或键盘聚焦时仍保留背景高亮。细连接线使用三级边框颜色,与首行图标中心对齐,跨过预留的展开控件空间连接叶子状态图标,末端竖线止于对应图标中心。