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/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml index e910137117..2bfd88d57c 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml @@ -9,11 +9,11 @@ en: c389c332bdadbbe4 zh: 217520278ccf0932 /agent-note-unambiguous-tool-argument-compatibility/decision: - en: 71c04efcfd972b02 - zh: d1f842920b1b0e3f + en: c6ac657b3875c95f + zh: 7b0a4cca7baafd03 /agent-note-unambiguous-tool-argument-compatibility/alternatives-considered: en: b2a96695819a978f zh: c6f84b244be0dddf /agent-note-unambiguous-tool-argument-compatibility/consequences: - en: bd24ad737c617c90 - zh: dbb7fa67c41af828 + en: 7d21da549466232c + zh: a373e135f79c5423 diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md index 7e2a5111c3..9cc6ced02e 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md @@ -10,7 +10,7 @@ Models can populate optional fields that do not affect the requested operation. ## Decision -`grep` treats an exact empty `include` as omitted. Whitespace-only, negated, and comma-separated filters remain invalid. `update_goal` uses replacement fields only for `edit` and a blocker reason only for `blocked`; other actions ignore those known fields. Declared types, consumed values, authority, and exact revisions remain validated. Ignored fields never reach another goal operation or change unrelated state, and call summaries select only values used by the action. `write` and `edit` allow absent or blank justification when no sandbox mode is requested or the effective mode is repeated; actual widening retains its reason and approval requirements, and filesystem observation and denial checks remain active. +`grep` treats an exact empty `include` as omitted. Whitespace-only, negated, and comma-separated filters remain invalid. `update_goal` uses replacement fields only for `edit` and a blocker reason only for `blocked`; other actions ignore those known fields. Declared types, consumed values, authority, and exact revisions remain validated. Ignored fields never reach another goal operation or change unrelated state, and call summaries select only values used by the action. `write` and `edit` allow absent or blank justification when no sandbox mode is requested or the effective mode is repeated; actual widening retains its reason and approval requirements, and filesystem observation and denial checks remain active. `subagent` and `list_subagent_models` treat an exact empty `provider`, `model`, or `reasoning_effort` as omitted; an empty subagent `name` remains invalid because its error states the accepted format. This partially supersedes the unused-field rejection in the [goal-tool decision](../feature/2026-07-19-model-facing-goal-tools.md). Its authority, lifecycle, scheduling, and persistence decisions remain active. The rules apply to every provider and stay inside the owning tool rather than weakening its underlying service. @@ -22,4 +22,4 @@ This partially supersedes the unused-field rejection in the [goal-tool decision] ## Consequences -The tools accept these calls without extra mutations. Unit tests cover ignored fields for every goal action, consumed-field and authority failures, stale revisions, filter validation, and real search results. A headless recorded-session scenario verifies both file extensions are searched and completion preserves the original objective and round cap. These rules give up detecting conflicting intent expressed only in inactive goal fields; they do not weaken authorization or establish a generic coercion policy. +The tools accept these calls without extra mutations. Unit tests cover ignored fields for every goal action, consumed-field and authority failures, stale revisions, filter validation, and real search results. A headless recorded-session scenario verifies both file extensions are searched and completion preserves the original objective and round cap. An SDK recorded-session scenario verifies that empty route fields start a subagent on its default route. These rules give up detecting conflicting intent expressed only in inactive goal fields; they do not weaken authorization or establish a generic coercion policy. diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md index 6887d9feb8..79c0cb2345 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`grep` 将值恰好为空字符串的 `include` 视为省略。仅含空白、否定形式和逗号分隔的过滤器仍然无效。`update_goal` 仅在 `edit` 时使用替换字段,仅在 `blocked` 时使用阻塞原因;其他 action 忽略这些已知字段。声明的类型、实际使用的值、权限和精确修订号仍会校验。被忽略的字段不会传入另一种目标操作,也不会改变无关状态;调用摘要仅选择当前 action 使用的值。未请求沙箱模式或重复当前生效模式时,`write` 和 `edit` 允许省略理由或提供空白理由;真正升权仍需理由和审批,文件系统观察与拒绝检查继续生效。 +`grep` 将值恰好为空字符串的 `include` 视为省略。仅含空白、否定形式和逗号分隔的过滤器仍然无效。`update_goal` 仅在 `edit` 时使用替换字段,仅在 `blocked` 时使用阻塞原因;其他 action 忽略这些已知字段。声明的类型、实际使用的值、权限和精确修订号仍会校验。被忽略的字段不会传入另一种目标操作,也不会改变无关状态;调用摘要仅选择当前 action 使用的值。未请求沙箱模式或重复当前生效模式时,`write` 和 `edit` 允许省略理由或提供空白理由;真正升权仍需理由和审批,文件系统观察与拒绝检查继续生效。`subagent` 和 `list_subagent_models` 将值恰好为空字符串的 `provider`、`model` 或 `reasoning_effort` 视为省略;空的 subagent `name` 仍然无效,因为其报错会说明可接受的格式。 本决策部分取代[目标工具决策](../feature/2026-07-19-model-facing-goal-tools.zh.md)中对无关字段的拒绝规则。其权限、生命周期、调度和持久化决策继续生效。这些规则适用于所有提供方,并保留在所属工具内,不削弱底层服务的校验。 @@ -22,4 +22,4 @@ Status: implemented ## 后果 -工具接受这些调用,且不会产生额外变更。单元测试覆盖每种目标 action 对无关字段的忽略、有效字段与权限失败、陈旧修订号、过滤器校验以及真实搜索结果。headless 会话回放验证两种扩展名的文件都参与搜索,并且完成操作保留原始目标和轮数上限。这些规则放弃检测仅由非当前 action 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。 +工具接受这些调用,且不会产生额外变更。单元测试覆盖每种目标 action 对无关字段的忽略、有效字段与权限失败、陈旧修订号、过滤器校验以及真实搜索结果。headless 会话回放验证两种扩展名的文件都参与搜索,并且完成操作保留原始目标和轮数上限。SDK 会话回放验证空路由字段会让 subagent 按默认路由启动。这些规则放弃检测仅由非当前 action 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml new file mode 100644 index 0000000000..db0702f47e --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-13-draft-attachments-across-session-switches.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md +/agent-note-draft-attachments-across-session-switches: + en: 2a1645c8c80d6dff + zh: 59277c3754231479 +/agent-note-draft-attachments-across-session-switches/problem: + en: 3f4030763e1f0105 + zh: c8a0bc5641d7bed4 +/agent-note-draft-attachments-across-session-switches/decision: + en: 40697e88c2ed6ca8 + zh: eeb363374b25c3a2 +/agent-note-draft-attachments-across-session-switches/alternatives-considered: + en: 2c43ad479f4a3577 + zh: 07743f45870eb0fe +/agent-note-draft-attachments-across-session-switches/consequences: + en: 6ac6defa552ea040 + zh: aa64a3c3e54dbebc diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md new file mode 100644 index 0000000000..8c33335f55 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -0,0 +1,25 @@ +# Agent Note: Draft attachments across Session switches + +Status: implemented + +English | [中文](2026-11-13-draft-attachments-across-session-switches.zh.md) + +## Problem + +Switching to another Session and back emptied the composer's attachment rail while its text survived (issue #5070). The Session scope disposer released every attachment the retiring composer held and revoked image previews, and nothing could rebuild them. + +## Decision + +**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A message the Host accepts leaves that ownership at once, while the registry keeps its attachments until the echo settles them. A retiring composer releases its attachments only when its Session was removed or a message or command was already submitted, because the Client cannot tell whether a submitted command consumed them; an aborted slash-line adjudication keeps them. Otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed. + +**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session that still owns draft attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark and no registered attachments shows the "add them again" notice. + +## Alternatives considered + +**Restoring attachments after a reload from durable browser references and a Host `restore` Remote.** It would bring uploaded files and images back after a page reload, but it needs a Host Remote with its Liveshare and catalog classifications, a persisted browser format, a send gate during restoration, and an image byte payload. Desktop, where most users work, gains little: its Host binds a new port on every launch, so its storage origin, and with it every saved reference, does not survive an application restart. + +**Releasing settled attachments on a switch and restoring them from the Host on return.** It would save the memory of pasted images while a Session is not shown, but every return needs a Host round trip, fails on a weak network, and allocates the same bytes again. + +## Consequences + +Switching never touches the Host, so a weak network cannot lose a draft attachment there. A reload or crash still discards attachments; a crash writes no mark and so shows no notice. diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md new file mode 100644 index 0000000000..645a79c881 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -0,0 +1,25 @@ +# Agent Note:草稿附件跨会话切换 + +Status: implemented + +[English](2026-11-13-draft-attachments-across-session-switches.md) | 中文 + +## 问题 + +切到另一个会话再切回时,输入框的附件栏被清空,文字却还在(issue #5070)。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。 + +## 决策 + +**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。Host 接受消息时,这些附件立即退出会话归属,注册表则保留它们直到回显结算。退役的输入框只在其会话已被删除、或消息与命令已经提交时释放附件,因为客户端无法判断已提交的命令是否用掉了附件;被中止的斜杠行裁决会保留附件。其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。 + +**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个仍持有草稿附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记且没有已登记附件的输入框,会显示「请重新添加」提示。 + +## 考虑过的替代方案 + +**刷新后通过浏览器 durable 引用与 Host `restore` Remote 恢复附件。** 它能在页面刷新后找回已上传的文件和图片,但需要新增一个 Host Remote 及其 Liveshare 与目录分类、一种浏览器持久化格式、恢复期间的发送拦截和图片字节载荷。主要用户所在的桌面端收益很小:桌面端 Host 每次启动都绑定新端口,存储 origin 连同所有已存引用都无法跨应用重启保留。 + +**切换时释放已结算附件,切回时由 Host 恢复。** 它能在会话不显示期间省下粘贴图片的内存,但每次切回都需要一次 Host 往返,弱网下会失败,并且之后还要再分配同样的字节。 + +## 影响 + +切换会话从不访问 Host,因此弱网不会让草稿附件在切换中丢失。刷新或崩溃仍会丢弃附件;崩溃时不会写标记,因此没有提示。 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index fadd86301d..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: cb337f04d0fe41b5 - zh: d9dc249507c419b6 + 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 7aad6df300..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,7 +10,7 @@ English | [中文](2026-10-09-forge-panel.zh.md) ## Decision -[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) is a two-face package. Its Host half, the `forgePanel` Remote, assembles everything the panel shows for one Session into one streamed state; the forge registry and the binding service keep only their domain operations. Its Client half is a right-sidebar tab, a Session header button that shows or hides it, a New Session option, a creation card above the composer, a toast, and the [Session list icons and hover card section](2026-10-20-forge-session-list.md). Every surface calls a bound item a change request, the forge registry's term, whatever its code host calls it. The [forge bundle](../../../../packages/experimental/forge-bundle/README.md) ships the panel, the forge registry, the GitHub provider, the bindings, the worktree model tool, and an isolated worktree service for the panel as one default-disabled Plugins page entry. +[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) is a two-face package. Its Host half, the `forgePanel` Remote, assembles everything the panel shows for one Session into one streamed state; the forge registry and the binding service keep only their domain operations. Its Client half is a Change requests section, checkout and local changes rows, and an attention mark in the [Session panel](2026-11-05-session-panel.md), a changes view, a New Session option, a creation card above the composer, a toast, and the [Session list icons and hover card section](2026-10-20-forge-session-list.md). Every surface calls a bound item a change request, the forge registry's term, whatever its code host calls it. The [forge bundle](../../../../packages/experimental/forge-bundle/README.md) ships the panel, the forge registry, the GitHub provider, the bindings, the worktree model tool, and an isolated worktree service for the panel as one default-disabled Plugins page entry. Review and worktree controls serve one code-change workflow. One Plugins entry lets users enable that workflow without having to distinguish the underlying package split. Packages and the two worktree services remain independent so each owns its before-Session or in-conversation creation flow. diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index f478c05f6f..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,7 +10,7 @@ Status: implemented ## Decision -[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 是一个双端包。宿主端的 `forgePanel` Remote 把面板为一个 Session 展示的全部内容组装成一条流式状态;forge 注册表与绑定服务只保留各自的领域操作。客户端包括一个右侧边栏标签页、一个显示或隐藏它的 Session 标题栏按钮、一个新会话选项、一张位于输入框上方的创建卡片、一个 toast,以及[会话列表中的图标与悬浮卡片部分](2026-10-20-forge-session-list.zh.md)。所有界面都把已绑定的条目称为变更请求(forge 注册表的术语),不随代码托管平台的叫法变化。[forge 套件](../../../../packages/experimental/forge-bundle/README.zh.md)把面板、forge 注册表、GitHub 提供方、绑定服务、工作树模型工具与面板使用的一个隔离 worktree 服务作为插件页中默认禁用的一个条目发布。 +[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 是一个双端包。宿主端的 `forgePanel` Remote 把面板为一个 Session 展示的全部内容组装成一条流式状态;forge 注册表与绑定服务只保留各自的领域操作。客户端包括[会话面板](2026-11-05-session-panel.zh.md)中的“变更请求”分栏、检出行与本地变更行和提醒标记,以及一个变更视图、一个新会话选项、一张位于输入框上方的创建卡片、一个 toast,以及[会话列表中的图标与悬浮卡片部分](2026-10-20-forge-session-list.zh.md)。所有界面都把已绑定的条目称为变更请求(forge 注册表的术语),不随代码托管平台的叫法变化。[forge 套件](../../../../packages/experimental/forge-bundle/README.zh.md)把面板、forge 注册表、GitHub 提供方、绑定服务、工作树模型工具与面板使用的一个隔离 worktree 服务作为插件页中默认禁用的一个条目发布。 评审与工作树控件服务于同一个代码修改流程。统一插件入口让用户可以一次启用这些能力,无需根据底层包的拆分判断应该开启哪张卡片。包与两套工作树服务仍保持独立,分别负责会话开始前和对话中创建工作树的流程。 diff --git a/.agents/notes/implemented/feature/2026-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/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index adff87f633..fb625e0d85 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -1,29 +1,36 @@ /** - * Daily stale pull-request reminders for the `Stale pull requests` workflow. + * Daily stale pull-request reminders and closing for the `Stale pull requests` workflow. * * A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review * event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross - * references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow - * comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` - * and pull requests opened by bots receive no reminders. The workflow never closes pull requests. + * references, do not count, so reminder and closing comments never extend it. After 7 and 14 days without activity the + * workflow comments once per stage and mentions the author. After 21 days without activity, and at least 7 days after + * the 14-day reminder, it comments and closes the pull request; the reminder therefore always gives the author 7 days' + * notice, including for pull requests that were already inactive when the workflow started. Activity, including + * reopening, starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` and pull requests opened by bots are neither + * reminded nor closed. * * Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at` - * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently + * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` comments, least recently * updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed * pull request is reported and skipped. */ -/** Label that exempts a pull request from reminders. */ +/** Label that exempts a pull request from reminders and closing. */ export const EXEMPT_LABEL = 'DO_NOT_CLOSE' /** Days without activity after which each reminder is posted, in ascending order. */ export const REMINDER_DAYS = [7, 14] +/** Days without activity after which a pull request is closed. */ +export const CLOSE_DAYS = 21 + const DAY_MS = 24 * 60 * 60 * 1000 // GitHub asks integrations to wait at least one second between content-creating requests. const COMMENT_INTERVAL_MS = 1000 const MAX_COMMENTS_PER_RUN = 100 -const MARKER = // +// Reminders posted before closing existed use `stale-pr-reminder` and announce no closing, so they are ignored. +const MARKER = // // Review bots that use ordinary user accounts. const BOT_LOGINS = new Set(['ds-review-bot']) @@ -55,39 +62,46 @@ function activityTimes(event) { } /** - * Selects the reminder a pull request is due for. + * Selects the reminder or closing a pull request is due for. * @param {object} options * @param {string} options.createdAt Pull-request creation time. * @param {object[]} options.timeline Complete issue timeline of the pull request. * @param {Date} options.now Evaluation time. - * @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due. + * @returns {{ days: number, comment: boolean } | undefined} Due stage in days, `CLOSE_DAYS` for closing, and whether its + * comment is still unposted; `undefined` when nothing is due. A closing whose comment was posted but whose close failed + * is due again without a comment. */ -export function dueReminder({ createdAt, timeline, now }) { +export function dueStage({ createdAt, timeline, now }) { const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) const lastActivity = Math.max(...times) - const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) - if (due === undefined) return undefined const sent = timeline .filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity) - .map(event => Number(MARKER.exec(event.body ?? '')?.[1])) - return sent.some(days => days >= due) ? undefined : due + .map(event => ({ days: Number(MARKER.exec(event.body ?? '')?.[1]), at: Date.parse(event.created_at) })) + const finalReminder = REMINDER_DAYS.at(-1) + const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS + if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) { + return { days: CLOSE_DAYS, comment: !sent.some(({ days }) => days === CLOSE_DAYS) } + } + const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) + if (due === undefined || sent.some(({ days }) => days >= due)) return undefined + return { days: due, comment: true } } /** - * Builds the reminder comment. + * Builds the reminder or closing comment. * @param {string} author Pull-request author login. - * @param {number} days Reminder stage in days. + * @param {number} days Stage in days; `CLOSE_DAYS` builds the closing comment. * @returns {string} Comment body. */ -export function reminderBody(author, days) { - return [ - ``, - `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`, - ].join('\n') +export function stageBody(author, days) { + const text = days === CLOSE_DAYS + ? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.` + : `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.` + return `\n${text}` } /** - * Posts every due reminder on open pull requests of the workflow repository. + * Posts every due reminder and closes every due pull request among the open pull requests of the workflow repository. * @param {object} options * @param {object} options.github Authenticated Octokit client from `actions/github-script`. * @param {object} options.context Workflow context from `actions/github-script`. @@ -96,7 +110,7 @@ export function reminderBody(author, days) { * @param {(ms: number) => Promise} [options.sleep] Delay between comments. * @returns {Promise} */ -export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { +export async function processStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { const { owner, repo } = context.repo const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 }) let posted = 0 @@ -107,12 +121,16 @@ export async function remindStalePullRequests({ github, context, core, now = new if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue try { const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) - const days = dueReminder({ createdAt: pull.created_at, timeline, now }) - if (days === undefined) continue - if (posted > 0) await sleep(COMMENT_INTERVAL_MS) - await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) }) - posted++ - core.info(`#${pull.number}: posted the ${days}-day reminder`) + const stage = dueStage({ createdAt: pull.created_at, timeline, now }) + if (stage === undefined) continue + const { days } = stage + if (stage.comment) { + if (posted > 0) await sleep(COMMENT_INTERVAL_MS) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) + posted++ + } + if (days === CLOSE_DAYS) await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) + core.info(days === CLOSE_DAYS ? `#${pull.number}: closed after ${days} days without activity` : `#${pull.number}: posted the ${days}-day reminder`) } catch (error) { failed++ core.warning(`#${pull.number}: ${error.message}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index cb2d56b437..c6033e1fc5 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -1,47 +1,67 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs' +import { dueStage as dueAction, stageBody, processStalePullRequests } from './remind.mjs' const now = new Date('2026-11-30T00:00:00Z') const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() const human = { login: 'author', type: 'User' } const bot = { login: 'github-actions[bot]', type: 'Bot' } const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) -const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage)) +const reminder = (days, stage) => comment(bot, days, stageBody('author', stage)) +const dueStage = options => dueAction(options)?.days test('no reminder is due within 7 days of the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) }) test('the latest due stage is posted once after the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(7), timeline: [], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(17), timeline: [reminder(3, 14)], now }), undefined) +}) + +test('a pull request closes after 21 days without activity and 7 days after the 14-day reminder', () => { + assert.equal(dueStage({ createdAt: daysAgo(21), timeline: [reminder(14, 7), reminder(7, 14)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), 21) + // A pull request that was already inactive gets the 14-day reminder first and 7 days' notice. + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(6, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14) + // A 14-day reminder from before the last activity gives no notice. + assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14) + // Reminders posted before closing existed announce no closing. + const legacy = comment(bot, 10, '\n@author This pull request has had no activity for 14 days.') + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [legacy], now }), 14) +}) + +test('a closing whose comment was posted retries the close without another comment', () => { + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14)], now }), { days: 21, comment: true }) + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14), reminder(1, 21)], now }), { days: 21, comment: false }) }) test('human activity restarts the cycle and bot activity does not', () => { const sentBefore = [reminder(30, 7), reminder(23, 14)] - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reopened', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), 21) }) test('mentions, labels and cross references are not activity', () => { const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) }) // GitHub records a `mentioned` event for the author right after each reminder. - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) }) -test('reminders mention the author and skip exempt and bot-authored pull requests', async () => { +test('reminders and closing mention the author and skip exempt and bot-authored pull requests', async () => { const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides }) const pulls = [ pull(1), @@ -51,12 +71,21 @@ test('reminders mention the author and skip exempt and bot-authored pull request pull(4, { updated_at: daysAgo(1) }), pull(6), pull(5), + pull(7, { created_at: daysAgo(30) }), + pull(8, { created_at: daysAgo(30) }), ] const comments = [] + const closed = [] const timelines = [] const github = { rest: { - pulls: { list: 'pulls' }, + pulls: { + list: 'pulls', + update: async params => { + if (params.pull_number === 8) throw new Error('close failed') + closed.push(params) + }, + }, issues: { listEventsForTimeline: 'timeline', createComment: async params => { @@ -68,20 +97,23 @@ test('reminders mention the author and skip exempt and bot-authored pull request paginate: async (method, params) => { if (method === 'pulls') return pulls timelines.push(params.issue_number) - return [] + return [7, 8].includes(params.issue_number) ? [reminder(9, 14)] : [] }, } const sleeps = [] const warnings = [] const failures = [] const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) - assert.deepEqual(timelines, [1, 4, 6, 5]) - assert.deepEqual(warnings, ['#6: locked']) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) + assert.deepEqual(timelines, [1, 4, 6, 5, 7, 8]) + // A failed close after its comment is retried on the next run without another comment. + assert.deepEqual(warnings, ['#6: locked', '#8: close failed']) assert.equal(failures.length, 1) - assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5]) - assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) - assert.deepEqual(sleeps, [1000, 1000, 1000]) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7, 8]) + assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) + assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) + assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) + assert.deepEqual(sleeps, [1000, 1000, 1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => { @@ -91,6 +123,6 @@ test('a run posts at most 100 reminders', async () => { rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } }, paginate: async method => method === 'pulls' ? pulls : [], } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) assert.equal(comments, 100) }) diff --git a/.github/workflows/stale-pull-requests.yml b/.github/workflows/stale-pull-requests.yml index a0ccb7f2b5..db1c3f8115 100644 --- a/.github/workflows/stale-pull-requests.yml +++ b/.github/workflows/stale-pull-requests.yml @@ -1,4 +1,4 @@ -# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them. +# Reminds authors of open pull requests after 7 and 14 days without activity and closes them after 21 days. # Rules: .github/stale-pull-requests/remind.mjs. name: Stale pull requests @@ -16,7 +16,7 @@ concurrency: jobs: remind: - name: Remind stale pull requests + name: Remind and close stale pull requests runs-on: ubuntu-latest permissions: contents: read @@ -27,9 +27,9 @@ jobs: with: sparse-checkout: .github/stale-pull-requests persist-credentials: false - - name: Post due reminders + - name: Post due reminders and close stale pull requests uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 with: script: | - const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) - await remindStalePullRequests({ github, context, core }) + const { processStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) + await processStalePullRequests({ github, context, core }) diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index 6fcdd1ef28..36a6d68aab 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -143,9 +143,7 @@ function createProfileLifecycleFixture(): ProfileLifecycleFixture { writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n') const linkTarget = join(profileDir, 'node_modules', 'dsh-lifecycle-bundle') mkdirSync(join(profileDir, 'node_modules'), { recursive: true }) - try { - rmSync(linkTarget, { recursive: true, force: true }) - } catch { /* fresh dir */ } + rmSync(linkTarget, { recursive: true, force: true }) // Copy-free: a package.json redirecting via a relative main is enough for require.resolve. mkdirSync(linkTarget, { recursive: true }) for (const file of ['package.json', 'cordis.patch.yml', 'plugin.mjs']) { 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..9e3ec3e15c 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 @@ -8,7 +8,7 @@ {"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":"\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.\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."}]},"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"}}} 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..498fb3440a 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 @@ -8,7 +8,7 @@ {"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":"\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.\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."}]},"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"}}} 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/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 2a378530ab..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"') 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/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(/^ - + + + + + {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/index.ts b/packages/client/ui-agent-team/src/client/index.ts index 23de9e7ee5..08484146ff 100644 --- a/packages/client/ui-agent-team/src/client/index.ts +++ b/packages/client/ui-agent-team/src/client/index.ts @@ -4,7 +4,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import { registerAgentTeamUi } from './mount.ts' export { inject } from './mount.ts' -export type { TeamBoardProps } from './TeamBoard.tsx' +export type { TeamBoardProps, TeamProgressProps } from './TeamBoard.tsx' export type { TeamKey } from './locales.ts' /** diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts index f7bba69ff8..33fb6c330f 100644 --- a/packages/client/ui-agent-team/src/client/locales.ts +++ b/packages/client/ui-agent-team/src/client/locales.ts @@ -8,12 +8,14 @@ export const zh = { 'progress.completed': '{count} 已完成', 'progress.active': '{count} 进行中', 'progress.pending': '{count} 待处理', + 'list.more': '显示其余 {count} 个', + 'list.less': '收起', + 'list.foldName': '{label}(共享任务)', 'command.title': '智能体团队协作', 'command.running': '执行中', 'command.done': '已完成', 'command.failed': '执行失败', 'command.failedReason': '执行失败:{reason}', - trigger: '任务板', 'mode.label': '开启智能体团队协作', 'mode.on': '开启', 'mode.off': '关闭', @@ -32,6 +34,7 @@ export const zh = { tasks: '共享任务', owner: '负责人', unowned: '未分配', + 'hover.owner': '负责人:{name}', blocked: '被依赖阻塞', 'status.pending': '待处理', 'status.in_progress': '进行中', @@ -46,12 +49,14 @@ export const en = { 'progress.completed': '{count} completed', 'progress.active': '{count} in progress', 'progress.pending': '{count} pending', + 'list.more': 'Show {count} more', + 'list.less': 'Show less', + 'list.foldName': '{label} (shared tasks)', 'command.title': 'Agent teamwork', 'command.running': 'Running', 'command.done': 'Completed', 'command.failed': 'Failed', 'command.failedReason': 'Failed: {reason}', - trigger: 'Task board', 'mode.label': 'Enable agent teamwork', 'mode.on': 'On', 'mode.off': 'Off', @@ -70,6 +75,7 @@ export const en = { tasks: 'Shared tasks', owner: 'Owner', unowned: 'Unowned', + 'hover.owner': 'Owner: {name}', blocked: 'Blocked by dependencies', 'status.pending': 'Pending', 'status.in_progress': 'In progress', @@ -81,6 +87,9 @@ export const ja = { 'progress.completed': '{count}件完了', 'progress.active': '{count}件進行中', 'progress.pending': '{count}件保留中', + 'list.more': '残り{count}件を表示', + 'list.less': '折りたたむ', + 'list.foldName': '{label}(共有タスク)', 'command.title': 'エージェント連携', 'command.running': '実行中', 'command.done': '完了', @@ -97,7 +106,6 @@ export const ja = { 'disable.cancel': 'キャンセル', 'disable.confirm': '無効にする', 'disable.close': '閉じる', - 'trigger': 'タスクボード', 'loading': 'タスクボードを読み込み中…', 'unavailable': 'タスクボードは利用できません', 'failure': '保存されたタスクレコードが無効です: {message}', @@ -105,6 +113,7 @@ export const ja = { 'tasks': '共有タスク', 'owner': 'オーナー', 'unowned': 'オーナーなし', + 'hover.owner': '担当:{name}', 'blocked': '依存関係によりブロック中', 'status.pending': '保留中', 'status.in_progress': '進行中', @@ -116,6 +125,9 @@ export const es = { 'progress.completed': '{count} completado', 'progress.active': '{count} en progreso', 'progress.pending': '{count} pendiente', + 'list.more': 'Mostrar {count} más', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (tareas compartidas)', 'command.title': 'Colaboración entre agentes', 'command.running': 'En ejecución', 'command.done': 'Completado', @@ -132,7 +144,6 @@ export const es = { 'disable.cancel': 'Cancelar', 'disable.confirm': 'Confirmar desactivación', 'disable.close': 'Cerrar', - trigger: 'Tablero de tareas', loading: 'Cargando tablero de tareas…', unavailable: 'El tablero de tareas no está disponible', failure: 'Registro de tarea persistente no válido: {message}', @@ -140,6 +151,7 @@ export const es = { tasks: 'Tareas compartidas', owner: 'propietario', unowned: 'Sin dueño', + 'hover.owner': 'Responsable: {name}', blocked: 'Bloqueado por dependencias', 'status.pending': 'Pendiente', 'status.in_progress': 'En progreso', @@ -151,6 +163,9 @@ export const fr = { 'progress.completed': '{count} terminé', 'progress.active': '{count} en cours', 'progress.pending': '{count} en attente', + 'list.more': 'Afficher {count} de plus', + 'list.less': 'Afficher moins', + 'list.foldName': '{label} (tâches partagées)', 'command.title': 'Collaboration entre agents', 'command.running': 'En cours', 'command.done': 'Terminé', @@ -167,7 +182,6 @@ export const fr = { 'disable.cancel': 'Annuler', 'disable.confirm': 'Confirmer la désactivation', 'disable.close': 'Fermer', - trigger: 'Tableau des tâches', loading: 'Chargement du tableau des tâches…', unavailable: 'Le tableau des tâches n’est pas disponible', failure: 'Enregistrement de tâche persistant non valide : {message}', @@ -175,6 +189,7 @@ export const fr = { tasks: 'Tâches partagées', owner: 'Propriétaire', unowned: 'Sans propriétaire', + 'hover.owner': 'Responsable : {name}', blocked: 'Bloqué par les dépendances', 'status.pending': 'En attente', 'status.in_progress': 'En cours', @@ -186,6 +201,9 @@ export const de = { 'progress.completed': '{count} abgeschlossen', 'progress.active': '{count} in Bearbeitung', 'progress.pending': '{count} ausstehend', + 'list.more': '{count} weitere anzeigen', + 'list.less': 'Weniger anzeigen', + 'list.foldName': '{label} (geteilte Aufgaben)', 'command.title': 'Agentenzusammenarbeit', 'command.running': 'Wird ausgeführt', 'command.done': 'Abgeschlossen', @@ -202,7 +220,6 @@ export const de = { 'disable.cancel': 'Abbrechen', 'disable.confirm': 'Deaktivierung bestätigen', 'disable.close': 'Schließen', - trigger: 'Aufgabenübersicht', loading: 'Aufgabenübersicht wird geladen…', unavailable: 'Aufgabenübersicht ist nicht verfügbar', failure: 'Ungültiger gespeicherter Aufgabeneintrag: {message}', @@ -210,6 +227,7 @@ export const de = { tasks: 'Geteilte Aufgaben', owner: 'Besitzer', unowned: 'Unbesessen', + 'hover.owner': 'Zuständig: {name}', blocked: 'Blockiert durch Abhängigkeiten', 'status.pending': 'Ausstehend', 'status.in_progress': 'In Bearbeitung', @@ -221,6 +239,9 @@ export const ru = { 'progress.completed': '{count} завершено', 'progress.active': '{count} в процессе', 'progress.pending': '{count} в ожидании', + 'list.more': 'Показать ещё {count}', + 'list.less': 'Свернуть', + 'list.foldName': '{label} (общие задачи)', 'command.title': 'Совместная работа агентов', 'command.running': 'Выполняется', 'command.done': 'Завершено', @@ -237,7 +258,6 @@ export const ru = { 'disable.cancel': 'Отмена', 'disable.confirm': 'Подтвердить отключение', 'disable.close': 'Закрыть', - trigger: 'Доска задач', loading: 'Загрузка доски задач…', unavailable: 'Доска задач недоступна', failure: 'Недопустимая сохранённая запись задачи: {message}', @@ -245,6 +265,7 @@ export const ru = { tasks: 'Общие задачи', owner: 'Владелец', unowned: 'Невладеющий', + 'hover.owner': 'Ответственный: {name}', blocked: 'Заблокировано зависимостями', 'status.pending': 'Ожидается', 'status.in_progress': 'В процессе', @@ -256,6 +277,9 @@ export const pt = { 'progress.completed': '{count} concluído', 'progress.active': '{count} em andamento', 'progress.pending': '{count} pendente', + 'list.more': 'Mostrar mais {count}', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (tarefas compartilhadas)', 'command.title': 'Colaboração entre agentes', 'command.running': 'Em execução', 'command.done': 'Concluído', @@ -272,7 +296,6 @@ export const pt = { 'disable.cancel': 'Cancelar', 'disable.confirm': 'Confirmar desativação', 'disable.close': 'Fechar', - trigger: 'Quadro de tarefas', loading: 'Carregando quadro de tarefas…', unavailable: 'O quadro de tarefas não está disponível', failure: 'Registro de tarefa persistente inválido: {message}', @@ -280,6 +303,7 @@ export const pt = { tasks: 'Tarefas compartilhadas', owner: 'Proprietário', unowned: 'Sem dono', + 'hover.owner': 'Responsável: {name}', blocked: 'Bloqueado por dependências', 'status.pending': 'Pendente', 'status.in_progress': 'Em andamento', diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index c2dec89b0a..c84e653564 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -2,7 +2,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-api-session-controller/client' -import type {} from '@deepseek-ai/dsh-client-ui-subagent/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' @@ -12,7 +12,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx' import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from './TeamModeToggle.tsx' -import { TeamBoard } from './TeamBoard.tsx' +import { TeamBoard, TeamProgress } from './TeamBoard.tsx' +import { createTeamBoardStore } from './team-board-store.ts' import { TeamCommandRow } from './TeamCommandRow.tsx' import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts' @@ -27,12 +28,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { export const inject = ['slots', 'locale'] /** - * Register the task-board dictionaries and subagent catalog sections. - * The panel reads the root Session’s `agentTeam` projection through standard Session hooks. + * Register the task-board dictionaries and the Session panel's shared tasks section. + * The section reads the root Session’s `agentTeam` projection through standard Session hooks. * @param ctx - Client Context carrying the injected locale and slot services. */ export function registerAgentTeamUi(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'client-ui-agent-team: dictionaries') + const t = ctx.locale.bind(NS) ctx.slots.inject('conversation.chat.commandview', () => ctx.slots.register({ name: 'conversation.chat.commandview', key: 'team', locale: NS, }, TeamCommandRow)) @@ -68,7 +70,20 @@ export function registerAgentTeamUi(ctx: ClientContext): void { }, TeamModePane)) }) }) - ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'agent-team', locale: NS, - }, TeamBoard)) + ctx.slots.inject('conversation.session.panel.section', function* () { + yield ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'shared-tasks', + // After subagents (200), before background jobs (300). + order: 250, + label: () => t('tasks'), + locale: NS, + store: createTeamBoardStore(), + }, TeamBoard) + yield ctx.slots.register({ + name: 'conversation.session.panel.section.actions', + key: 'shared-tasks', + locale: NS, + }, TeamProgress) + }) } diff --git a/packages/client/ui-agent-team/src/client/team-board-store.ts b/packages/client/ui-agent-team/src/client/team-board-store.ts new file mode 100644 index 0000000000..312f7d72e4 --- /dev/null +++ b/packages/client/ui-agent-team/src/client/team-board-store.ts @@ -0,0 +1,38 @@ +/** + * Whether the user unfolded the shared tasks list of the Session panel. The + * registration declares it as an exclusive store, so each Session keeps its + * own while its scope is retained, across hiding and showing the panel. + */ + +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' + +/** The fold of one Session's shared tasks list. */ +export interface TeamBoardState { + /** Whether the list shows every task instead of holding back the tasks past its limit. */ + unfolded: boolean +} + +/** The shared tasks store's write set. */ +type TeamBoardActions = { + unfoldedSet: (draft: TeamBoardState, unfolded: boolean) => void +} + +/** + * Declare the shared tasks section's store. + * @returns the store handle to declare on the registration. + */ +export function createTeamBoardStore(): EngineStoreHandle { + return defineStore({ + init: (): TeamBoardState => ({ unfolded: false }), + actions: { + /** + * Record the user's choice to show every task or fold the list again. + * @param d - draft state. + * @param unfolded - whether the list now shows every task. + */ + unfoldedSet: (d, unfolded: boolean) => { + d.unfolded = unfolded + }, + }, + }) +} diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index 95011ef4cf..22def8176a 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -5,9 +5,10 @@ import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from '../src/client/TeamModeToggle.tsx' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import { TeamBoard } from '../src/client/TeamBoard.tsx' +import { TeamBoard, TeamProgress } from '../src/client/TeamBoard.tsx' import { TeamCommandRow } from '../src/client/TeamCommandRow.tsx' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected } from '../src/client/TeamDisableConfirmation.tsx' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { apply, inject } from '../src/client/index.ts' import { apply as nodeApply } from '../src/index.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -20,43 +21,52 @@ async function bench() { const collapseHeader = ctx.slots.register({ name: 'root', children: { - 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, 'conversation.input.model': { kind: 'single', scope: 'session' }, 'shell.overlay': { kind: 'list', scope: 'root' }, }, } as never, () => null) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() - const entry = () => ctx.slots.entries('conversation.session.header.actions.subagent.footer') + const entry = () => ctx.slots.entries('conversation.session.panel.section') .find(candidate => candidate.component === TeamBoard) - return { ctx, fiber, entry, collapseHeader } + const progress = () => ctx.slots.entries('conversation.session.panel.section.actions') + .find(candidate => candidate.component === TeamProgress) + return { ctx, fiber, entry, progress, collapseHeader } } describe('task-board browser plugin', () => { - it('registers a disposable root task-board section without navigation or Team Remote services', async () => { + it('registers a disposable shared tasks section with its progress, without navigation or Team Remote services', async () => { const b = await bench() expect(inject).toEqual(['slots', 'locale']) expect(b.entry()).toMatchObject({ - options: { id: 'agent-team' }, + options: { id: 'shared-tasks', order: 250 }, locale: 'agent-team', }) expect(b.entry()!.inject).toBeUndefined() + expect(resolveSlotLabel(b.entry()!.options.label)).toBe('Shared tasks') + expect(b.progress()).toMatchObject({ options: { key: 'shared-tasks' }, locale: 'agent-team' }) expect(b.ctx.slots.entries('conversation.session.header.actions')).toHaveLength(0) const t = b.ctx.locale.bind('agent-team') - expect(t('trigger')).toBe('Task board') + expect(t('tasks')).toBe('Shared tasks') await b.fiber.dispose() expect(b.entry()).toBeUndefined() + expect(b.progress()).toBeUndefined() expect(t('empty')).toBe('empty') }) - it('re-registers when the conversation header slot is declared again', async () => { + it('re-registers when the section slot is declared again', async () => { const b = await bench() expect(b.entry()).toBeDefined() b.collapseHeader() expect(b.entry()).toBeUndefined() b.ctx.slots.register({ name: 'root', - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, + children: { + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + }, } as never, () => null) await Promise.resolve() expect(b.entry()).toBeDefined() diff --git a/packages/client/ui-agent-team/tests/team-board.client.spec.tsx b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx index f60eb99e4a..7f81bcc470 100644 --- a/packages/client/ui-agent-team/tests/team-board.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx @@ -8,8 +8,10 @@ import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-sess import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import { TeamBoard, type TeamBoardProps } from '../src/client/TeamBoard.tsx' +import { TeamBoard, TeamProgress, type TeamBoardProps, type TeamProgressProps } from '../src/client/TeamBoard.tsx' +import { createTeamBoardStore } from '../src/client/team-board-store.ts' import { en, zh } from '../src/client/locales.ts' +import type { PanelDetailsProps, PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' afterEach(() => { cleanup() @@ -46,11 +48,35 @@ function summary(id: SessionId, title?: string): SessionSummary { } } +/** One Session's board store, as the registration mints it. */ +type BoardStore = ReturnType['create']> + +/** + * The Session panel's Factories as this suite renders them: the fold control as a button with its state, name, and + * label, and a row's details as one element per part in order. ui-session-panel's own suite owns their markup. + */ +function renderPanelFactory(name: string, input: object) { + if (name === 'conversation.session.panel.details') { + const { title, lines = [], status, facts = [] } = input as PanelDetailsProps + return ( +
+ {title !== undefined &&
{title}
} + {lines.map(line =>
{line}
)} + {status !== undefined &&
{status.label}
} + {facts.length > 0 &&
{facts.map(fact => {fact.label})}
} +
+ ) + } + const fold = input as PanelFoldProps + return +} + function bench(options: { projections?: Projections sessionId?: SessionId byId?: Record value?: TeamProjection + store?: BoardStore } = {}) { const sessionId = options.sessionId ?? SESSION const byId = options.byId ?? { [SESSION]: summary(SESSION) } @@ -63,12 +89,14 @@ function bench(options: { const value = state.projectionsBySession[sessionId]?.values.agentTeam return selector === undefined ? value : selector(value) })) as TeamBoardProps['useProjection'] + const store = options.store ?? createTeamBoardStore().create() const props = { sessionId, useProjection, useSessions: bindSnapshotSelector(sessions), + useStore: bindSnapshotSelector(store), actions: store.actions, renderFactorySlot: renderPanelFactory, t: makeTranslate(zh, commonZh), } as TeamBoardProps - return { props, sessions } + return { props, sessions, store } } function setProjectionSnapshot( @@ -108,14 +136,20 @@ function enableTooltips(): void { vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) } +/** The text the progress beside the section title renders for these props. */ +function progressText(props: TeamBoardProps): string { + const progress: Pick = { useProjection: props.useProjection, t: props.t } + const view = render() + const text = view.container.textContent + view.unmount() + return text +} + describe('TeamBoard', () => { - it('shows a nonclickable Checklist header and compact initially closed rows', () => { + it('leaves the title to the panel and shows compact initially closed rows', () => { const b = bench() render() - const heading = screen.getByRole('heading') - expect(heading.textContent).toBe(`${zh.tasks}${b.props.t('progress.active', { count: 1 })}`) - expect(heading.querySelector('button')).toBeNull() - expect(heading.querySelector('[data-icon="dsw-icon-checklist-outline-regular"]')).toBeTruthy() + expect(screen.queryByRole('heading')).toBeNull() expect(screen.getAllByRole('button')).toEqual([row()]) expect(row().getAttribute('aria-expanded')).toBe('false') expect(row().textContent).toBe(task.subject) @@ -163,7 +197,7 @@ describe('TeamBoard', () => { expect(screen.getAllByRole('button').every(button => button.getAttribute('aria-expanded') === 'false')).toBe(true) }) - it('preserves source order, keeps completed tasks, and excludes deleted tombstones from rows and counts', () => { + it('lists tasks in progress, then pending, then completed, and excludes deleted tombstones from rows and counts', () => { const b = bench({ value: { ...team, tasks: [ { ...task, subject: 'Pending first', status: 'pending', ready: true }, { ...task, id: TASK_2, subject: 'Completed second', status: 'completed' }, @@ -171,10 +205,10 @@ describe('TeamBoard', () => { { ...task, id: 'deleted' as TeamTaskId, subject: 'Deleted task', status: 'deleted' }, ] } }) render() - expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Pending first', 'Completed second', 'Active third']) - expect(screen.getByRole('heading').textContent).toBe(`${zh.tasks}${[ + expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Active third', 'Pending first', 'Completed second']) + expect(progressText(b.props)).toBe([ b.props.t('progress.completed', { count: 1 }), b.props.t('progress.active', { count: 1 }), b.props.t('progress.pending', { count: 1 }), - ].join('\u2002·\u2002')}`) + ].join('\u2002·\u2002')) expect(screen.queryByText('Deleted task')).toBeNull() expect(row('Pending first').querySelector('[data-state="idle"]')).toBeTruthy() expect(row('Completed second').querySelector('[data-state="done"]')).toBeTruthy() @@ -184,6 +218,65 @@ describe('TeamBoard', () => { expect(screen.getByText(task.description)).toBeTruthy() }) + /** A task named by its id. */ + const named = (id: string, status: TeamTask['status']): TeamTask => ({ ...task, id: id as TeamTaskId, subject: id, status, ready: true }) + /** The task rows' names in display order. */ + const shownTasks = (): (string | null)[] => [...document.querySelectorAll('[data-team-task]')].map(item => item.getAttribute('data-team-task')) + const fold = (): HTMLElement | null => document.querySelector('[data-fold]') + + it('keeps source order within the tasks in progress and the pending ones, and lists the latest completed task first', () => { + const b = bench({ value: { ...team, tasks: [ + named('done-1', 'completed'), named('wait-1', 'pending'), named('run-1', 'in_progress'), named('done-2', 'completed'), + named('wait-2', 'pending'), named('run-2', 'in_progress'), + ] } }) + render() + expect(shownTasks()).toEqual(['run-1', 'run-2', 'wait-1', 'wait-2', 'done-2', 'done-1']) + // Six tasks show in full: folding would hold back one task for a control that takes a row itself. + expect(fold()).toBeNull() + }) + + it('holds two tasks back from seven, behind a fold control that shows them and folds again', () => { + const tasks = [ + named('done-1', 'completed'), named('done-2', 'completed'), named('run-1', 'in_progress'), named('wait-1', 'pending'), + named('wait-2', 'pending'), named('wait-3', 'pending'), named('wait-4', 'pending'), + ] + const b = bench({ value: { ...team, tasks } }) + render() + expect(shownTasks()).toEqual(['run-1', 'wait-1', 'wait-2', 'wait-3', 'wait-4']) + const control = fold() as HTMLElement + expect([control.textContent, control.getAttribute('aria-label'), control.getAttribute('aria-expanded')]) + .toEqual(['显示其余 2 个', '显示其余 2 个(共享任务)', 'false']) + // The control follows the list instead of joining it, so the list holds only tasks. + expect(screen.getByRole('list').contains(control)).toBe(false) + fireEvent.click(control) + expect(shownTasks()).toEqual(['run-1', 'wait-1', 'wait-2', 'wait-3', 'wait-4', 'done-2', 'done-1']) + expect([fold()?.textContent, fold()?.getAttribute('aria-label'), fold()?.getAttribute('aria-expanded')]).toEqual(['收起', '收起(共享任务)', 'true']) + fireEvent.click(fold() as HTMLElement) + expect(shownTasks()).toHaveLength(5) + // The progress beside the title counts every task, shown or held back. + expect(progressText(b.props)).toBe([ + b.props.t('progress.completed', { count: 2 }), b.props.t('progress.active', { count: 1 }), b.props.t('progress.pending', { count: 4 }), + ].join('\u2002·\u2002')) + }) + + it('keeps the fold in the Session store while the section is unmounted', () => { + const store = createTeamBoardStore().create() + const tasks = Array.from({ length: 8 }, (_, index) => named(`wait-${index}`, 'pending')) + const first = render() + fireEvent.click(fold() as HTMLElement) + expect(store.getSnapshot()).toEqual({ unfolded: true }) + first.unmount() + render() + expect(shownTasks()).toHaveLength(8) + expect(fold()?.getAttribute('aria-expanded')).toBe('true') + }) + + it.each(Object.entries({ zh, en }))('names the fold control with its visible text first in %s', (_locale, copy) => { + for (const label of [copy['list.more'].replace('{count}', '3'), copy['list.less']]) { + expect(copy['list.foldName'].replace('{label}', label).startsWith(label)).toBe(true) + } + }) + it('announces blocked status without displaying readiness, dependencies, scopes, warnings, or task ids', () => { const { ownerId: _ownerId, ownerName: _ownerName, ...unowned } = task const b = bench({ value: { ...team, tasks: [ @@ -244,6 +337,7 @@ describe('TeamBoard', () => { const b = bench() render() setProjection(b.sessions, SESSION, { ...team, enabled: false }) + expect(progressText(b.props)).toBe('') expect(screen.queryByRole('region')).toBeNull() expect(screen.queryByText(task.subject)).toBeNull() setProjection(b.sessions, SESSION, team) @@ -283,7 +377,6 @@ describe('TeamBoard', () => { const view = render() expect(screen.getByRole('alert').textContent).toBe('任务记录无效:revision is not contiguous') expect(row()).toBeTruthy() - expect(screen.getByRole('heading')).toBeTruthy() for (const tasks of [[], [{ ...task, status: 'deleted' as const }]]) { setProjectionSnapshot(b.sessions, SESSION, { state: 'ready', error: null, values: { agentTeam: { enabled: true, tasks, failure: 'invalid task' }, @@ -293,11 +386,8 @@ describe('TeamBoard', () => { expect(alert.textContent).toBe('任务记录无效:invalid task') expect(screen.getAllByRole('alert')).toHaveLength(1) expect(view.container.textContent).toBe(alert.textContent) - expect(view.container.querySelector('[data-with-members="true"]')).toBeNull() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByRole('region')).toBeNull() expect(screen.queryByText(zh.empty)).toBeNull() - expect(document.querySelector('[data-team-panel]')).toBeNull() + expect(progressText(b.props)).toBe('') } setProjection(b.sessions, SESSION, { enabled: false, tasks: [], failure: 'invalid task' }) expect(view.container.childElementCount).toBe(0) @@ -334,7 +424,7 @@ describe('TeamBoard', () => { it('uses translated English progress and details without Show more or Show less controls', () => { const b = bench() render() - expect(screen.getByRole('heading').textContent).toBe(`${en.tasks}${makeTranslate(en)('progress.active', { count: 1 })}`) + expect(progressText({ ...b.props, t: makeTranslate(en) })).toBe(makeTranslate(en)('progress.active', { count: 1 })) fireEvent.click(row()) expect(ownerValue()).toBe('lead') expect(document.querySelector('[data-team-task-owner]')?.textContent).toBe(`${en.owner}: lead`) @@ -374,36 +464,28 @@ describe('TeamBoard', () => { expect(ownerValue()).toBeNull() }) - it('delays clipped collapsed subject hover by 500ms while keeping keyboard focus immediate', () => { + it('shows the subject, owner, description, and state in a hover card after 500ms, and none while the row is expanded', () => { vi.useFakeTimers() - enableTooltips() - const view = render() + vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' }))) + render() const button = row() - const subject = screen.getByText(task.subject) - const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockReturnValue(80) - vi.spyOn(Element.prototype, 'clientWidth', 'get').mockReturnValue(80) - fireEvent.pointerEnter(button) - act(() => { vi.advanceTimersByTime(500) }) - expect(screen.queryByRole('tooltip')).toBeNull() - fireEvent.pointerLeave(button) - scrollWidth.mockImplementation(function (this: Element) { return this === subject ? 180 : 80 }) - fireEvent.pointerEnter(button) + const anchor = button.parentElement as HTMLElement + const details = (): string[] | null => { + const card = document.querySelector('[data-session-panel-details]') + return card === null ? null : [...card.children].map(child => child.textContent ?? '') + } + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) act(() => { vi.advanceTimersByTime(499) }) - expect(screen.queryByRole('tooltip')).toBeNull() + expect(details()).toBeNull() act(() => { vi.advanceTimersByTime(1) }) - expect(screen.getByRole('tooltip').textContent).toBe(task.subject) - expect(view.container.contains(screen.getByRole('tooltip'))).toBe(false) + expect(details()).toEqual([task.subject, '负责人:lead', task.description, '进行中']) + // Expanding the row shows the same details in place, so the card closes and stays closed. fireEvent.click(button) - expect(row()).toBe(button) - expect(screen.queryByRole('tooltip')).toBeNull() - fireEvent.pointerLeave(button) - fireEvent.pointerEnter(button) + act(() => { vi.advanceTimersByTime(200) }) + expect(details()).toBeNull() + fireEvent.pointerLeave(anchor, { pointerType: 'mouse' }) + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) act(() => { vi.advanceTimersByTime(500) }) - expect(screen.queryByRole('tooltip')).toBeNull() - fireEvent.click(button) - fireEvent.pointerLeave(button) - fireEvent.keyDown(document.body, { key: 'Tab' }) - fireEvent.focus(button) - expect(screen.getByRole('tooltip').textContent).toBe(task.subject) + expect(details()).toBeNull() }) }) diff --git a/packages/client/ui-agent-team/tsconfig.json b/packages/client/ui-agent-team/tsconfig.json index 429b9adac3..b5d6224ca9 100644 --- a/packages/client/ui-agent-team/tsconfig.json +++ b/packages/client/ui-agent-team/tsconfig.json @@ -13,7 +13,7 @@ { "path": "../ui-model-selection" }, { "path": "../ui-layout" }, { "path": "../../core/agent" }, - { "path": "../ui-subagent" }, + { "path": "../ui-session-panel" }, { "path": "../locale/tsconfig.client.json" }, { "path": "../store" }, { "path": "../ui-conversation/tsconfig.client.json" }, diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index a986f761c4..ae1adac098 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -39,8 +39,8 @@ en: f6d8bbae13a1a8f8 zh: 96c8f400c215e33d /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: 1b12aa6c505dde3b - zh: 88e1654dd63816d7 + en: 596c30d730cdbce7 + zh: 6009f248a3b9d39f /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 70921859ae..84e81d7c62 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -158,7 +158,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. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail sits at the scrollport's start edge, which leaves the end gutter to the [Session panel](../ui-session-panel/README.md), and its previews open toward the transcript. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. + +The `conversation.chat.aside` slot holds one Session-level occupant beside the transcript, such as the [Session panel](../ui-session-panel/README.md). Every Chat View occurrence, main or embedded, renders it in a zero-height layer at the top of the Chat frame, positioned like the turn rail, so it stays in place while the transcript scrolls and inherits `--dsh-composer-height` and `--dsh-conversation-viewport-height` from the shared scrollport. The layer stacks above the turn rail and the back-to-bottom button and passes pointer events through. The layer measures nothing: its stylesheet publishes the end gutter, the inline space between the centered transcript column and the frame's end edge, as the `--dsh-chat-aside-gutter` custom property, `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`. The percentage resolves against the layer in the inline sizes of an element whose containing block is the layer, so an occupant sizes and places itself in CSS, and the Chat View neither re-renders nor observes sizes for it. The transcript root uses `overflow-x: visible; overflow-y: clip`: vertical overflow is clipped without creating a scroll container. Sticky Markdown code banners and expanded compaction headers therefore retain the actual conversation scrollport as their reference when no nearer scrolling ancestor exists. Capped process groups and terminal sections keep their own scrollports. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index d50ba90f91..6243b9825a 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -158,7 +158,9 @@ Chat 等待初始历史就绪后,才允许自动内容、滚动或尺寸更新 Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及到达底部(容许小于 1px 的取整误差)的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。采用完成时收起时,提交正文输入或 steering 会立即恢复跟随底部,并清除先前待处理的读者滚动采样。采用下次消息时收起时,没有折叠批次承载的正文输入用一次原生动画落到底部;steering 在两种时机下都立即落到底部,因为运行中的 Turn 仍在其回显上方持续输出。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 -轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 +轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。轮次轨道贴在滚动容器的起始边,把末端留白让给[会话面板](../ui-session-panel/README.zh.md),预览朝正文方向弹出。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 + +`conversation.chat.aside` slot 放一个位于正文旁边、面向整个会话的组件,例如[会话面板](../ui-session-panel/README.zh.md)。每个 Chat 视图实例(主正文区或嵌入的)都会渲染它:它位于 Chat 外框顶部的零高度图层中,定位方式与轮次轨道相同,因此不随正文滚动,并从共享滚动容器继承 `--dsh-composer-height` 与 `--dsh-conversation-viewport-height`。该图层叠在轮次轨道与回到底部按钮之上,自身不拦截指针事件。图层不做任何测量:它的样式表把末端留白(居中的正文列到外框末端边缘之间的行向空间)发布为自定义属性 `--dsh-chat-aside-gutter`,值为 `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`。其中的百分比在以该图层为包含块的元素的行向尺寸里按图层宽度解析,因此占位组件用 CSS 决定自身的尺寸与位置,Chat 视图既不为它重新渲染,也不为它观察尺寸。 正文根节点使用 `overflow-x: visible; overflow-y: clip`:裁剪纵向溢出,但不创建滚动容器。因此,在没有更近的滚动祖先时,Markdown 代码块的 sticky 头栏和展开的压缩摘要头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。 diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 7e4a3a5f01..56bb503a9a 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -245,6 +245,7 @@ export function apply(ctx: Context): void { 'conversation.chat.flow': { kind: 'single', scope: 'session', inject: CHAT_FLOW_INJECT }, 'conversation.chat.text-interaction': { kind: 'keyed', scope: 'session' }, 'conversation.chat.markdown.fence': { kind: 'hoc', scope: 'session' }, + 'conversation.chat.aside': { kind: 'single', scope: 'session' }, }, store: chatStore, inject: (sessionId: SessionId): ChatViewInjected => { diff --git a/packages/client/ui-chat/src/client/chat/ChatAside.tsx b/packages/client/ui-chat/src/client/chat/ChatAside.tsx new file mode 100644 index 0000000000..1e314c8d41 --- /dev/null +++ b/packages/client/ui-chat/src/client/chat/ChatAside.tsx @@ -0,0 +1,15 @@ +/** The Chat View's aside layer: one Session-level occupant beside the transcript, which the layer's stylesheet tells the end gutter. */ +import { memo } from 'react' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import css from './ChatView.module.css' + +/** + * Render the aside layer with its occupant. The Chat View's `renderSlot` is + * stable per registration, so the layer renders once and transcript updates + * do not re-render it; its geometry is CSS only. + * @param props - the Chat View's slot renderer. + * @returns the zero-height aside layer. + */ +export const ChatAside = memo(function ChatAside({ renderSlot }: Pick, 'renderSlot'>) { + return
{renderSlot('conversation.chat.aside', {})}
+}) diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 1f84e97842..520b899f08 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -356,6 +356,30 @@ /* Floating controls sit outside the clipped transcript. A standalone Chat anchors them to its frame; the shared host supplies the sticky scrollport. */ +/* The aside layer: zero height at the frame's top, sticky in a shared + scrollport so its occupant stays put while the transcript scrolls and + inherits the scrollport's --dsh-composer-height and + --dsh-conversation-viewport-height. Above the turn rail (7) and the + back-to-bottom control (8). It publishes the end gutter, the inline space + between the centered transcript column and the frame's end edge, for the + occupant's inline sizes: the percentage resolves against the layer in an + element whose containing block is the layer, as it does in the + back-to-bottom control's padding below. */ +.asideSlot { + position: absolute; + top: 0; + right: 0; + left: 0; + z-index: 9; + height: 0; + pointer-events: none; + --dsh-chat-aside-gutter: max(0px, calc((100% - var(--dsh-chat-content-width, 100%)) / 2)); +} + +:global([data-conversation-scroll]) .asideSlot { + position: sticky; +} + .toBottomSlot { position: absolute; right: 0; diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index c9143248a1..2c361fa35e 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} /> )} +
- & 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/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-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 311679176c..ed04662097 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -500,12 +500,17 @@ function makeHarness( return renderUserContent(owner as UserContentInput, renderImages, props.t) } const fenceCalls: { owner: MarkdownDelegateFenceInfo; entryKey: string | undefined }[] = [] + const asideRenders = { count: 0 } const renderSlot = ( key: string, owner: ChatFlowOwnerProps | MarkdownDelegateFenceInfo, opts: Parameters[2] & { entryKey?: string; children?: React.ReactNode }, ) => { if (key === 'conversation.chat.text-interaction') return null + if (key === 'conversation.chat.aside') { + asideRenders.count += 1 + return + } if (key === 'conversation.chat.markdown.fence' && 'lang' in owner) { fenceCalls.push({ owner, entryKey: opts.entryKey }) return opts.children ?? null @@ -608,7 +613,7 @@ function makeHarness( setConnection: (state: ConnectionState) => { connection.set(state) }, openFile, openUserFile, loadOlder, consumeOlder, prepareOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, - chatScroll, forkAt, toolOwners, fenceCalls, + chatScroll, forkAt, toolOwners, fenceCalls, asideRenders, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, setGrouped: (value: ConversationGroupedView | undefined) => { grouped = value @@ -763,7 +768,7 @@ describe('Chat node rendering', () => { const { getTriggerProps } = useMarkdownDelegate() return <>{targets.map((target, index) => )} } - const view = render( } />) + const view = render( key === 'conversation.chat.aside' ? null : } />) directory = '/workspace/moved' for (const [index, target] of targets.entries()) { const button = view.getByRole('button', { name: String(index) }) @@ -863,6 +868,26 @@ describe('Chat node rendering', () => { }) describe('ChatView', () => { + it('renders the aside once in a layer at the top of the Chat frame, which observes no sizes', () => { + const observed: Element[] = [] + vi.stubGlobal('ResizeObserver', class { + observe(target: Element): void { observed.push(target) } + unobserve(): void {} + disconnect(): void {} + }) + const h = makeHarness({}, {}, chatSnapshotFixture({ nodes: [user(1, 'hello')] })) + const view = render() + const frame = view.container.firstElementChild as HTMLElement + const layer = frame.querySelector('[data-chat-aside]') as HTMLElement + expect(layer.parentElement).toBe(frame) + expect(layer.querySelector('[data-chat-aside-probe]')).not.toBeNull() + // The layer's stylesheet publishes the gutter; the layer itself measures nothing. + expect(observed).not.toContain(layer) + // Transcript updates do not re-render the aside. + act(() => { h.setSession({ running: true }) }) + expect(h.asideRenders.count).toBe(1) + }) + it('renders only referenced Nodes without deleting unreferenced Node data', () => { const snapshot = chatSnapshotFixture({ nodes: [user(1, 'included'), user(2, 'omitted')] }) const h = makeHarness({}, {}, snapshot) @@ -4922,7 +4947,7 @@ it('formats Portuguese elapsed minutes with numeric units', () => { it('does not infer menu targets from links or data attributes inside a plugin flow slot', () => { const h = makeHarness() const custom = vi.fn() - const view = render( <> + const view = render( key === 'conversation.chat.aside' ? null : <> Plugin link + + }> +

{body}

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

{resolveText(entry.copy.title)}

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

{resolveText(display.detail)}

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

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

+ )} +

{resolveText(entry.copy.hint)}

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

{resolveText(activation.body)}

+
+ ) +} + +/** + * The `shell.overlay` entry: account outcomes reported outside the Plugins panel's lifetime. + * @param props - the face and the translator. + * @returns the toast for the latest notice, or null. + */ +export function ConnectorAccountToastEntry({ useConnectorAccounts, resolveText, dismissNotice, t }: FaceProps): ReactNode { + const notice = useConnectorAccounts(state => state.notice) + if (notice === undefined) return null + return notice.kind === 'action-failed' + ? } onDone={dismissNotice} /> + : +} diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts new file mode 100644 index 0000000000..e0e30d6285 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -0,0 +1,91 @@ +/** + * Connector account surfaces, browser half: follows the accounts CLI app plugins and MCP connectors register on the Host, + * and shows each bundle's section, title tag, and activation prompt on its Plugins page, with the notices of the + * operations this browser started. The surfaces read the shared copy from this package's dictionary and each + * registrant's text from the Host. + */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from './components.tsx' +import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' +import { BrowserAccounts } from './state.ts' +import type { ConnectorAccountFace } from './types.ts' + +export type { ConnectorAccountKey } from './locales.ts' +export type { + ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace, +} from './types.ts' + +/** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ +export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] + +function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { + const bundle = { ...face, account } + const dispose = ctx.effect(function* () { + yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountSectionEntry)) + yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountActivationEntry)) + }, `connector-account: ${packageName}`) + return () => void dispose() +} + +/** + * Show the registered connector accounts for one plugin lifetime: one tag and one notice entry for the page, and a + * section and activation prompt for each bundle that owns an account. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') + const remote = ctx.remote.connectorAccounts + const browser = new BrowserAccounts(ctx, remote) + ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') + const face: ConnectorAccountFace = { + hooks: { connectorAccounts: browser.state }, + start: (key, operation) => remote.start(key, operation), + cancel: (key, id) => remote.cancel(key, id), + resolveText: text => ctx.locale.resolveText(text), + follow: (key, id) => { browser.follow(key, id) }, + failed: () => { browser.failed() }, + dismissNotice: () => { browser.dismissNotice() }, + } + ctx.effect(function* () { + yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: 'connector-account.badge', locale: NS, inject: () => face, + }, ConnectorAccountBadgeEntry)) + yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'connector-account.notice', locale: NS, inject: () => face, + }, ConnectorAccountToastEntry)) + }, 'connector-account: page surfaces') + ctx.effect(() => { + const shown = new Map void }>() + const sync = (): void => { + const owned = new Map() + for (const entry of browser.state.getSnapshot().accounts.values()) { + if (entry.packageName !== undefined) owned.set(entry.packageName, entry.key) + } + for (const [packageName, surfaces] of shown) { + if (owned.get(packageName) === surfaces.account) continue + surfaces.withdraw() + shown.delete(packageName) + } + for (const [packageName, account] of owned) { + if (!shown.has(packageName)) shown.set(packageName, { account, withdraw: registerBundle(ctx, face, packageName, account) }) + } + } + sync() + const stop = browser.state.subscribe(sync) + return () => { + stop() + for (const surfaces of shown.values()) surfaces.withdraw() + } + }, 'connector-account: bundle surfaces') +} diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts new file mode 100644 index 0000000000..c0a30b7555 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -0,0 +1,86 @@ +/** Locale-owned copy the connector account surfaces share; each registrant's own text arrives from the Host. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace of the shared account copy. */ +export const NS = 'connectorAccount' + +/** Chinese dictionary and key source. */ +export const zh = { + close: '关闭', + 'action.cancel': '取消', + 'activation.later': '稍后', + 'failure.details': '排障信息:{details}', + 'notice.action-failed': '操作未完成,请重试', +} + +/** Every key the shared account surfaces translate. */ +export type ConnectorAccountKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + close: 'Close', + 'action.cancel': 'Cancel', + 'activation.later': 'Later', + 'failure.details': 'Diagnostic: {details}', + 'notice.action-failed': 'The action did not finish. Try again.', +} + +/** Japanese dictionary. */ +export const ja: Record = { + close: '閉じる', + 'action.cancel': 'キャンセル', + 'activation.later': '後で', + 'failure.details': '診断情報:{details}', + 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', +} + +/** Spanish dictionary. */ +export const es: Record = { + close: 'Cerrar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Más tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', +} + +/** French dictionary. */ +export const fr: Record = { + close: 'Fermer', + 'action.cancel': 'Annuler', + 'activation.later': 'Plus tard', + 'failure.details': 'Diagnostic : {details}', + 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', +} + +/** German dictionary. */ +export const de: Record = { + close: 'Schließen', + 'action.cancel': 'Abbrechen', + 'activation.later': 'Später', + 'failure.details': 'Diagnose: {details}', + 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', +} + +/** Russian dictionary. */ +export const ru: Record = { + close: 'Закрыть', + 'action.cancel': 'Отмена', + 'activation.later': 'Позже', + 'failure.details': 'Диагностика: {details}', + 'notice.action-failed': 'Действие не завершено. Повторите попытку.', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + close: 'Fechar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Mais tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + connectorAccount: ConnectorAccountKey + } +} diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts new file mode 100644 index 0000000000..7a061d98dc --- /dev/null +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -0,0 +1,142 @@ +/** + * The page's one subscription to the registered accounts, and what only this browser knows about them: the operations + * it started, whose authorization pages open here, and the notice to show. + */ +import type { Context } from '@deepseek-ai/cordis' +import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsState } from './types.ts' + +const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) + +/** + * Open an authorization page in a new tab when it is HTTPS, or HTTP on a loopback address such as a local + * authorization server. + * @param url - the page an operation waits on; other values open nothing. + */ +export function openAuthorizationPage(url: string | undefined): void { + if (url === undefined || !URL.canParse(url)) return + const parsed = new URL(url) + if (parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))) { + window.open(url, '_blank', 'noopener,noreferrer') + } +} + +/** One Host subscription per browser, shared by every account surface on the page. */ +export class BrowserAccounts { + /** The accounts, stream state, and notice every surface on the page reads. */ + readonly state: SnapshotStore = createSnapshotStore({ + accounts: new Map(), linked: true, notice: undefined, + }) + + /** + * The operation each account's latest start in this browser returned, with the pages already opened for it. It lasts + * until the stream delivers its result or the account leaves. + */ + private readonly followed = new Map }>() + private seq = 0 + private disposed = false + private readonly stream: RemoteStream + private readonly observing: Promise + + /** + * @param ctx - the browser context carrying the Remote client. + * @param remote - the `connectorAccounts` Remote. + */ + constructor(private readonly ctx: Context, remote: Pick) { + this.stream = ctx.remote.$stream({ + name: 'Connector accounts', open: signal => remote.watch(signal), + ended: () => new Error('Connector accounts stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe() + } + + /** + * Follow an operation this browser started, replacing the account's previous one. + * @param key - the account key. + * @param id - the operation the Host started. + */ + follow(key: string, id: ConnectorOperationId): void { + if (this.disposed) return + this.followed.set(key, { id, opened: new Set() }) + // The stream may have delivered the operation before the start call answered. + const entry = this.state.getSnapshot().accounts.get(key) + if (entry !== undefined) this.track(entry) + } + + /** Report that a Remote call this browser made did not finish; the Host keeps the diagnostic. */ + failed(): void { + this.notify({ kind: 'action-failed' }) + } + + /** Clear the notice once it has been shown. */ + dismissNotice(): void { + this.patch({ notice: undefined }) + } + + /** + * Stop observing the Host; afterwards the page opens no page and reports nothing more. Host-owned operations keep + * running. + * @returns after the stream closes. + */ + async dispose(): Promise { + this.disposed = true + await this.stream.dispose() + await this.observing + } + + private async observe(): Promise { + try { + for await (const item of this.stream) { + // An item the stream yielded just before disposal must not reach the disposed page. + if (this.disposed) return + this.show(item.value.accounts) + item.accept() + } + } catch (error) { + // A terminal failure, such as a Host without the registry, leaves the buttons disabled until the page reloads. + if (this.disposed) return + this.patch({ linked: false }) + this.ctx.logger.warn('connector accounts stream failed; reload the page to reconnect: %s', error) + } + } + + private show(entries: readonly ConnectorAccountEntry[]): void { + const accounts = new Map(entries.map(entry => [entry.key, entry])) + for (const key of [...this.followed.keys()]) if (!accounts.has(key)) this.followed.delete(key) + this.patch({ accounts, linked: true }) + for (const entry of entries) this.track(entry) + } + + /** Open each new page of the account's followed operation once, and report its success once its result arrives. */ + private track(entry: ConnectorAccountEntry): void { + const followed = this.followed.get(entry.key) + if (followed === undefined) return + const url = entry.operation?.id === followed.id ? entry.operation.authorizationUrl : undefined + if (url !== undefined && !followed.opened.has(url)) { + followed.opened.add(url) + openAuthorizationPage(url) + } + const result = entry.result + if (result?.id !== followed.id) return + this.followed.delete(entry.key) + if (result.notice !== undefined) this.notify({ kind: 'succeeded', text: result.notice }) + } + + private notify( + notice: { readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly kind: 'action-failed' }, + ): void { + if (this.disposed) return + this.seq += 1 + const next: ConnectorAccountNotice = { ...notice, seq: this.seq } + this.patch({ notice: next }) + } + + private patch(change: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...change }) + } +} diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts new file mode 100644 index 0000000000..afff7bc9ad --- /dev/null +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -0,0 +1,44 @@ +/** Browser-side state and face of the accounts the Plugins page shows. */ +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorOperationId } from '../types.ts' + +/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ +export type ConnectorAccountNotice = + | { readonly seq: number; readonly kind: 'succeeded'; readonly text: LocalizedText } + | { readonly seq: number; readonly kind: 'action-failed' } + +/** What this browser shows: the Host's accounts, the stream state, and the latest notice. */ +export interface ConnectorAccountsState { + /** Registered accounts by key, as the Host last published them. */ + readonly accounts: ReadonlyMap + /** Whether the Host stream is delivering. */ + readonly linked: boolean + readonly notice: ConnectorAccountNotice | undefined +} + +/** The face every surface entry injects. */ +export interface ConnectorAccountFace { + hooks: { connectorAccounts: HostObservable } + /** + * Start an operation of an account on the Host. The Remote result carries the operation the Host started, or the + * failure when the Host refuses or the call does not answer. + */ + readonly start: ClientRemote['connectorAccounts']['start'] + /** Cancel an account's operation on the Host; the Remote result carries a failure like `start`. */ + readonly cancel: ClientRemote['connectorAccounts']['cancel'] + /** Pick the active language's entry of a registrant's text. */ + readonly resolveText: (text: LocalizedText) => string + /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ + readonly follow: (key: string, id: ConnectorOperationId) => void + /** Report that a Remote call this browser made did not finish. */ + readonly failed: () => void + readonly dismissNotice: () => void +} + +/** The face of a bundle's own surfaces, which show the bundle's account. */ +export interface ConnectorBundleAccountFace extends ConnectorAccountFace { + /** The key of the account the bundle owns. */ + readonly account: string +} diff --git a/packages/client/ui-connector-account/src/css-modules.d.ts b/packages/client/ui-connector-account/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-connector-account/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts new file mode 100644 index 0000000000..aa7ec1d6d4 --- /dev/null +++ b/packages/client/ui-connector-account/src/index.ts @@ -0,0 +1,163 @@ +/** + * Connector account surfaces, Host half. CLI app plugins and MCP connectors register their accounts with + * `ctx.connectorAccounts`; the Plugins page follows every registered account through the `connectorAccounts` Remote and + * starts or cancels operations through it, so the browser never learns how an account connects. + * @module @deepseek-ai/dsh-client-ui-connector-account + */ + +import type { Context } from '@deepseek-ai/cordis' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { + AnyConnectorAccountView, ConnectorAccountEntry, ConnectorAccountRegistration, ConnectorAccountsView, ConnectorOperationId, +} from './types.ts' + +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Connector accounts on the Plugins page. */ + connectorAccounts: ConnectorAccounts + } +} + +interface Registered { + readonly packageName: string | undefined + readonly entry: () => ConnectorAccountEntry + readonly refresh: () => void + readonly start: (operation: string) => ConnectorOperationId | Promise + readonly cancel: (id: ConnectorOperationId) => Promise +} + +function registeredOf(registration: ConnectorAccountRegistration): Registered { + const { key, packageName, source, operations, copy, present } = registration + return { + packageName, + entry: () => { + const view = source.snapshot() + const { operation, result } = view + const notice = result?.outcome === 'succeeded' ? operations.find(candidate => candidate.kind === result.kind)?.notice : undefined + return { + key, ...packageName === undefined ? {} : { packageName }, copy, display: present(view), + ...operation === undefined ? {} : { + operation: { + id: operation.id, ...operation.authorizationUrl === undefined ? {} : { authorizationUrl: operation.authorizationUrl }, + }, + }, + ...result === undefined ? {} : { result: { id: result.id, ...notice === undefined ? {} : { notice } } }, + } + }, + refresh: () => { source.refresh() }, + start: (operation) => { + const kind = operations.find(candidate => candidate.kind === operation)?.kind + if (kind === undefined) throw new Error(`connectorAccounts: ${key} has no page operation ${operation}`) + return source.start(kind) + }, + cancel: id => source.cancel(id), + } +} + +/** Holds the registered accounts and serves them to the Plugins page. */ +export default class ConnectorAccounts extends TypertRemoteService { + private readonly accounts = new Map() + private readonly listeners = new Set<() => void>() + private readonly lifetime = new AbortController() + private subscribers = 0 + + /** @param ctx - the Host context the registry serves the page from. */ + constructor(ctx: Context) { + super(ctx, 'connectorAccounts') + ctx.effect(() => () => { this.lifetime.abort(new Error('connectorAccounts: registry disposed')) }) + } + + /** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ + register(registration: ConnectorAccountRegistration): () => void { + const { key, packageName } = registration + if (this.accounts.has(key)) throw new Error(`connectorAccounts: ${key} is already registered`) + if (packageName !== undefined && [...this.accounts.values()].some(account => account.packageName === packageName)) { + throw new Error(`connectorAccounts: ${packageName} already has an account`) + } + this.accounts.set(key, registeredOf(registration)) + const stop = registration.source.observe(() => { this.changed() }) + // A page that already follows the accounts checks a newly registered one, as it checks each account it subscribes to. + if (this.subscribers > 0) registration.source.refresh() + this.changed() + let active = true + return () => { + if (!active) return + active = false + stop() + this.accounts.delete(key) + this.changed() + } + } + + /** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + const combined = AbortSignal.any([signal, this.lifetime.signal]) + let wake = Promise.withResolvers() + let changed = true + const notify = (): void => { changed = true; wake.resolve() } + this.listeners.add(notify) + combined.addEventListener('abort', notify, { once: true }) + this.subscribers += 1 + try { + for (const account of this.accounts.values()) account.refresh() + for (;;) { + if (!changed) await wake.promise + if (combined.aborted) break + wake = Promise.withResolvers() + changed = false + yield { accounts: [...this.accounts.values()].map(account => account.entry()) } + } + } finally { + this.subscribers -= 1 + this.listeners.delete(notify) + combined.removeEventListener('abort', notify) + } + } + + /** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ + @Remote + async start(key: string, operation: string): Promise { + return await this.account(key).start(operation) + } + + /** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ + @Remote + cancel(key: string, id: ConnectorOperationId): Promise { + return this.account(key).cancel(id) + } + + private account(key: string): Registered { + const account = this.accounts.get(key) + if (account === undefined) throw new Error(`connectorAccounts: ${key} is not registered`) + return account + } + + private changed(): void { + for (const notify of this.listeners) notify() + } +} diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts new file mode 100644 index 0000000000..debd04d302 --- /dev/null +++ b/packages/client/ui-connector-account/src/types.ts @@ -0,0 +1,164 @@ +/** + * Credential-free account views of connector plugins, and what the Plugins page receives about them. Each registrant + * supplies its own account, operation, phase, and failure types and maps its views to the page's display, so CLI app + * plugins and MCP connectors share one registry and one page. + */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' + +/** Identifies one Host-owned account operation across the browsers that show the account. */ +export type ConnectorOperationId = Branded<'ConnectorOperationId'> + +/** The account operation in progress; `Phase` names the registrant's own steps. */ +export interface ConnectorOperation { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly phase: Phase + /** Whether the source cancels the operation in its current phase. */ + readonly cancellable: boolean + /** The page the user authorizes in, while the operation waits for one; only the browser that started it opens it. */ + readonly authorizationUrl?: string +} + +/** The most recent finished operation, kept until another one starts. */ +export interface ConnectorOperationResult { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly outcome: 'succeeded' | 'cancelled' | 'failed' + /** The registrant's classified failure, for its own presentation; does not imply rollback or a safe retry. */ + readonly failure?: Failure +} + +/** The complete account view; observers reread it after each change. */ +export interface ConnectorAccountView { + /** The account as the source last published it. */ + readonly account: Account + readonly operation?: ConnectorOperation + readonly result?: ConnectorOperationResult +} + +/** Any registrant's account view. */ +export type AnyConnectorAccountView = ConnectorAccountView + +/** The operation kinds a view reports. */ +export type ConnectorOperationKindOf = NonNullable['kind'] + +/** What the Plugins page shows about an account; each registrant maps its own account states onto these phases. */ +export type ConnectorAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' + +/** What a section button does. */ +export type ConnectorAccountCommand = + /** Start one of the operations the account registered as page actions. */ + | { readonly kind: 'start'; readonly operation: string } + /** Cancel the operation in progress when it is cancellable. */ + | { readonly kind: 'cancel' } + /** Open the current operation's authorization page again in this browser. */ + | { readonly kind: 'open' } + +/** The question a button asks before it runs. */ +export interface ConnectorAccountConfirmation { + readonly title: LocalizedText + readonly body: LocalizedText + /** The confirm button's label. */ + readonly label: LocalizedText +} + +/** One button in the section. */ +export interface ConnectorAccountButton { + readonly label: LocalizedText + readonly command: ConnectorAccountCommand + /** Defaults to an outline button. */ + readonly variant?: 'primary' | 'ghost' + /** Ask first, for an action that changes the account outside DSH, such as signing out. */ + readonly confirm?: ConnectorAccountConfirmation +} + +/** One extra row under the status line, such as the linked app, with an optional button. */ +export interface ConnectorAccountNote { + readonly text: LocalizedText + readonly button?: ConnectorAccountButton +} + +/** A failed operation as the section reports it. */ +export interface ConnectorAccountFailure { + /** The registrant's recovery guidance. */ + readonly text: LocalizedText + /** Untranslated diagnostic items shown after the guidance in order. */ + readonly details?: readonly string[] +} + +/** What the section shows for the current view; every text carries each shipped language. */ +export interface ConnectorAccountDisplay { + readonly phase: ConnectorAccountPhase + readonly status: LocalizedText + /** The tag beside the bundle title; absent while nothing is settled. */ + readonly badge?: LocalizedText + readonly buttons: readonly ConnectorAccountButton[] + /** What Connect in the activation prompt starts after opening the bundle page; absent, Connect only opens the page. */ + readonly connect?: Extract + readonly detail?: LocalizedText + readonly notes: readonly ConnectorAccountNote[] + readonly failure?: ConnectorAccountFailure +} + +/** The section's fixed text that names the service or uses its wording. */ +export interface ConnectorAccountCopy { + readonly title: LocalizedText + /** The line under the section, such as where the account is shared or authorized. */ + readonly hint: LocalizedText + /** The prompt after the bundle is switched on while the account is disconnected. */ + readonly activation: { readonly title: LocalizedText; readonly body: LocalizedText; readonly connect: LocalizedText } +} + +/** One registered account as the Plugins page receives it. */ +export interface ConnectorAccountEntry { + /** The registrant's stable account key, which the page passes back to start and cancel operations. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; absent for an account no bundle owns. */ + readonly packageName?: string + readonly copy: ConnectorAccountCopy + readonly display: ConnectorAccountDisplay + /** The operation in progress, which a browser follows when it started it. */ + readonly operation?: { readonly id: ConnectorOperationId; readonly authorizationUrl?: string } + /** The most recent finished operation, with the registrant's text when it succeeded. */ + readonly result?: { readonly id: ConnectorOperationId; readonly notice?: LocalizedText } +} + +/** Every registered account, as each change publishes it. */ +export interface ConnectorAccountsView { + readonly accounts: readonly ConnectorAccountEntry[] +} + +/** The account a registration exposes to the page. */ +export interface ConnectorAccountSource { + snapshot(): View + /** @returns a disposer; the listener runs after each change without starting a check. */ + observe(listener: () => void): () => void + /** Start a check unless an operation runs; a source whose view is always current does nothing. */ + refresh(): void + /** @returns the started operation's identity, at once or after the source has started the operation. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise + /** @returns after the named operation settles, or at once when it is not cancellable. */ + cancel(id: ConnectorOperationId): Promise +} + +/** One operation a page button may start, with the text its success reports in the browser that started it. */ +export interface ConnectorAccountOperation { + readonly kind: Kind + readonly notice?: LocalizedText +} + +/** One connector account, registered with the Host's `ctx.connectorAccounts`. */ +export interface ConnectorAccountRegistration { + /** Stable key, unique among registered accounts, such as the bundle's package name. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; at most one account per package. */ + readonly packageName?: string + readonly source: ConnectorAccountSource + /** The operations a page button may start; the registry rejects any other. */ + readonly operations: readonly ConnectorAccountOperation>[] + readonly copy: ConnectorAccountCopy + /** Map the current view to what the section shows; called on each change for each subscriber. */ + readonly present: (view: View) => ConnectorAccountDisplay +} diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts new file mode 100644 index 0000000000..4dda30bb1c --- /dev/null +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -0,0 +1,163 @@ +/** + * The browser plugin shows one tag and one notice entry for the page, and a section and activation prompt for each bundle + * that owns an account, withdrawing them with the account or the plugin. + */ +import assert from 'node:assert/strict' +import { Context, Service } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { NS } from '../src/client/locales.ts' +import { apply, inject } from '../src/client/index.ts' +import type { ConnectorAccountFace, ConnectorBundleAccountFace } from '../src/client/types.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' +const OP = 'op-1' as ConnectorOperationId + +function isFace(value: Record): asserts value is Record & ConnectorAccountFace { + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function') + assert(typeof value.start === 'function' && typeof value.cancel === 'function') + assert(typeof value.hooks === 'object' && value.hooks !== null) +} + +/** Read the face a slot entry injects. */ +function faceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorAccountFace { + assert(item.inject !== undefined) + const face = item.inject() + isFace(face) + return face +} + +function bundleFaceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorBundleAccountFace { + const face = faceOf(item) + assert('account' in face && typeof face.account === 'string') + return face as ConnectorBundleAccountFace +} + +function entry(key: string, packageName: string | null = key): ConnectorAccountEntry { + return { + key, ...packageName === null ? {} : { packageName }, + copy: { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } }, + display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, + } +} + +async function bench() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, accepted = 0 + const closeStream = vi.fn(async () => { closed = true; wake?.() }) + const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + const cancel = vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ({ ok: true, value: undefined })) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + $stream() { + return { + async *[Symbol.asyncIterator]() { + for (;;) { + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: closeStream, + } + } + } + new Remote() + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel }) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => + ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) + return { + ctx, locale, start, cancel, closeStream, bundles, + mount: () => ctx.plugin({ inject: [...inject], apply }), + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + queue.push({ accounts: entries }) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + } +} + +it('shows one tag and one notice entry for the page and each bundle\'s section and prompt under the shared dictionary', async () => { + const b = await bench() + await b.mount() + expect(b.locale.bind(NS)('action.cancel')).toBe('Cancel') + expect(b.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.badge', ConnectorAccountBadgeEntry], + ]) + expect(b.ctx.slots.entries('shell.overlay').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.notice', ConnectorAccountToastEntry], + ]) + expect(b.bundles('plugins.bundle.config')).toEqual([]) + + // An account no bundle owns gets no bundle surfaces. + await b.publish(entry(FIXTURE), entry(OTHER), entry('mcp:custom', null)) + expect(b.bundles('plugins.bundle.config')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + const [section] = b.ctx.slots.entries('plugins.bundle.config') + assert(section !== undefined) + expect(section).toMatchObject({ locale: NS, component: ConnectorAccountSectionEntry }) + expect(b.ctx.slots.entries('plugins.bundle.activation')[0]).toMatchObject({ locale: NS, component: ConnectorAccountActivationEntry }) + const face = bundleFaceOf(section) + const [badge] = b.ctx.slots.entries('plugins.detail.badge') + assert(badge !== undefined) + const [toast] = b.ctx.slots.entries('shell.overlay') + assert(toast !== undefined) + expect(faceOf(badge).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) + expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') + expect(await face.start(FIXTURE, 'connect')).toEqual({ ok: true, value: OP }) + expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + expect(await face.cancel(FIXTURE, OP)).toEqual({ ok: true, value: undefined }) + expect(b.cancel).toHaveBeenCalledWith(FIXTURE, OP) + // A refusal reaches the buttons as the Remote's result. + const refused: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } + b.start.mockResolvedValueOnce(refused) + expect(await face.start(FIXTURE, 'connect')).toBe(refused) + face.follow(FIXTURE, OP) + face.failed() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) + face.dismissNotice() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toBeUndefined() + + // A dropped account withdraws its bundle's surfaces, and a bundle whose account changed key shows the new one. + await b.publish(entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, OTHER]]) + await b.publish(entry('mcp:other', OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, 'mcp:other']]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[OTHER, 'mcp:other']]) +}) + +it('withdraws every surface, the dictionaries, and the stream when the plugin unloads', async () => { + const b = await bench() + const fiber = b.mount() + await fiber + await b.publish(entry(FIXTURE), entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toHaveLength(2) + await fiber.dispose() + for (const slot of ['plugins.bundle.config', 'plugins.bundle.activation', 'plugins.detail.badge', 'shell.overlay'] as const) { + expect(b.ctx.slots.entries(slot)).toEqual([]) + } + expect(b.locale.bind(NS)('action.cancel')).toBe('action.cancel') + expect(b.closeStream).toHaveBeenCalledOnce() +}) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx new file mode 100644 index 0000000000..8e645a7bc4 --- /dev/null +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -0,0 +1,246 @@ +// @vitest-environment jsdom +/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Host callbacks. */ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { zh } from '../src/client/locales.ts' +import type { ConnectorAccountFace, ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' + +afterEach(cleanup) + +const KEY = '@acme/fixture' +const OP = 'op-1' as ConnectorOperationId +const STARTED: RemoteResult = { ok: true, value: OP } +const REFUSED: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } +const t = makeTranslate(zh) +const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en +const button = (name: string) => screen.getByRole('button', { name }) +const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) +const click = async (name: string) => { await act(async () => { fireEvent.click(button(name)) }) } + +const DISCONNECTED: ConnectorAccountDisplay = { + phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', + buttons: [{ label: '连接演示', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [], +} + +function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}): ConnectorAccountEntry { + return { + key: KEY, packageName: KEY, display, + copy: { title: { en: 'Fixture account', zh: '演示账号' }, hint: '与终端共用。', activation: { title: '连接演示', body: '插件已开启。', connect: '连接演示' } }, + ...extra, + } +} + +function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { + const current: ConnectorAccountsState = { + accounts: new Map(accounts.map(item => [item.key, item])), linked: true, notice: undefined, ...change, + } + return { + useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), + start: vi.fn(async () => STARTED), + cancel: vi.fn(async () => ({ ok: true, value: undefined })), + account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, + } +} + +const sectionOf = (display: ConnectorAccountDisplay, change: Partial = {}) => face(change, [entry(display)]) +const prompt = (props: ReturnType, onDismiss = vi.fn(), onOpenDetails = vi.fn()) => + + +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation on the Host', async () => { + const props = sectionOf({ + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + }) + const { container } = render() + for (const text of ['演示账号', '未连接', '先关联一个应用。', '普通说明', '与终端共用。']) expect(screen.getByText(text)).toBeTruthy() + expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() + await click('连接演示') + await click('更换') + expect(props.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) + expect(props.follow.mock.calls).toEqual([[KEY, OP], [KEY, OP]]) +}) + +it('disables the buttons while a call is pending or the Host stream is down', async () => { + const props = face() + const answer = Promise.withResolvers>() + props.start.mockReturnValueOnce(answer.promise) + render() + fireEvent.click(button('连接演示')) + expect(disabled()).toEqual([true]) + await act(async () => { answer.resolve(STARTED) }) + expect(disabled()).toEqual([false]) + expect(props.failed).not.toHaveBeenCalled() + cleanup() + render() + expect(disabled()).toEqual([true]) +}) + +it('asks before a button that changes the account outside DSH and starts it only after the user accepts', async () => { + const props = sectionOf({ + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + }) + render() + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.click(button('退出登录')) + await click('确认退出') + expect(screen.queryByRole('dialog')).toBeNull() + expect(props.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it('disables an open confirmation and the activation prompt\'s Connect while the Host stream is down', () => { + const display: ConnectorAccountDisplay = { + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + } + const { rerender } = render() + fireEvent.click(button('退出登录')) + // The stream drops while the confirmation is open. + const down = sectionOf(display, { linked: false }) + rerender() + fireEvent.click(button('确认退出')) + expect((button('确认退出') as HTMLButtonElement).disabled).toBe(true) + expect(down.start).not.toHaveBeenCalled() + cleanup() + const offline = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }, { linked: false }) + render(prompt(offline)) + fireEvent.click(button('连接演示')) + expect((button('连接演示') as HTMLButtonElement).disabled).toBe(true) + expect(offline.start).not.toHaveBeenCalled() +}) + +it.each<[string, ConnectorAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], +])('reports %s', (_name, failure, expected) => { + render() + expect(screen.getByRole('alert').textContent).toBe(expected) +}) + +it('reports a start whose result is a failure or whose call rejected, without following it', async () => { + const props = face() + props.start.mockResolvedValueOnce(REFUSED).mockRejectedValueOnce(new Error('Remote method is no longer mounted')) + render() + await click('连接演示') + expect(props.failed).toHaveBeenCalledOnce() + expect(disabled()).toEqual([false]) + await click('连接演示') + expect(props.failed).toHaveBeenCalledTimes(2) + expect(props.follow).not.toHaveBeenCalled() +}) + +it('cancels the operation in progress and opens its authorization page again on request', async () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + const display: ConnectorAccountDisplay = { + phase: 'connecting', status: '等待浏览器', notes: [], + buttons: [{ label: '打开授权页', command: { kind: 'open' } }, { label: '取消', command: { kind: 'cancel' }, variant: 'ghost' }], + } + const props = face({}, [entry(display, { operation: { id: OP, authorizationUrl: 'https://example.com/a' } })]) + render() + fireEvent.click(button('打开授权页')) + expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') + await click('取消') + expect(props.cancel).toHaveBeenCalledWith(KEY, OP) + expect(props.failed).not.toHaveBeenCalled() + props.cancel.mockResolvedValueOnce(REFUSED) + await click('取消') + expect(props.failed).toHaveBeenCalledOnce() + // A cancel button with no operation in progress calls nothing. + cleanup() + const idle = sectionOf(display) + render() + await click('取消') + expect(idle.cancel).not.toHaveBeenCalled() +}) + +it('renders nothing for a bundle whose account the Host has not listed', () => { + render() + render(prompt(face({}, []))) + expect(document.body.textContent).toBe('') +}) + +it('tags only the enabled bundle that owns an account, with the display\'s tag', () => { + const pkg = (name: string, enabled = true) => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] } as const) + const page = (name: string, enabled = true): PluginsSubject => ({ kind: 'bundle', pkg: pkg(name, enabled) }) + const row: PluginsSubject = { kind: 'row', pkg: pkg(KEY), row: { rowId: 'fixture', moduleName: '@acme/fixture-row', enabled: true } } + const tag = (props: ReturnType, subject: PluginsSubject) => + const { rerender } = render(tag(face(), page(KEY))) + expect(screen.getByText('未连接')).toBeTruthy() + rerender(tag(face(), row)) + expect(screen.getByText('未连接')).toBeTruthy() + for (const [props, subject] of [ + [face(), page(KEY, false)], [face(), page('@acme/other')], [face(), { kind: 'item', id: 'fixture-item' }], + [sectionOf({ phase: 'checking', status: '检查中', buttons: [], notes: [] }), page(KEY)], + ] as const) { + rerender(tag(props, subject)) + expect(document.body.textContent).toBe('') + } +}) + +it('prompts to connect only while disconnected, waits while checking or connecting, and dismisses itself once settled', () => { + const onDismiss = vi.fn() + const at = (phase: ConnectorAccountDisplay['phase']) => prompt(sectionOf({ phase, status: phase, buttons: [], notes: [] }), onDismiss) + const { rerender } = render(at('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(at('connecting')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(at('disconnected')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button(zh['activation.later'])) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(at('connected')) + rerender(at('unavailable')) + expect(onDismiss).toHaveBeenCalledTimes(3) +}) + +it('connects from the prompt through the operation the display names, or only opens the page', async () => { + const onOpenDetails = vi.fn() + const named = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } }) + const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) + await click('连接演示') + expect(onOpenDetails).toHaveBeenCalledOnce() + expect(named.start).toHaveBeenCalledWith(KEY, 'link-app') + const bare = face() + rerender(prompt(bare, vi.fn(), onOpenDetails)) + fireEvent.click(button('连接演示')) + expect(onOpenDetails).toHaveBeenCalledTimes(2) + expect(bare.start).not.toHaveBeenCalled() +}) + +it('starts once for a second click before the first call answers', async () => { + const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) + const answer = Promise.withResolvers>() + props.start.mockReturnValueOnce(answer.promise) + render(prompt(props)) + fireEvent.click(button('连接演示')) + fireEvent.click(button('连接演示')) + await act(async () => { answer.resolve(STARTED) }) + expect(props.start).toHaveBeenCalledOnce() + expect(props.follow).toHaveBeenCalledOnce() +}) + +it('shows the latest notice with the registrant text or the shared failure copy', () => { + const toast = (notice: ConnectorAccountsState['notice']) => + const { rerender } = render(toast(undefined)) + expect(document.body.textContent).toBe('') + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) + expect(screen.getByText('演示已连接')).toBeTruthy() + rerender(toast({ seq: 2, kind: 'action-failed' })) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() +}) diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts new file mode 100644 index 0000000000..ee8e24276f --- /dev/null +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -0,0 +1,170 @@ +/** The registry serves every registered account to the Plugins page and routes page operations to the account that owns them. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished, vi } from 'vitest' +import ConnectorAccounts from '../src/index.ts' +import type { + ConnectorAccountDisplay, ConnectorAccountRegistration, ConnectorAccountSource, ConnectorAccountsView, ConnectorAccountView, + ConnectorOperationId, +} from '../src/types.ts' + +type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const COPY = { + title: { en: 'Fixture account', zh: '演示账号' }, + hint: 'Shared with the terminal.', + activation: { title: 'Connect Fixture', body: 'The plugin is on.', connect: 'Connect' }, +} + +function source(initial: View = { account: { state: 'out' } }) { + let view = initial + const listeners = new Set<() => void>() + const fake = { + snapshot: () => view, + observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), + refresh: vi.fn(), + start: vi.fn((_kind: 'check' | 'connect'): ConnectorOperationId | Promise => OP), + cancel: vi.fn(async (_id: ConnectorOperationId) => {}), + } satisfies ConnectorAccountSource + return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } +} + +function display(view: View): ConnectorAccountDisplay { + return view.account.state === 'in' + ? { phase: 'connected', status: 'Connected', badge: 'Connected', buttons: [], notes: [] } + : { phase: 'disconnected', status: 'Not connected', buttons: [{ label: 'Connect', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [] } +} + +/** A registration whose bundle package defaults to its key; `null` registers an account no bundle owns. */ +function registration(key: string, account = source(), packageName: string | null = key): ConnectorAccountRegistration { + return { + key, ...packageName === null ? {} : { packageName }, source: account.fake, copy: COPY, present: display, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Fixture connected', zh: '演示已连接' } }], + } +} + +async function registry() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(ConnectorAccounts) + return ctx +} + +/** Read the stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('stream ended') + if (predicate(next.value)) return next.value + } +} + +it('publishes each account with its key, package, copy, display, operation, and result, and checks it for each new subscriber', async () => { + const ctx = await registry() + const account = source() + const withdraw = ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(account.fake.refresh).not.toHaveBeenCalled() + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + const first = await until(stream, () => true) + expect(account.fake.refresh).toHaveBeenCalledOnce() + expect(first.accounts).toEqual([ + { key: '@acme/fixture', packageName: '@acme/fixture', copy: COPY, display: display({ account: { state: 'out' } }) }, + ]) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://example.com/a' } }) + const waiting = await until(stream, view => view.accounts[0]?.operation !== undefined) + expect(waiting.accounts[0]?.operation).toEqual({ id: OP, authorizationUrl: 'https://example.com/a' }) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: false } }) + const checking = await until(stream, (view) => { + const operation = view.accounts[0]?.operation + return operation !== undefined && operation.authorizationUrl === undefined + }) + expect(checking.accounts[0]?.operation).toEqual({ id: OP }) + + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + const connected = await until(stream, view => view.accounts[0]?.result !== undefined) + expect(connected.accounts[0]).toMatchObject({ + display: { phase: 'connected' }, result: { id: OP, notice: { en: 'Fixture connected', zh: '演示已连接' } }, + }) + + // Only a success reports a notice, and only for an operation that registered one. + account.publish({ account: { state: 'out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'disconnected')).accounts[0]?.result).toEqual({ id: OP }) + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'connected')).accounts[0]?.result).toEqual({ id: OP }) + + withdraw() + expect((await until(stream, view => view.accounts.length === 0)).accounts).toEqual([]) + withdraw() + expect(account.listeners.size).toBe(0) + controller.abort() + expect((await stream.next()).done).toBe(true) +}) + +it('publishes an account that no bundle owns without a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('mcp:custom', source(), null)) + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const [entry] = (await until(stream, () => true)).accounts + expect(entry).toEqual({ key: 'mcp:custom', copy: COPY, display: display({ account: { state: 'out' } }) }) +}) + +it('checks an account registered while the page follows, and none registered while nobody follows', async () => { + const ctx = await registry() + const idle = source() + ctx.connectorAccounts.register(registration('@acme/idle', idle)) + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + await until(stream, view => view.accounts.length === 1) + const late = source() + ctx.connectorAccounts.register(registration('@acme/late', late)) + expect(late.fake.refresh).toHaveBeenCalledOnce() + expect((await until(stream, view => view.accounts.length === 2)).accounts.map(entry => entry.key)).toEqual(['@acme/idle', '@acme/late']) + controller.abort() + await stream.next() + const after = source() + ctx.connectorAccounts.register(registration('@acme/after', after)) + expect(after.fake.refresh).not.toHaveBeenCalled() +}) + +it('starts only the operations an account registered and cancels through its source', async () => { + const ctx = await registry() + const account = source() + ctx.connectorAccounts.register(registration('@acme/fixture', account)) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(OP) + expect(account.fake.start).toHaveBeenCalledWith('connect') + // A source that starts its operation asynchronously answers once it has the identity. + account.fake.start.mockImplementationOnce(async () => NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).rejects.toThrow('@acme/fixture has no page operation sign-out') + await expect(ctx.connectorAccounts.start('@acme/other', 'connect')).rejects.toThrow('@acme/other is not registered') + await ctx.connectorAccounts.cancel('@acme/fixture', OP) + expect(account.fake.cancel).toHaveBeenCalledWith(OP) + expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') +}) + +it('refuses a second account for a key or for a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('@acme/fixture')) + expect(() => ctx.connectorAccounts.register(registration('@acme/fixture'))).toThrow('@acme/fixture is already registered') + expect(() => ctx.connectorAccounts.register(registration('mcp:fixture', source(), '@acme/fixture'))) + .toThrow('@acme/fixture already has an account') + expect(() => ctx.connectorAccounts.register(registration('mcp:custom', source(), null))).not.toThrow() +}) + +it('ends every stream when the registry unloads', async () => { + const ctx = new Context() + const fiber = ctx.plugin(ConnectorAccounts) + await fiber + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + await until(stream, () => true) + const pending = stream.next() + await fiber.dispose() + expect((await pending).done).toBe(true) + await ctx.fiber.dispose() +}) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts new file mode 100644 index 0000000000..4c11668ac2 --- /dev/null +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -0,0 +1,179 @@ +// @vitest-environment jsdom +/** The browser follows every registered account through one Host stream and keeps only what this browser started. */ +import { Context } from '@deepseek-ai/cordis' +import { RemoteStreamCarrierError, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import { expect, it, onTestFinished, vi } from 'vitest' +import { BrowserAccounts, openAuthorizationPage } from '../src/client/state.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const FIXTURE = '@acme/fixture' +const OTHER = 'mcp:other' +const COPY = { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } } + +function entry(key: string, extra: Partial = {}): ConnectorAccountEntry { + return { key, copy: COPY, display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, ...extra } +} + +const waiting = (url?: string, id = OP): Partial => + ({ operation: { id, ...url === undefined ? {} : { authorizationUrl: url } } }) + +function fixture() { + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const open = () => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + // A queued item still arrives after close, as an item the stream yielded just before disposal does. + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + }) + const streams: Array> = [] + const remote = { watch: vi.fn() } + const ctx = new Context() + ctx.provide('remote', { + $stream: (value: typeof options) => { + options = value + closed = false + failure = undefined + streams.push(open()) + return streams.at(-1) + }, + }) + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + const browser = new BrowserAccounts(ctx, remote) + onTestFinished(async () => { await browser.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) + return { + ctx, browser, remote, open: windowOpen, streams, options: () => options, + state: () => browser.state.getSnapshot(), + deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + this.deliver({ accounts: entries }) + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + fail(error: Error) { failure = error; wake?.() }, + } +} + +it('mirrors the Host accounts by key and reports carrier loss until the next item', async () => { + const b = fixture() + expect(b.state()).toEqual({ accounts: new Map(), linked: true, notice: undefined }) + const open = b.options().open(new AbortController().signal) + expect(b.remote.watch).toHaveBeenCalledOnce() + expect(open).toBe(b.remote.watch.mock.results[0]?.value) + await b.publish(entry(FIXTURE), entry(OTHER)) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE, OTHER]) + b.options().carrierFailed?.(new RemoteStreamCarrierError('offline')) + expect(b.state().linked).toBe(false) + await b.publish(entry(FIXTURE)) + expect(b.state().linked).toBe(true) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) + expect(b.options().ended(true).message).toBe('Connector accounts stream ended') +}) + +it('opens each new authorization page of an operation this browser started once, and no other account\'s', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER, waiting('https://example.com/other'))) + expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + await b.publish(entry(FIXTURE, waiting('http://127.0.0.1:8123/authorize'))) + // Another browser's operation on the same account opens nothing here. + await b.publish(entry(FIXTURE, waiting('https://example.com/b', NEXT))) + expect(b.open.mock.calls.map(([url]) => url)).toEqual(['https://example.com/a', 'http://127.0.0.1:8123/authorize']) +}) + +it('opens the page at once when the stream delivered the operation before the start call answered', async () => { + const b = fixture() + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() + b.browser.follow(FIXTURE, OP) + expect(b.open).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') +}) + +it('reports the success of an operation this browser started once, and stops following it', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, { result: { id: NEXT, notice: 'Other browser connected' } })) + expect(b.state().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toEqual({ seq: 1, kind: 'succeeded', text: 'Fixture connected' }) + b.browser.dismissNotice() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toBeUndefined() + + // A result without the registrant's text, or a cancelled or failed one, reports nothing. + b.browser.follow(FIXTURE, NEXT) + await b.publish(entry(FIXTURE, { result: { id: NEXT } })) + expect(b.state().notice).toBeUndefined() +}) + +it('forgets the operation of an account the Host withdrew', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(OTHER)) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() +}) + +it('reports a call that did not finish with a fresh notice each time', () => { + const b = fixture() + b.browser.failed() + b.browser.failed() + expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) +}) + +it('keeps the buttons disabled and logs a terminal stream failure, opening no second stream', async () => { + const b = fixture() + const warn = vi.spyOn(b.ctx.logger, 'warn').mockImplementation(() => {}) + await b.publish(entry(FIXTURE)) + b.fail(new Error('Host without the registry')) + await vi.waitFor(() => { expect(b.state().linked).toBe(false) }) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('connector accounts stream failed'), expect.any(Error)) + expect(b.streams).toHaveLength(1) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) +}) + +it('opens nothing and reports nothing after disposal', async () => { + const b = fixture() + await b.browser.dispose() + b.browser.follow(FIXTURE, OP) + b.browser.failed() + expect(b.state().notice).toBeUndefined() +}) + +it('shows nothing for a stream that fails while the page disposes it', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.fail(new Error('carrier lost')) + await disposing + expect(b.state().linked).toBe(true) +}) + +it('ignores an item the stream yielded just before disposal', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.deliver({ accounts: [entry(FIXTURE)] }) + await disposing + expect(b.state().accounts.size).toBe(0) +}) + +it('opens only HTTPS pages and HTTP pages on loopback addresses', () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + for (const url of [undefined, 'not a url', 'http://example.com/a', 'javascript:alert(1)']) openAuthorizationPage(url) + expect(windowOpen).not.toHaveBeenCalled() + for (const url of ['https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a']) openAuthorizationPage(url) + expect(windowOpen.mock.calls.map(([url]) => url)).toEqual([ + 'https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a', + ]) +}) diff --git a/packages/client/ui-connector-account/tsconfig.client.json b/packages/client/ui-connector-account/tsconfig.client.json new file mode 100644 index 0000000000..115af386fd --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.client.json @@ -0,0 +1,57 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/css-modules.d.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.host.json b/packages/client/ui-connector-account/tsconfig.host.json new file mode 100644 index 0000000000..564ba19f3b --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.host.json @@ -0,0 +1,26 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.json b/packages/client/ui-connector-account/tsconfig.json new file mode 100644 index 0000000000..2eca820546 --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.host.json" + }, + { + "path": "./tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-connector-account/tsdown.config.ts b/packages/client/ui-connector-account/tsdown.config.ts new file mode 100644 index 0000000000..620261533c --- /dev/null +++ b/packages/client/ui-connector-account/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index c1b711fdd5..89ea06d3e0 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 25dd776b1c1562f1 - zh: 1efe8e6e56e73153 + en: 4919c08c24d2453b + zh: 45566252950a1ed1 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -42,8 +42,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..528c8e368c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,7 +100,7 @@ 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; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. @@ -116,6 +116,8 @@ View selection is deterministic: a registered persisted selection wins, otherwis The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated. +Until the user drags a width, the main transcript is 64% of the Conversation body wide, from 680px up to 880px; an embedded transcript is the body width less 32px, up to 880px. Beside the main transcript, the composer card is 32px wider than the transcript. + Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The handle scrolls the first `[data-conversation-scroll]` element inside the body, which is the body's own scroll element even when frame layers wrap it. The sticky composer owns its full footer band, which is not a resize target; a captured drag continues under the band and under gutter tables, which cover its indicator. In an active transcript the composer rests at the scrollport floor even when no View fills the column, keeps one stacking rank in every state, above transcript sticky headers and the back-to-bottom control, so menus it opens upward cover that control, and never serves as a scroll-anchoring target. It keeps its own compositor layer whatever lies beneath it, which makes it the containing block for fixed-position descendants: contributions to `conversation.composer`, `conversation.composer.bar`, `conversation.composer.dock`, `conversation.input.dock`, and the other `conversation.input.*` slots must portal fixed overlays to the document body, for example with `Tooltip` or `Menu` `portal` or `createPortal` ([handle and composer styles](src/client/skeleton/ConversationRoot.module.css)). The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged. @@ -223,6 +225,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..c43343c7be 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,7 +100,7 @@ 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 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 @@ -116,6 +116,8 @@ View 选择规则固定:有效且已注册的持久化选择优先,其次是 Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。 +用户拖动调整宽度之前,主 transcript 宽度为 Conversation 主体宽度的 64%,范围 680px 到 880px;嵌入式 transcript 为主体宽度减 32px,最多 880px。主 transcript 下方的输入框卡片比 transcript 宽 32px。 + 主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。拖拽条滚动的是 body 内第一个 `[data-conversation-scroll]` 元素;即使有 frame 层包在外面,它也是 body 自己的滚动区。粘滞 composer 拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会在该区带和沟槽中的表格下方继续,此时指示线被它们遮住。在活跃 transcript 中,即使没有 View 撑满整列,composer 也停在滚动区底部;它在所有状态下保持同一层级,高于 transcript 的吸顶标题与“回到底部”按钮,因此它向上打开的菜单会盖住该按钮;它也从不作为滚动锚定目标。无论下方是什么内容,它都保持自己的合成层,因此成为 fixed 定位后代的包含块:向 `conversation.composer`、`conversation.composer.bar`、`conversation.composer.dock`、`conversation.input.dock` 以及其他 `conversation.input.*` slot 贡献的内容,必须把 fixed 浮层 portal 到 document body,例如使用 `Tooltip` 或 `Menu` 的 `portal`,或 `createPortal`([拖动手柄与 composer 样式](src/client/skeleton/ConversationRoot.module.css))。 宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。 @@ -223,6 +225,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/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index f6e9ce4183..8944d91981 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -52,11 +52,41 @@ interface ConversationAttachmentFace { ): Promise serializeDraftAttachments(attachmentIds: readonly DraftAttachmentId[]): Promise releaseDraftAttachment(id: DraftAttachmentId): void + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] + draftAttachmentSessions(): readonly SessionId[] + releaseDraftSession(sessionId: SessionId): void +} + +/** Per-Session marker that a page unload discarded the draft's browser-owned attachments. */ +const UNLOAD_MARK_PREFIX = 'dsh.composer-draft-attachments-unloaded' + +/** Record that an unloading page held draft attachments for these Sessions. */ +function writeUnloadMarks(sessionIds: readonly SessionId[]): void { + try { + for (const sessionId of sessionIds) localStorage.setItem(`${UNLOAD_MARK_PREFIX}.${sessionId}`, '1') + } catch (error) { + console.error('conversation draft attachment unload marks could not be saved; a reload cannot report the loss', error) + } +} + +/** Remove one Session's unload marker. @returns whether the marker was present. */ +function takeUnloadMark(sessionId: SessionId): boolean { + try { + const key = `${UNLOAD_MARK_PREFIX}.${sessionId}` + const marked = localStorage.getItem(key) !== null + localStorage.removeItem(key) + return marked + } catch (error) { + console.error('conversation draft attachment unload mark could not be read', error) + return false + } } /** Session-addressed input facade registry (SessionInputResolver face + composer-layer extras). */ export class InputHub implements SessionInputResolver { private readonly shells = new WeakMap() + private knownSessionIds: Set | undefined + private lifecycleWatchInstalled = false /** * @param ctx - client root context (services resolved lazily per call — boot order stays free). @@ -168,10 +198,24 @@ export class InputHub implements SessionInputResolver { ] return () => { for (const off of offs) off() + // Snapshot the phase before dispose resets the machine. + const phaseAtTeardown = shell.snapshot.phase const drafts = shell.dispose() this.shells.delete(binding) const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - for (const attachmentId of drafts) conversation?.releaseDraftAttachment(attachmentId) + if (conversation === undefined) return + if (binding.session.getSnapshot().removed) { + conversation.releaseDraftSession(binding.sessionId) + return + } + // Teardown aborts adjudication before any message leaves, so those attachments stay with the draft. + // A message or command already submitted cannot settle through its retirement path after teardown, + // and the Client cannot tell whether a submitted command consumed its attachments, so both release + // here rather than risk a duplicate submission; every other draft attachment stays registered for + // the Session's next composer. + if (phaseAtTeardown === 'sending' || phaseAtTeardown === 'submitting') { + for (const attachmentId of drafts) conversation.releaseDraftAttachment(attachmentId) + } } }, 'conversation.input: session shell') actx.inject(['inputTriggers'], (scope) => { @@ -181,9 +225,64 @@ export class InputHub implements SessionInputResolver { }, 'conversation.input: reference catalogs') }) shell.setDraft(readConversationDraft(binding.sessionId)) + this.ensureLifecycleWatch() + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const retained = conversation?.draftAttachmentIds(binding.sessionId) ?? [] + // A Session switch keeps the draft's attachments registered; this composer re-adopts them. + if (retained.length > 0) shell.addAttachments(retained) + // A reload discarded the browser-owned attachments; say so instead of dropping them silently. + if (takeUnloadMark(binding.sessionId) && retained.length === 0) shell.notify('error', this.t('attachments.unavailable')) return shell } + /** + * Install the root-lifetime watchers once: a Session removed while no composer + * is mounted releases its draft attachments, and an unloading page marks the + * Sessions whose attachments it discards. + */ + private ensureLifecycleWatch(): void { + if (this.lifecycleWatchInstalled) return + this.lifecycleWatchInstalled = true + const sessions = this.sessions() + this.knownSessionIds = new Set(sessions.list.getSnapshot().ids) + this.rootCtx.effect(() => { + const stop = sessions.list.subscribe(() => { this.cleanupRemovedSessions() }) + const conversation = (): ConversationAttachmentFace | undefined => + this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const onHide = (): void => { writeUnloadMarks(conversation()?.draftAttachmentSessions() ?? []) } + // A back-forward cache restore keeps the registry, so the marks just written are stale. + const onShow = (event: PageTransitionEvent): void => { + if (!event.persisted) return + for (const sessionId of conversation()?.draftAttachmentSessions() ?? []) takeUnloadMark(sessionId) + } + window.addEventListener('pagehide', onHide) + window.addEventListener('pageshow', onShow) + return () => { + stop() + window.removeEventListener('pagehide', onHide) + window.removeEventListener('pageshow', onShow) + this.knownSessionIds = undefined + this.lifecycleWatchInstalled = false + } + }, 'conversation.input: draft attachment lifecycle') + } + + /** Release draft attachments and unload marks for every Session removed from the catalog. */ + private cleanupRemovedSessions(): void { + const known = this.knownSessionIds + /* v8 ignore next -- the catalog subscription is stopped before the known set is cleared. */ + if (known === undefined) return + const liveIds = new Set(this.sessions().list.getSnapshot().ids) + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + for (const id of [...known]) { + if (liveIds.has(id)) continue + known.delete(id) + conversation?.releaseDraftSession(id) + takeUnloadMark(id) + } + for (const id of liveIds) known.add(id) + } + /** * Resident shell by session id (service-face path; the provide channel has * normally created it already — this covers direct id-addressed access). diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 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/service.ts b/packages/client/ui-conversation/src/client/service.ts index 27cae036db..98454ba0f0 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -158,6 +158,10 @@ export class ConversationController extends Service implements IConversation { /** Live upload state per draft that uploads when added: every file draft and every uploaded image draft. */ readonly fileUploads: SnapshotStore> = createSnapshotStore>({}) private readonly draftAttachments = new Map() + /** Draft attachment ids per owning Session; they outlive that Session's composer so a return re-adopts them. */ + private readonly sessionDraftIds = new Map>() + /** Reverse ownership lookup for release and Workspace rebinding. */ + private readonly draftAttachmentSession = new Map() private readonly fileUploadOperations = new Map @@ -196,6 +200,8 @@ export class ConversationController extends Service implements IConversation { if (attachment.kind === 'image') revokePreview(attachment.previewUrl) } this.draftAttachments.clear() + this.sessionDraftIds.clear() + this.draftAttachmentSession.clear() this.fileUploads.set({}) }, 'conversation draft attachments') } @@ -279,6 +285,11 @@ export class ConversationController extends Service implements IConversation { ) // The composer owns the attachments until the Host accepts the prompt. const ownership = { accepted: false, retiredUnobserved: false } + // An accepted message's attachments leave the draft: a later composer must not re-adopt them, while + // the registry keeps them until the echo settles their previews or an unobserved retirement releases them. + const disownAccepted = (): void => { + for (const attachment of attachments) this.forgetDraftAttachment(attachment.id) + } const acceptance = Promise.withResolvers() const submission = session.beginSubmission({ mode, @@ -286,6 +297,7 @@ export class ConversationController extends Service implements IConversation { attachments: pendingAttachments, onAccept: () => { ownership.accepted = true + disownAccepted() accept?.() acceptance.resolve(undefined) }, @@ -309,6 +321,7 @@ export class ConversationController extends Service implements IConversation { const result = await Promise.race([session.prompt(content, mode, signal, submission.requestId), acceptance.promise]) if (result !== undefined && !result.ok) return { kind: 'error' } ownership.accepted = true + disownAccepted() // An accepted prompt whose echo already retired unobserved, as when its queue entry was removed. if (ownership.retiredUnobserved) this.releaseDraftAttachments(attachments) return { kind: 'success' } @@ -332,6 +345,7 @@ export class ConversationController extends Service implements IConversation { if (isImageMediaType(file.type)) { const attachment = browserDraftAttachment(file) this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) probeDimensions(attachment) if (uploadImages) this.beginFileUpload(sessionId, attachment) return attachment @@ -342,6 +356,7 @@ export class ConversationController extends Service implements IConversation { file, } this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) this.beginFileUpload(sessionId, attachment) return attachment }) @@ -369,6 +384,7 @@ export class ConversationController extends Service implements IConversation { for (const id of ids) { const attachment = this.draftAttachments.get(id) if (attachment === undefined) continue + this.ownDraftAttachment(sessionId, id) if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id) else this.beginFileUpload(sessionId, attachment) } @@ -504,11 +520,59 @@ export class ConversationController extends Service implements IConversation { const attachment = this.draftAttachments.get(id) if (attachment === undefined) return this.draftAttachments.delete(id) + this.forgetDraftAttachment(id) if (attachment.kind === 'image') revokePreview(attachment.previewUrl) // The stored Host object stays durable; only the draft's upload state ends. this.dropUpload(id) } + /** + * Draft attachment ids a Session still owns after its composer retired. + * @param sessionId - owning Session identity. + * @returns registered ids in registration order. + */ + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] { + return [...this.sessionDraftIds.get(sessionId) ?? []] + } + + /** + * Sessions that still own registered draft attachments. + * @returns Session identities with at least one registered attachment. + */ + draftAttachmentSessions(): readonly SessionId[] { + return [...this.sessionDraftIds.keys()] + } + + /** + * Release every draft attachment one removed Session owns. + * @param sessionId - removed Session identity. + */ + releaseDraftSession(sessionId: SessionId): void { + for (const id of this.draftAttachmentIds(sessionId)) this.releaseDraftAttachment(id) + } + + /** Record, or move after a Workspace rebind, one draft attachment's owning Session. */ + private ownDraftAttachment(sessionId: SessionId, id: DraftAttachmentId): void { + this.forgetDraftAttachment(id) + this.draftAttachmentSession.set(id, sessionId) + let ids = this.sessionDraftIds.get(sessionId) + if (ids === undefined) { + ids = new Set() + this.sessionDraftIds.set(sessionId, ids) + } + ids.add(id) + } + + /** Forget one draft attachment's owning Session. */ + private forgetDraftAttachment(id: DraftAttachmentId): void { + const sessionId = this.draftAttachmentSession.get(id) + if (sessionId === undefined) return + this.draftAttachmentSession.delete(id) + const ids = this.sessionDraftIds.get(sessionId) + ids?.delete(id) + if (ids?.size === 0) this.sessionDraftIds.delete(sessionId) + } + /** Abort one draft's active upload and drop its upload state. */ private dropUpload(id: DraftAttachmentId): void { const operation = this.fileUploadOperations.get(id) @@ -605,6 +669,7 @@ export class ConversationController extends Service implements IConversation { continue } this.draftAttachments.delete(attachment.id) + this.forgetDraftAttachment(attachment.id) this.forgetUpload(attachment.id) if (ref !== undefined && 'mediaType' in ref && uiConversation?.seedImageUrl(sessionId, ref, attachment.previewUrl) === true) continue diff --git a/packages/client/ui-conversation/src/client/skeleton/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/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..f758d2def7 --- /dev/null +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -0,0 +1,312 @@ +// @vitest-environment jsdom +// Draft attachments outlive their Session's composer: a switch keeps them registered, +// a removed Session releases them, and a page unload reports what it discarded. +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { brandString } from '@deepseek-ai/dsh-brand' +import 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: 2, + }).await() + const root = runtime.ctx.get('conversation') as ConversationController + const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) + const shell = shellNow() + const behavior = () => runtime.sessions.behavior(SESSION) as UploadBehavior + /** Retire the Session's composer, as a switch to another Session does. */ + const switchAway = async (): Promise => { + reference.release() + await runtime.flush() + expect(runtime.sessions.binding(SESSION)).toBeUndefined() + } + /** Mount a fresh composer for the Session again. */ + const switchBack = async () => { + reference = runtime.sessions.retain(sessionId()) + await reference.ready + return shellNow() + } + return { runtime, hub, root, shell, upload, behavior, switchAway, switchBack } +} + +function draftFile(name = 'notes.txt'): File { + return new File([new Uint8Array([1, 2, 3])], name, { type: 'text/plain' }) +} + +beforeEach(() => { localStorage.clear() }) +afterEach(() => { vi.restoreAllMocks() }) + +describe('draft attachments across a Session switch', () => { + it('re-adopts settled files and images without uploading them again', async () => { + const b = await bench() + const revoked = vi.spyOn(URL, 'revokeObjectURL') + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const drafts = b.root.createDrafts(sessionId(), [draftFile(), new File([Uint8Array.of(9)], 'pic.png', { type: 'image/png' })], true) + expect(b.shell.addAttachments(drafts.map(draft => draft.id))).toBe(true) + await vi.waitFor(() => { + for (const draft of drafts) expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') + }) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual(drafts.map(draft => draft.id)) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual(drafts.map(draft => draft.id)) + expect(b.root.resolveDraftAttachments(back.snapshot.attachmentIds)).toEqual(drafts) + expect(b.upload).toHaveBeenCalledOnce() + expect(revoked).not.toHaveBeenCalled() + expect(back.notices.getSnapshot()).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps an upload running while the Session is switched away', async () => { + const b = await bench() + try { + let finish!: (value: unknown) => void + b.behavior().uploadFile = vi.fn((...args: unknown[]) => new Promise((resolve) => { + finish = resolve + ;(args[2] as AbortSignal).addEventListener('abort', () => { resolve({ ok: false, error: new Error('aborted') }) }) + })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('uploading') }) + await b.switchAway() + finish({ ok: true, value: uploadValue('big.bin') }) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(b.upload).toHaveBeenCalledOnce() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps a failed upload so it can be retried in place after returning', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.reject(new Error('network lost'))) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('error') }) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('big.bin') })) + b.root.retryFileUpload(sessionId(), draft.id) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('removed Sessions', () => { + it('releases the draft attachments of a Session removed while no composer is mounted', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.switchAway() + localStorage.setItem(UNLOAD_MARK, '1') + await b.runtime.sessions.remove(SESSION) + await vi.waitFor(() => { expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) }) + expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('releases the draft attachments when the mounted composer of a removed Session retires', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.runtime.sessions.remove(SESSION) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('page unload report', () => { + it('marks Sessions whose attachments an unload discards, and reports them on the next page', async () => { + const first = await bench() + try { + first.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = first.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + first.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + } finally { + await first.runtime.dispose() + } + // A reload starts with an empty registry; the saved mark survives in browser storage. + const second = await bench(() => { localStorage.setItem(UNLOAD_MARK, '1') }) + try { + expect(second.shell.notices.getSnapshot()).toMatchObject({ level: 'error', text: zh['attachments.unavailable'] }) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await second.runtime.dispose() + } + }) + + it('does not report attachments a switch kept, and drops marks a back-forward restore made stale', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + const restore = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(restore, 'persisted', { value: false }) + window.dispatchEvent(restore) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + const cached = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(cached, 'persisted', { value: true }) + window.dispatchEvent(cached) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + localStorage.setItem(UNLOAD_MARK, '1') + await b.switchAway() + const back = await b.switchBack() + expect(back.notices.getSnapshot()).toBeNull() + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps working when browser storage refuses the marks', async () => { + const b = await bench() + const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + window.dispatchEvent(new Event('pagehide')) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(errors).toHaveBeenCalledTimes(2) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('submitted attachments', () => { + it('does not re-adopt or report attachments of an accepted message whose echo has not retired', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + b.shell.setDraft('send with file') + b.shell.submit('queue', 'click') + await vi.waitFor(() => { expect(b.shell.snapshot.phase).toBe('plain') }) + await b.runtime.flush() + // The registry still holds the attachment for the echo; the draft no longer owns it. + expect(b.root.resolveDraftAttachments([draft.id])).toHaveLength(1) + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + expect(b.root.draftAttachmentSessions()).toEqual([]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) + + it('keeps the attachments of a slash line whose adjudication a switch aborted', async () => { + const adjudicate = vi.fn(() => new Promise(() => undefined)) + const b = await bench() + try { + const lexicon = { getSnapshot: () => new Map<'/' | '@', readonly string[]>(), subscribe: () => () => undefined } + const triggers = { adjudicate, lexicon, track: vi.fn() } + b.runtime.ctx.provide('inputTriggers', { sessionOf: () => triggers } as never) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + b.shell.setDraft('/review this file') + b.shell.submit('queue', 'enter') + expect(b.shell.snapshot.phase).toBe('adjudicating') + expect(adjudicate).toHaveBeenCalledOnce() + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([draft.id]) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + } finally { + await b.runtime.dispose() + } + }) +}) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index e29bf0a8e0..9b93ef4240 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -138,7 +138,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 +150,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() diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index e8c20dde27..e3efe6510e 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -972,32 +972,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-jobs/README.i18n.yaml b/packages/client/ui-jobs/README.i18n.yaml index f6bb8ea61f..6da1b12ab5 100644 --- a/packages/client/ui-jobs/README.i18n.yaml +++ b/packages/client/ui-jobs/README.i18n.yaml @@ -3,32 +3,32 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-jobs/README.md /: - en: 063a69d5d6281c07 - zh: 04562d2b1dd29590 + en: ee6ba7faaa030a05 + zh: c74dcdb3f5d7d0b7 /deepseek-ai-dsh-client-ui-jobs: en: faa1eecdc7f06930 zh: c6e7b06ccb434f0b /deepseek-ai-dsh-client-ui-jobs/summary: - en: b61245c057c1a924 - zh: 6013131975ece32e + en: 4181e6f8df4dc4e9 + zh: 7a8f25a775bd854a /deepseek-ai-dsh-client-ui-jobs/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-jobs/use-this-package: - en: 3466553808f81088 - zh: 02a806ece1c3e012 + en: 6ebf1b995be0d5ba + zh: a6dba97d5b8f6bfb /deepseek-ai-dsh-client-ui-jobs/use-this-package/one-row-per-job: - en: 64c1f55b35e73295 - zh: 4d93594923cf787f + en: 67eec41471ccdf6b + zh: 2ffe602ad5575643 /deepseek-ai-dsh-client-ui-jobs/use-this-package/the-expanded-panel: en: c34dad62fee63306 zh: 167d9da7928a9488 /deepseek-ai-dsh-client-ui-jobs/understand-the-implementation: - en: 640e8bd39b28c07d - zh: 86c7eb39acfeebc0 + en: e5bbb2f24732e6e9 + zh: ac3f248b255c5211 /deepseek-ai-dsh-client-ui-jobs/further-exploration: - en: 01eaaecb5850f391 - zh: 2eabd14cde191ab8 + en: e9370f09a7b49495 + zh: 6b297e9dbf7a6aa6 /deepseek-ai-dsh-client-ui-jobs/model-experience: en: 84ad94ba940f17af zh: 0199b09d360df0d8 diff --git a/packages/client/ui-jobs/README.md b/packages/client/ui-jobs/README.md index 04abc0f1d1..687b51cfff 100644 --- a/packages/client/ui-jobs/README.md +++ b/packages/client/ui-jobs/README.md @@ -1,5 +1,5 @@ --- -description: "The session-header background-job list: expandable streaming output panels, running/finished sections, and static rows for settled jobs without retained output." +description: "The Session panel's background-jobs section: expandable streaming output panels, live rows above a folded finished list, and static rows for settled jobs without retained output." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-client-ui-jobs` shows the session's background jobs in one header control, with lifecycle, elapsed time, progress, and terminal detail. Live jobs and settled jobs with retained output offer expandable output panels; collapsing stops the stream. Live rows lead with a ticking duration, followed by kind and status. Settled rows fold under a section heading; those without retained output, including subagents whose answers went to the model, stay static. +`dsh-client-ui-jobs` shows the session's background jobs in the Session panel's Background jobs section, with lifecycle, elapsed time, progress, and terminal detail. Live jobs and settled jobs with retained output offer expandable output panels; collapsing stops the stream. Live rows show the label above the kind, current progress, and a ticking duration. Settled rows fold under a count; those without retained output, including subagents whose answers went to the model, stay static. ## Table of Contents @@ -25,17 +25,17 @@ English | [中文](README.zh.md) ## Use this package -Load the plugin through the web-app manifest; it renders nothing until the session can see at least one job, so an ordinary conversation never grows a control for a capability it is not using. +Load the plugin through the web-app manifest. It registers the [Session panel](../ui-session-panel/README.md#contribute-a-section) section `background-jobs` at order 300, after Subagents, titled “Background jobs”. While jobs 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; it keeps the Session's roster stream open while the toggle is mounted. The section renders nothing until the session can see at least one job, so the panel hides it together with its title and an ordinary conversation shows no section for a capability it is not using. -The header shows the live job count when any jobs are running or stopping, otherwise the visible job count, without repeating the spinner's running state in visible text. The trigger's accessible description identifies live work in both wide and compact layouts. In wide layout, a 14px icon slot shows the spinner for live jobs or the 14px layers icon for idle jobs; the root trigger has no disclosure arrow. At container widths up to 460px, the count hides and the trigger always shows the layers icon, including while jobs are live; running indicators remain inside the menu. The trigger matches More and sidebar controls: a 28×28px icon button 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. Its count tooltip appears after 500ms of hover or immediately on keyboard focus, and stays hidden while the list is open. +Live rows come first, the most recently started first; settled rows follow newest-first under a “Finished {count}” toggle, whose chevron follows the text, with a “Clear” action. The toggle starts folded while a job is live and open otherwise; the user's choice holds for the Session, also after the panel is hidden and shown again. Each of the two groups shows five rows and then the Session panel's fold control as its last row, “Show {count} more running” or “Show {count} more finished”, which shows the rest and then reads “Show less”; a group folds only when that holds back two rows or more. That choice also holds for the Session, and Clear folds the settled group to five rows again. An expanded row stops observing its output while its group holds it back. Each row is one 28px line with the command, then the duration, the stop control while the job runs, and a chevron at its end, in the Session panel's columns; the whole row, chevron included, expands and collapses it. A command the row clips crawls into view while the pointer rests on the row, and the stop control names its action after 500ms of hover. Resting the pointer on a row for 500ms opens a hover card with the job kind, the status or terminal detail, and the duration, but not the command, which can run to many lines and shows in full, with Copy, in the expanded output panel; the card stays closed while the pointer rests on the stop control; assistive technology reads the kind and status as the row's description. A job that finished with a nonzero exit code shows the warning dot, like a stopped one, and a `failed` job the error dot. The settled list folds while any job is live and opens when only settled jobs remain; pressing the toggle overrides that default. Clear hides the current settled rows in this client while the Session stays open, also after the panel is hidden and shown again; the registry keeps their records, a job that settles later appears normally, and the section hides when no rows remain. -Non-touch hover on the text-visible trigger opens the list after 150ms; leaving both the trigger and its portaled list closes it after 120ms. Clicking the wide trigger opens or pins the list; clicking an already pinned trigger closes it. The compact trigger toggles on click and never opens on hover, including when the count hides during a pending hover. ArrowDown opens and pins the list and focuses its first control. Pointer interaction or keyboard focus inside also pins it. Outside click or Escape dismisses it, and Tab connects the trigger to the portaled controls. Hover timers and pins reset when the session changes, no visible jobs remain, or the component unmounts. +Pressing an observable row expands its output panel, and pressing it again collapses it; one row expands at a time. Each duration has a tooltip, “Running for {duration}” on live rows and “Took {duration}” on settled rows, and live durations advance once per second while any job is live. ### One row per job The `job.list` stream `ctx.jobs` mirrors is the single roster: each `JobView` row carries lifecycle, duration, the live `progress` line or the terminal `detail`, and its retained byte count — a live job, or a settled one with retained output, is what makes a row expandable. There is no second roster to join. -Running job rows also carry a two-press stop control: the first press arms it, the confirming press within three seconds calls `ctx.jobs.kill`, and the row converges through the roster stream (`stopping`, then the settled section, whose detail carries `cancelled by the user`). The kill claims nothing in the model's notice ledger, so the owning agent still receives the standard completion notice — the model is told the user stopped its task rather than left to infer it ([reference](../../jobs/tool-jobs/README.md)). The settled section folds behind its count while live work exists and can be cleared client-side. +Running job rows also carry a two-press stop control, whose tooltip reads “Stop task” without the command: the first press arms it and widens it into a “Confirm stop” button, the confirming press within three seconds calls `ctx.jobs.kill`, and the row converges through the roster stream (`stopping`, then the settled list, whose detail carries `cancelled by the user`). A rejected kill shows “Stop failed” for four seconds. The kill claims nothing in the model's notice ledger, so the owning agent still receives the standard completion notice — the model is told the user stopped its task rather than left to infer it ([reference](../../jobs/tool-jobs/README.md)). ### The expanded panel @@ -49,15 +49,16 @@ Expanding an observable row opens that job's output observation stream from `ctx
Implementation internals — click to expand -One slot entry in the header actions band (after the preset label) renders the trigger; its popover uses a body-mounted `MenuSurface` with fixed positioning so dock panels and clipping ancestors cannot cover it. CSS anchors keep the popover 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. Its internal scrolling and dismissal remain available. All data arrives through `ctx.jobs` — the component holds no transport state. The roster follows the mount: one `useEffect` keeps the session's `job.list` stream open while the control lives. Observation follows visibility: another `useEffect` opens the stream for the expanded row's job and closes it on collapse, unmount, or popover close. +One `conversation.session.panel.section` registration renders the section body; the Session panel draws its title, supplies its inset, and scrolls it. All data arrives through `ctx.jobs` — the component holds no transport state. The roster follows the mount: one `useEffect` keeps the session's `job.list` stream open while the section is mounted, which is while the Session panel shows. Observation follows visibility: another `useEffect` opens the stream for the expanded row's job and closes it on collapse or unmount, including when the panel hides. | File | Role | |---|---| -| [`src/client/JobListAction.tsx`](src/client/JobListAction.tsx) | The job list: sections, durations, panels | -| [`src/client/index.ts`](src/client/index.ts) | Slot registration and the dictionaries | +| [`src/client/JobsSection.tsx`](src/client/JobsSection.tsx) | The section: live and settled rows, durations, the stop control, output panels | +| [`src/client/jobs-store.ts`](src/client/jobs-store.ts) | Per-Session store of cleared rows | +| [`src/client/index.ts`](src/client/index.ts) | Session panel section registration and the dictionaries | | [`src/client/locales.ts`](src/client/locales.ts) | The `job` namespace copy (zh source of truth) | -Background-job rows follow the [standard menu edge geometry](../../../docs/ui-radius.md#nested-hover); controls inside a filled running row retain compact corners. +Background-job rows use the standard menu item radius from the [nested geometry rules](../../../docs/ui-radius.md#nested-hover); controls inside a filled running row retain compact corners.
@@ -68,6 +69,7 @@ Background-job rows follow the [standard menu edge geometry](../../../docs/ui-ra - [`dsh-api-job-controller`](../../api/job-controller/README.md) — the `job.list` and `job.follow` streams, the `job.kill` Remote, and the `ctx.jobs` service behind the rows, the panel, and the stop control. - [`dsh-jobs`](../../jobs/jobs/README.md) — the registry contract that owns the ring and projection semantics. +- [`dsh-client-ui-session-panel`](../ui-session-panel/README.md) — the Session panel that orders, titles, and scrolls this section. - [`dsh-client-ui-primitives`](../ui-primitives/README.md) — the `TerminalBlock` surface the panel configures. ----- diff --git a/packages/client/ui-jobs/README.zh.md b/packages/client/ui-jobs/README.zh.md index 0f226d9973..9107a6cac2 100644 --- a/packages/client/ui-jobs/README.zh.md +++ b/packages/client/ui-jobs/README.zh.md @@ -1,5 +1,5 @@ --- -description: "会话头部后台任务列表:可展开的流式输出面板、进行中/已结束分组,以及无保留输出的已结束任务的静态行。" +description: "会话面板的「后台任务」分栏:可展开的流式输出面板、位于已折叠的已结束列表上方的进行中行,以及无保留输出的已结束任务的静态行。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -`dsh-client-ui-jobs` 在一个头部控件中展示本会话的后台任务,包括生命周期、耗时、进度与终态详情。进行中的任务和保留了输出的已结束任务提供可展开的输出面板;收起即停流。进行中的行以持续更新的时长为主行,随后展示类型与状态。已结束的行折叠在分组标题下;没有保留输出的任务保持静态,包括回答已交给模型的 subagent。 +`dsh-client-ui-jobs` 在会话面板的「后台任务」分栏中展示本会话的后台任务,包括生命周期、耗时、进度与终态详情。进行中的任务和保留了输出的已结束任务提供可展开的输出面板;收起即停流。进行中的行在标签下方展示类型、当前进度与持续更新的时长。已结束的行折叠在计数之下;没有保留输出的任务保持静态,包括回答已交给模型的 subagent。 ## 目录 @@ -25,17 +25,17 @@ kind: "package-reference" ## 使用本包 -通过 web-app 清单加载本插件;在会话看得到至少一个 job 之前它不渲染任何东西,因此普通对话不会为未使用的能力长出控件。 +通过 web-app 清单加载本插件。它在 order 300 注册[会话面板](../ui-session-panel/README.zh.md#contribute-a-section)分栏 `background-jobs`,位于「子智能体」之后,标题为「后台任务」。任务运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;开关挂载期间它保持该会话的任务列表订阅。在会话看得到至少一个 job 之前,该分栏不渲染任何东西,面板因此连同标题一起隐藏它,普通对话不会为未使用的能力显示分栏。 -有运行中或正在停止的任务时,头部显示这些任务的数量;否则显示可见任务总数,可见文字不重复旋转指示器已表达的运行状态。宽布局和紧凑布局中的触发器均通过无障碍描述说明是否有进行中的任务。宽布局下,14px 图标区域在有进行中任务时显示旋转指示器,否则显示 14px 图层图标;根触发器不带展开箭头。容器宽度不超过 460px 时,数量文字隐藏,触发器始终显示图层图标,包括任务运行期间;运行指示器仍在菜单内显示。触发器与更多及侧边栏控件一致:28×28px 图标按钮,无内边距,15px 图标位内显示 15px 图标,使用次级前景色以及 ghost 悬停和按下背景。页头操作在紧凑布局中间距为 8px,宽布局中为 10px。数量工具提示在悬停 500ms 后或获得键盘焦点时立即显示,列表打开期间保持隐藏。 +进行中的行排在最前,最近开始的在前;已结束的行按结束时间从新到旧排在「已结束 {count}」切换按钮之下,箭头紧跟文字,旁边有「清空」操作。有进行中的任务时默认折叠,否则默认展开;用户的选择在 Session 内保持,隐藏后再次显示面板也不变。两个分组各自只显示五行,然后以会话面板的收起控件作为最后一行:「显示其余 {count} 个运行中」或「显示其余 {count} 个已结束」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时分组才收起。这个选择同样在 Session 内保持,「清空」会让已结束分组回到只显示五行。已展开的行被分组收起期间停止观察输出。每行只占 28px 一行:命令,行尾依次是时长、运行时的停止按钮和箭头,遵循会话面板的列;点整行(包括箭头)都能展开或收起。命令放不下时,指针停在这一行上会滚动显示全文;停止按钮悬停 500ms 后显示其操作说明。指针在行上停留 500ms 后,悬停卡片显示任务类型、状态或结束详情以及时长,但不显示命令:命令可能有很多行,展开输出面板后可查看全文并复制;指针停在停止按钮上时不显示悬停卡片;辅助技术把任务类型和状态作为该行的描述读出。以非 0 退出码结束的任务显示警告色圆点,与被停止的任务相同;`failed` 的任务显示错误色圆点。有任务进行中时已结束列表折叠,只剩已结束任务时展开;按下切换按钮会覆盖该默认状态。「清空」在本客户端中隐藏当前已结束的行,Session 保持打开期间一直有效,隐藏后再次显示面板也不变;注册表保留其记录,之后结束的 job 照常出现,没有剩余行时分栏隐藏。 -非触摸指针在文字可见的触发器上悬停 150ms 后打开列表;指针离开触发器和挂载到 portal 的列表后,经过 120ms 关闭。点击宽布局触发器会打开或固定列表;再次点击已固定的触发器会关闭列表。紧凑触发器通过点击切换开关状态,不因悬停打开,包括等待悬停期间数量文字隐藏的情况。ArrowDown 会打开并固定列表,将焦点移至首个控件。在列表内进行指针交互或移入键盘焦点也会固定列表。点击外部或按 Escape 可关闭列表,Tab 将触发器与 portal 内的控件连接起来。切换会话、没有可见任务或组件卸载时,悬停计时器与固定状态都会重置。 +按下可观察的行会展开其输出面板,再次按下则收起;同一时间只展开一行。每个时长都带工具提示:进行中的行为「已运行 {duration}」,已结束的行为「耗时 {duration}」;有任务进行中时,进行中的时长每秒更新一次。 ### 一 job 一行 `ctx.jobs` 镜像的 `job.list` 流是唯一名册:每个 `JobView` 行携带生命周期、时长、实时 `progress` 行或终态 `detail`,以及其保留字节数——进行中的 job,或留有保留输出的已结束 job,就是行可展开的依据。不存在需要 join 的第二份名册。 -运行中的 job 行还带一个两击式停止控件:首击武装,三秒内的确认击调用 `ctx.jobs.kill`,行状态经名册流收敛(先 `stopping`,再入已结束分组,其 detail 携带 `cancelled by the user`)。该 kill 不在模型的播报台账里认领任何东西,任务的 owner agent 因此照常收到标准完成通知——模型被明确告知用户停止了它的任务,而不是留给它去猜([参考](../../jobs/tool-jobs/README.zh.md))。已结束分组在有进行中工作时折叠在其计数之后,并可在客户端清空。 +运行中的 job 行还带一个两击式停止控件,其提示只写「停止任务」,不带命令:首击武装并将其展宽为「确认停止」按钮,三秒内的确认击调用 `ctx.jobs.kill`,行状态经名册流收敛(先 `stopping`,再入已结束列表,其 detail 携带 `cancelled by the user`)。kill 被拒绝时显示「停止失败」四秒。该 kill 不在模型的播报台账里认领任何东西,任务的 owner agent 因此照常收到标准完成通知——模型被明确告知用户停止了它的任务,而不是留给它去猜([参考](../../jobs/tool-jobs/README.zh.md))。 ### 展开的面板 @@ -49,15 +49,16 @@ kind: "package-reference"
实现内幕——点击展开 -头部操作带里的一个 slot 条目(preset 标签之后)渲染触发器;弹出层通过挂载到 body 的 `MenuSurface` 固定定位,避免被停靠面板遮挡或被祖先容器裁剪。CSS 锚点让弹层跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时弹层随页面移动,因此可以超出视觉视口。内部滚动和关闭操作保持可用。所有数据经 `ctx.jobs` 到达——组件不持有任何传输状态。名册跟随挂载:一个 `useEffect` 在控件存活期间保持会话的 `job.list` 流打开。观测跟随可见性:另一个 `useEffect` 为展开行的 job 打开流,并在收起、卸载或弹出层关闭时关闭它。 +一条 `conversation.session.panel.section` 注册渲染分栏正文;会话面板绘制其标题、提供内边距并负责滚动。所有数据经 `ctx.jobs` 到达——组件不持有任何传输状态。名册跟随挂载:一个 `useEffect` 在分栏挂载期间(即会话面板显示期间)保持会话的 `job.list` 流打开。观测跟随可见性:另一个 `useEffect` 为展开行的 job 打开流,并在收起或卸载时关闭它,包括面板隐藏时。 | 文件 | 角色 | |---|---| -| [`src/client/JobListAction.tsx`](src/client/JobListAction.tsx) | 任务列表:分组、时长、面板 | -| [`src/client/index.ts`](src/client/index.ts) | slot 注册与词典 | +| [`src/client/JobsSection.tsx`](src/client/JobsSection.tsx) | 分栏:进行中与已结束的行、时长、停止控件、输出面板 | +| [`src/client/jobs-store.ts`](src/client/jobs-store.ts) | 按 Session 保存已清空行的 store | +| [`src/client/index.ts`](src/client/index.ts) | 会话面板分栏注册与词典 | | [`src/client/locales.ts`](src/client/locales.ts) | `job` 命名空间文案(zh 为事实源) | -后台任务行遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover);带底色运行行内的控件保留紧凑圆角。 +后台任务行使用[嵌套几何规则](../../../docs/ui-radius.zh.md#nested-hover)中的标准菜单项圆角;带底色运行行内的控件保留紧凑圆角。
@@ -68,6 +69,7 @@ kind: "package-reference" - [`dsh-api-job-controller`](../../api/job-controller/README.zh.md) —— 行、面板与停止控件背后的 `job.list`、`job.follow` 流、`job.kill` Remote 与 `ctx.jobs` 服务。 - [`dsh-jobs`](../../jobs/jobs/README.zh.md) —— 拥有环与投影语义的注册表契约。 +- [`dsh-client-ui-session-panel`](../ui-session-panel/README.zh.md) —— 为本分栏排序、绘制标题并负责滚动的会话面板。 - [`dsh-client-ui-primitives`](../ui-primitives/README.zh.md) —— 面板所配置的 `TerminalBlock` 表面。 ----- diff --git a/packages/client/ui-jobs/package.json b/packages/client/ui-jobs/package.json index 299c2c4765..14f52837df 100644 --- a/packages/client/ui-jobs/package.json +++ b/packages/client/ui-jobs/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-jobs", - "description": "Session-header background-job list with on-demand streaming record panels", + "description": "Session panel background-job list with on-demand streaming record panels", "version": "0.2.2-rc.3", "type": "module", "main": "lib/index.js", @@ -39,11 +39,12 @@ "@deepseek-ai/dsh-api-job-controller": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "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-slots": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", @@ -64,8 +65,8 @@ "inject": [ "@deepseek-ai/dsh-api-job-controller", "@deepseek-ai/dsh-client-locale", - "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives" + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel" ], "platform": "web" } diff --git a/packages/client/ui-jobs/src/client/JobListAction.module.css b/packages/client/ui-jobs/src/client/JobListAction.module.css deleted file mode 100644 index 6b72ce3241..0000000000 --- a/packages/client/ui-jobs/src/client/JobListAction.module.css +++ /dev/null @@ -1,502 +0,0 @@ -.trigger { - display: inline-flex; - align-items: center; - gap: 4px; - min-height: 28px; - padding: 3px 2px; - border: 0; - border-radius: var(--dsw-radius-sm); - background: transparent; - color: var(--dsw-alias-label-tertiary); - font-size: 12px; - line-height: 18px; - cursor: pointer; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-secondary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - } -} - -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger .compactIcon { - display: none; -} - -@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); - } - } -} - -/* Portaled above the right sidebar (at most 40) and below modal overlays (1000). */ -.menu { - position: fixed; - z-index: 100; - box-sizing: border-box; - display: flex; - flex-direction: column; - width: 500px; - max-width: min(560px, calc(100vw - 32px)); - max-height: min(480px, calc(100dvh - 140px)); - overflow: hidden; - --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); - --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); - --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); - box-shadow: var(--dsw-elevation-prominent); - position-area: none; - top: max(12px, calc(anchor(bottom) + 5px)); - bottom: 12px; - left: max(12px, anchor(left)); - right: 12px; - position-try-fallbacks: --dsh-jobs-window, --dsh-jobs-opposite, --dsh-jobs-wide-opposite, --dsh-jobs-tall, --dsh-jobs-viewport; - align-self: start; - justify-self: start; - height: fit-content; - min-height: 0; - margin: 0; -} - -.menuBody { - display: flex; - flex-direction: column; - gap: 1px; - min-height: 0; - margin: 0; - padding: 4px; - overflow: auto; - list-style: none; -} - -/* Section labels over the live rows and the settled tail. */ -.sectionHeader { - display: flex; - align-items: center; - justify-content: space-between; - margin: 4px 4px 1px; - padding: 4px 0 3px; - border-top: 0.5px solid var(--dsw-alias-border-l1); - color: var(--dsw-alias-label-tertiary); - font-size: 11px; - line-height: 16px; -} - -/* The leading section needs no divider above it. */ -.sectionHeader:first-child { - margin-top: 0; - border-top: 0; -} - -/* Fold toggle and clear action on the settled section line. */ -.sectionToggle, -.sectionClear { - display: inline-flex; - gap: 3px; - align-items: center; - padding: 2px 4px; - border: 0; - border-radius: var(--dsw-radius-sm); - background: transparent; - color: var(--dsw-alias-label-tertiary); - font-size: 11px; - line-height: 16px; - cursor: pointer; -} - -.sectionToggle:focus-visible, -.sectionClear:focus-visible { - background: var(--dsw-alias-fill-l1); - color: var(--dsw-alias-label-secondary); -} - -@media (hover: hover) { - .sectionToggle:hover, - .sectionClear:hover { - background: var(--dsw-alias-fill-l1); - color: var(--dsw-alias-label-secondary); - } -} - -.sectionChevron { - transform: rotate(-90deg); - transition: transform 120ms ease; -} - -.sectionChevronOpen { - transform: none; -} - -.item { - display: flex; - flex-direction: column; -} - -/* Row plus its optional kill button; the row button keeps its full-width hit - area by flexing, so non-job rows render identically to before. */ -.rowLine { - display: flex; - gap: 6px; - align-items: stretch; -} - -/* Live rows read as filled cards so running work outranks the settled tail; - the inner padding frames the row and both trailing controls on the fill, - and the hover wash sits on the card so the controls never escape it. */ -.rowLineLive { - padding: 4px 8px 4px 2px; - border-radius: var(--dsw-radius-md); - background: var(--dsw-alias-fill-l2); -} - -@media (hover: hover) { - .rowLineLive:hover { - background: color-mix(in srgb, var(--dsw-alias-label-primary) 9%, transparent); - } -} - -/* The kind badge shares the card fill, so it pops on the menu surface instead. */ -.rowLineLive .kind { - background: var(--dsw-specific-menu); -} - -.rowLine .row { - flex: 1; - min-width: 0; -} - -/* The card carries the hover wash; the inner row stays transparent so the - two washes never stack, keeping keyboard focus its own visible state. */ -@media (hover: hover) { - .rowLineLive .row:hover { - background: transparent; - } -} - -.rowLineLive .row { - border-radius: var(--dsw-radius-sm); -} - -.rowLineLive .row:focus-visible { - background: color-mix(in srgb, var(--dsw-alias-label-primary) 6%, transparent); -} - -/* The expand affordance on live rows: a persistent bordered square, so the - control reads as a button before hover (it lives inside the row toggle). */ -.chevronBox { - display: inline-flex; - flex: none; - align-items: center; - align-self: center; - justify-content: center; - width: 20px; - height: 20px; - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: var(--dsw-radius-sm); - background: var(--dsw-specific-menu); -} - -/* Two-press kill affordance on running job rows: same persistent square. */ -.stop { - display: inline-flex; - flex: none; - align-items: center; - align-self: center; - justify-content: center; - width: 20px; - height: 20px; - padding: 0; - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: var(--dsw-radius-sm); - background: var(--dsw-specific-menu); - color: var(--dsw-alias-label-secondary); - cursor: pointer; -} - -.stop:focus-visible { - border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent); - color: var(--dsw-alias-state-error-primary); -} - -@media (hover: hover) { - .stop:hover { - border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent); - 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. */ -.stopArmed, -.stopArmed:focus-visible { - gap: 4px; - width: auto; - padding: 0 7px; - border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent); - background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent); - color: var(--dsw-alias-state-error-primary); -} - -@media (hover: hover) { - .stopArmed:hover { - gap: 4px; - width: auto; - padding: 0 7px; - border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent); - 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); -} - -.row { - display: flex; - align-items: center; - gap: 6px; - box-sizing: border-box; - width: 100%; - min-height: 28px; - padding: 4px 7px; - border: 0; - border-radius: var(--dsw-radius-md); - background: transparent; - color: var(--dsw-alias-label-primary); - font-size: 12px; - line-height: 17px; - text-align: left; - cursor: pointer; -} - -.row:focus-visible { - background: var(--dsw-alias-fill-l1); -} - -@media (hover: hover) { - .row:hover { - background: var(--dsw-alias-fill-l1); - } -} - -/* A row with no observable output offers no interaction. */ -.rowStatic { - cursor: default; -} - -@media (hover: hover) { - .rowStatic:hover { - background: transparent; - } -} - -.rowSettled { - color: var(--dsw-alias-label-tertiary); -} - -/* Live rows align the dot with the first text line, not the row center. */ -.row .rowDot { - flex: none; -} - -.main { - display: flex; - flex: 1; - flex-direction: column; - gap: 2px; - min-width: 0; -} - -.primary { - display: flex; - align-items: baseline; - gap: 8px; - min-width: 0; -} - -.secondary { - display: flex; - align-items: center; - gap: 6px; - min-width: 0; -} - -.kind { - flex: none; - padding: 0 5px; - border-radius: var(--dsw-radius-xs); - background: var(--dsw-alias-fill-l2); - color: var(--dsw-alias-label-secondary); - font-size: 10px; - line-height: 16px; -} - -.label { - flex: 1; - min-width: 0; - overflow: hidden; - font-family: var(--dsw-font-mono); - white-space: nowrap; - text-overflow: ellipsis; -} - -/* A failed task's detail is the producer's raw text, so it has no bound; - without this it widens the row past the menu instead of eliding like .label. */ -.status { - flex: none; - max-width: 60%; - overflow: hidden; - color: var(--dsw-alias-label-tertiary); - font-size: 10px; - line-height: 16px; - white-space: nowrap; - text-overflow: ellipsis; -} - -.duration { - flex: none; - color: var(--dsw-alias-label-tertiary); - font-size: 11px; - line-height: 18px; - font-variant-numeric: tabular-nums; -} - -.chevron { - flex: none; - color: var(--dsw-alias-label-tertiary); -} - -.chevronOpen { - transform: rotate(180deg); -} - -.panel { - margin: 0 8px 8px; - /* 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. The override targets the card - element itself because the gutter variable is declared on it — a value - inherited from this container would lose to that declaration. */ -.panel :global([data-terminal]) { - --dsl-terminal-gutter: 12px; -} - -.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); -} - -@position-try --dsh-jobs-window { - position-area: none; - top: max(12px, calc(anchor(bottom) + 5px)); - bottom: 12px; - left: 12px; - right: 12px; - margin: 0; - align-self: safe start; - justify-self: safe end; -} - -@position-try --dsh-jobs-opposite { - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: max(12px, calc(anchor(top) + 5px)); - align-self: end; -} - -@position-try --dsh-jobs-wide-opposite { - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: max(12px, calc(anchor(top) + 5px)); - left: 12px; - right: 12px; - align-self: end; - justify-self: safe end; -} - -@position-try --dsh-jobs-tall { - position-area: none; - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: 12px; - left: max(12px, anchor(left)); - right: 12px; - margin: 0; - align-self: safe start; - justify-self: start; -} - -@position-try --dsh-jobs-viewport { - position-area: none; - inset: max(12px, var(--dsh-frame-overlay-top, 12px)) 12px 12px; - margin: 0; - align-self: safe start; - justify-self: safe end; -} diff --git a/packages/client/ui-jobs/src/client/JobListAction.tsx b/packages/client/ui-jobs/src/client/JobListAction.tsx deleted file mode 100644 index 1c88d77ef9..0000000000 --- a/packages/client/ui-jobs/src/client/JobListAction.tsx +++ /dev/null @@ -1,637 +0,0 @@ -import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react' -import { createPortal } from 'react-dom' -import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' -import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { - IconChevronDownOutlineRegular, IconLayersOutlineRegular, IconStopFillRegular, MenuSurface, StateDot, TerminalBlock, Tooltip, - useDismissOnOutsidePointer, - type StateDotState, type TerminalBlockLabels, -} 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 css from './JobListAction.module.css' - -/** Registration-side business face for the job list. */ -export interface JobListInjected { - 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-header job-list action. */ -export type JobListActionProps = - PropsRuntime<'conversation.session.header.actions'> - & PropsLocale - & InjectFace - -/** Stable empty list so a session with no jobs keeps one array identity. */ -const NO_JOBS: readonly JobView[] = [] - -/** Keyboard-reachable controls inside the list, in document order. */ -const FOCUSABLE = 'button:not(:disabled), a[href], [tabindex]:not([tabindex="-1"])' - -/** 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. - */ -function dotState(status: JobView['status']): StateDotState { - switch (status) { - case 'running': return 'ongoing' - case 'stopping': return 'warning' - case 'completed': return 'done' - case 'killed': return 'warning' - case 'failed': return 'error' - /* v8 ignore next -- closed wire status union */ - default: return assertNever(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 in start order, then settled rows newest-first. 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 left.startedAt - right.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, t }: { - 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 durationCell = ( - - {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-open-in-app/src/client/controller.ts b/packages/client/ui-open-in-app/src/client/controller.ts index bd43f8af7e..9d2eba76ce 100644 --- a/packages/client/ui-open-in-app/src/client/controller.ts +++ b/packages/client/ui-open-in-app/src/client/controller.ts @@ -99,17 +99,19 @@ export class OpenInAppController { private async run(): Promise { let apps: readonly string[] = [] + let payload: OpenInAppAppsPayload | undefined try { - const response = await this.fetcher(OPEN_IN_APP_APPS_ROUTE, { - headers: { accept: 'application/json' }, - }) - if (response.ok) { - const payload = await response.json() as OpenInAppAppsPayload - if (Array.isArray(payload.apps)) apps = payload.apps.filter(id => typeof id === 'string') - } - } catch (_error) { - // An unreachable Host supplies no directory openers in menus or controls. + payload = await this.readAppsPayload() + } catch (_appsUnavailable) { + // An unreachable Host or an unreadable reply supplies no directory openers in menus or controls. } + if (Array.isArray(payload?.apps)) apps = payload.apps.filter(id => typeof id === 'string') this.apps.set(apps) } + + /** The Host's opener payload, or `undefined` for a non-OK reply; rejects when the Host or its reply is unreadable. */ + private async readAppsPayload(): Promise { + const response = await this.fetcher(OPEN_IN_APP_APPS_ROUTE, { headers: { accept: 'application/json' } }) + return response.ok ? await response.json() as OpenInAppAppsPayload : undefined + } } diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index 85ea703b5d..1d2d10c4d9 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -96,7 +96,7 @@ export class OpenInAppPathController { let ok = false try { ok = (await this.remote.session.openWorkspacePath(request)).ok - } catch { + } catch (_hostUnreachable) { // Swallows carrier rejections: a Host that cannot be reached failed the // gesture like a Host that refused it, and the control announces that. } @@ -173,14 +173,13 @@ export class OpenInAppPathController { } private async run(): Promise { - let available = false + let result: RemoteResult | undefined try { - const result = await this.remote.session.canOpenWorkspacePath() - available = result.ok && result.value - } catch { + result = await this.remote.session.canOpenWorkspacePath() + } catch (_hostUnreachable) { // Swallows carrier rejections: an unreachable Host reads as no desktop, // so the preview shows no path control rather than a broken one. } - this.desktop.set(available) + this.desktop.set(result?.ok === true && result.value) } } diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 008c6b8907..9cc32a1ba4 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: 33a5b39959a595c6 zh: efd1088e9f13ed67 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 320dba9d3737458f - zh: efd132302c7e17f4 + en: 07574e4640e01163 + zh: cc3f074a6ec0a17d /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: fd3499ef403a0594 zh: 3a17727316d3c666 @@ -27,8 +27,8 @@ en: 7fed4894a6d0d568 zh: c22881bfcef2d4b6 /deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy: - en: 3fd7072b662eed0a - zh: 88c6c299c0a6f8cd + en: 90c17f874ec27b52 + zh: 21bf452318578f03 /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation: en: 88448dce667337fe zh: 5d9b6035191a0b08 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index cc25340659..c7745cac13 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -55,6 +55,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 +65,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 +80,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. | @@ -133,7 +134,7 @@ 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. ----- diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 9ca3abc2ba..6fad582dde 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -55,6 +55,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 +65,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 +80,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 浏览器与文件夹插画,用于侧栏引导入口。 | @@ -133,7 +134,7 @@ 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 动画与弹窗生命周期计时。普通下拉菜单不经过右键菜单的准备延迟。 ----- diff --git a/packages/client/ui-primitives/package.json b/packages/client/ui-primitives/package.json index 6702ddf30d..10148e5f70 100644 --- a/packages/client/ui-primitives/package.json +++ b/packages/client/ui-primitives/package.json @@ -44,7 +44,7 @@ "@types/mdast": "^4.0.4", "micromark-factory-space": "^2.0.1", "micromark-extension-math": "^3.1.0", - "mdast-util-from-markdown": "^2.0.3", + "mdast-util-from-markdown": "^2.1.0", "mdast-util-gfm": "^3.1.0", "mdast-util-math": "^3.0.0", "micromark-extension-gfm": "^3.0.0", diff --git a/packages/client/ui-primitives/src/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/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/icons/artwork.ts b/packages/client/ui-primitives/src/icons/artwork.ts index 76e4235739..c3fd3ef4d0 100644 --- a/packages/client/ui-primitives/src/icons/artwork.ts +++ b/packages/client/ui-primitives/src/icons/artwork.ts @@ -95,6 +95,7 @@ export const ICON_ARTWORK = { '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 => `` }, diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 1b4aa7eca7..7ed1d9c2aa 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -462,6 +462,12 @@ export const IconListPenOutlineRegular = productIcon('list-pen-outline', 'regula /** Medium IconListPenOutline artwork with a 1.3px stroke. */ export const IconListPenOutlineMedium = productIcon('list-pen-outline', 'medium') +/** Regular one-pixel IconFilesDiffOutline artwork. */ +export const IconFilesDiffOutlineRegular = productIcon('files-diff-outline', 'regular') + +/** Medium IconFilesDiffOutline artwork with a 1.3px stroke. */ +export const IconFilesDiffOutlineMedium = productIcon('files-diff-outline', 'medium') + /** Regular one-pixel IconGoalOutline artwork. */ export const IconGoalOutlineRegular = productIcon('goal-outline', 'regular') diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 3f1756bfbf..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' 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={
    first body
    } /> + 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/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-schedule/src/client/TaskManagerPage.module.css b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css index 41edcf0370..1d49839577 100644 --- a/packages/client/ui-schedule/src/client/TaskManagerPage.module.css +++ b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css @@ -1365,8 +1365,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; } 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/tests/task-manager-page.client.spec.tsx b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx index e7f2ca44e4..33eb9e2628 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 @@ -2127,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) @@ -2140,9 +2140,16 @@ describe('Task manager deletion', () => { // installed. The dialog's cap must follow the padding of the Modal layer // that holds it, and the scrolling content must sit inside that cap instead // of pinning a number that a wrong layer padding could not contradict. - installStyles({ confirmDialog: css.confirmDialog, confirmContent: css.confirmContent }) + installStyles({ confirmDialog: css.confirmDialog, confirmContent: css.confirmContent, confirmPrompt: css.confirmPrompt }) expect(getComputedStyle(dialog).maxHeight).toBe(`calc(100dvh - ${MODAL_LAYER_PADDING * 2}px)`) expect(getComputedStyle(content).overflowY).toBe('auto') + // The instruction is a three-line excerpt, so a long one cannot stretch the dialog. + const prompt = within(content).getByText(/^Review release/) + const clamp = getComputedStyle(prompt) + expect(clamp.display).toBe('-webkit-box') + expect(clamp.getPropertyValue('-webkit-box-orient')).toBe('vertical') + expect(clamp.overflow).toBe('hidden') + expect(clamp.getPropertyValue('-webkit-line-clamp')).toBe('3') const footer = dialog.lastElementChild as HTMLElement expect(getComputedStyle(footer).flexShrink).toBe('0') fireEvent.click(confirm) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml new file mode 100644 index 0000000000..b2577faa28 --- /dev/null +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -0,0 +1,43 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-session-panel/README.md +/: + en: 8409e6477f312897 + zh: b982bc13dfe0e002 +/deepseek-ai-dsh-client-ui-session-panel: + en: aff5b9d70836e810 + zh: 2cb8c75d3c82fba9 +/deepseek-ai-dsh-client-ui-session-panel/summary: + en: b5a091528bf5375a + zh: 48a22fec747fb07a +/deepseek-ai-dsh-client-ui-session-panel/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-client-ui-session-panel/use-this-package: + en: 62a513f72d48d6e2 + zh: 7f0eb3e873c0473f +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/docking-and-the-overlay: + en: 67b33b9f412a687d + zh: 2a9b8c89c8bb22e4 +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/contribute-a-section: + en: b76852d8740aee0f + zh: ccfeb7774e1b0e27 +/deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: + en: ede595ecc4aab24a + zh: 5a30a4042ab7483a +/deepseek-ai-dsh-client-ui-session-panel/further-exploration: + en: 09b403af819bd155 + zh: e949998de4794393 +/deepseek-ai-dsh-client-ui-session-panel/model-experience: + en: 7e8bbe318a76fd54 + zh: c60e87da2a37642a +/deepseek-ai-dsh-client-ui-session-panel/model-experience/kv-cache-effect: + en: 47f982e326fe77fd + zh: 275b2ef7eec3ab19 +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work: + en: d5cf7883b7f7e0ab + zh: f5407439447acc44 +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: b532016223ceceef diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md new file mode 100644 index 0000000000..43ba71d18e --- /dev/null +++ b/packages/client/ui-session-panel/README.md @@ -0,0 +1,134 @@ +--- +description: "The Session panel: a header toggle and a floating panel in the Chat View's aside whose sections other plugins register, with the built-in Environment section." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-session-panel + +English | [中文](README.zh.md) + +## Summary + +`dsh-client-ui-session-panel` adds a Session header toggle that shows or hides a floating panel of facts about the current Session. The panel lives in the Chat View: it docks in the Chat View's end gutter when the gutter can hold it, and otherwise opens over the transcript on request. It draws section titles and leaves section content to the plugins that register sections; it ships the Environment section with the working folder row. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +The `@deepseek-ai/dsh-web-app` bundle loads this package by default. The toggle is the first Session header utility, before sharing and the schedule catalog. It is an icon button with the panel name and its indicators as its accessible name, a tooltip that says whether a press shows or hides the panel, shown after 500ms of hover or at once on keyboard focus, and `aria-expanded` for whether the panel shows. + +### Docking and the overlay + +The panel docks while the gutter between the transcript column and the Chat frame's end edge is at least 348px: 40px clear of the column and its width handle, the panel's 300px minimum width, and an 8px edge margin. Docked, it is 300–360px wide, 8px from the end edge, starts 12px below the header, stops above the composer stack, and scrolls inside itself in a reserved scrollbar column 2px from its end edge, so its content keeps one width whether or not it scrolls. Pressing the toggle then flips one docking preference that every Session shares and that persists in `localStorage` under `dsh.sessionPanel.pinned`; the panel docks by default. + +A narrower gutter hides the docked panel, so it never covers the transcript. This includes a narrow window, an expanded right sidebar, and a dragged-wide transcript column. Pressing the toggle then opens the panel over the transcript with the prominent elevation, 280px wide so it covers less of the transcript than the docked panel takes beside it, 8px from the end edge, above the composer stack and not covering it. The overlay closes from the toggle, on Escape, and on a pointer press outside the panel, the toggle, and any open menu, such as a row's context menu; Escape returns focus to the toggle when focus was inside the panel. A modal above the page, an input method composing text, and a handler that already took the key, such as an open menu's, keep Escape; otherwise the overlay takes it first, so with the overlay open the first Escape from the composer closes the overlay and does not count toward stopping a running turn. Closing it does not change the docking preference. At most one Session's overlay is open; it closes once the gutter widens enough to dock and once no Chat View shows the Session, as after switching to another Session or View, and switching back does not reopen it. When the panel hides while focus is inside it, focus moves to the toggle. + +Other Views, such as the trajectory View, show no panel. While no Chat View shows the Session, the toggle is unavailable: it stays in the header with its indicators, dimmed, and its tooltip asks to switch to the Chat view. + + +### Contribute a section + +A section is one `conversation.session.panel.section` list registration: `id` addresses it, `order` sorts it ascending, and the required `label` is its title, which the panel draws in the active locale. The section component receives `presentation` (`docked` or `overlay`) and `dismissOverlay()` as owner props; it renders its body and renders nothing when it has nothing to show, which hides its title too. Register trailing title controls, such as a count or a refresh button, in the keyed `conversation.session.panel.section.actions` slot under the section's `id`. A section without a label is reported to the console and not shown. The shipped sections are Environment (`order: 0`), Change requests from the [forge bundle](../../experimental/client-ui-forge/README.md) (`100`), [Subagents](../ui-subagent/README.md) (`200`), [Shared tasks](../ui-agent-team/README.md) (`250`), and [Background jobs](../ui-jobs/README.md) (`300`). + +Plugins share a title by registering rows in a section owner's row slot. The built-in Environment section (`id: 'environment'`, `order: 0`) declares `conversation.session.panel.environment.row`, whose rows receive the same owner props as a section; its `project` row (`order: 0`) shows the Session's working folder: the current directory from the `workingDirectory` projection, or, before the projection arrives or when it records none, the directory the Session was created in, then the directory of the Workspace that lists the Session. The row shows the folder name followed by its parent folder in tertiary ink, which clips with an ellipsis; its tooltip, shown after 500ms of hover, names the working folder and gives the full path. Both abbreviate the Host home to `~`. Right-clicking the row or pressing its More button opens the shared `directory` context menu. The forge bundle adds its checkout and local changes rows at orders 20 and 30. A plugin that owns a shared section declares its own row slot the same way. + +Marks that must stay visible while the panel is hidden, such as an attention dot, go in the `conversation.session.panel.indicator` list. Each occupant is one element: the toggle sizes it to a 6px dot at the glyph's corner, and the occupant sets its `background` and includes text that names it, which becomes part of the toggle's accessible name. Occupants overlap, and a higher `order` paints above a lower one. The `panelShown` owner prop lets a mark that only repeats the panel's content render nothing while the panel shows. Subagents and Background jobs show a blue dot while work runs and the panel does not show (orders 10 and 20); the forge bundle's red attention dot (order 100) paints above them and stays while the panel shows. + +Rows share one look without sharing a component. A section's component, or an Environment row entry, writes its row's markup and marks the parts, and the panel's stylesheet lays them out, so icon, text, and trailing areas line up across packages while each package owns what its row contains. + +| Mark | Part | +|---|---| +| `data-session-panel-row` | The row: one 28px line. A row with an action or a menu highlights as a whole on hover and while one of its menus is open. | +| `data-row-part="body"` | The icon and the text. A ` +
    + ) +} diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.module.css b/packages/client/ui-session-panel/src/client/ProjectRow.module.css new file mode 100644 index 0000000000..0e99b68fd7 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/ProjectRow.module.css @@ -0,0 +1,41 @@ +/* [name] · [parent]: the name keeps its width up to the row, and the parent + fills the rest of the line and clips with an ellipsis. With less than 5em + left for it, the parent wraps onto a second line, which the one-line height + hides, so the row never shows a separator without a parent. The separator + is decorative, so assistive technology reads the name and the parent alone. */ + +.folder { + display: flex; + flex-wrap: wrap; + align-items: baseline; + min-width: 0; + height: 1lh; + overflow: hidden; + white-space: nowrap; +} + +.folder:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} + +.name { + flex: 0 1 auto; + min-width: 0; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; +} + +.parent { + flex: 1 1 0; + min-width: 5em; + overflow: hidden; + color: var(--dsw-alias-label-tertiary); + text-overflow: ellipsis; +} + +.parent::before { + padding: 0 4px; + content: '·' / ''; +} diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.tsx b/packages/client/ui-session-panel/src/client/ProjectRow.tsx new file mode 100644 index 0000000000..15f64d245d --- /dev/null +++ b/packages/client/ui-session-panel/src/client/ProjectRow.tsx @@ -0,0 +1,51 @@ +/** Environment row naming the Session's working folder. */ +import type { ReactNode } from 'react' +import { IconFolderCloseRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { abbreviateHomePath, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' +import type {} from '@deepseek-ai/dsh-working-directory/types' +import type { ProjectRowProps } from './slots.ts' +import css from './ProjectRow.module.css' + +const ROOT = /^(?:[/\\]|[A-Za-z]:[/\\])$/ + +/** + * Render the Session's working folder as its name followed by its parent + * folder, with the label and the full path in the tooltip. The folder is the + * Session's current working directory; before that projection arrives, or + * when it records none, it is the directory the Session was created in, else + * the Workspace that lists the Session. Paths under the Host account home + * start with `~`. The row and its More button open the directory context menu. + * @param props - Session values, the working directory projection, Workspace and Session list hooks, Host facts, menu bindings, and copy. + * @returns the row, or null before the Session's directory is known. + */ +export function ProjectRow({ + sessionId, useProjection, useWorkspaces, useSessions, useHost, useContextMenu, renderFactorySlot, t, +}: ProjectRowProps): ReactNode { + const current = useProjection('workingDirectory') + const createdIn = useSessions(snapshot => snapshot.byId[sessionId]?.cwd) + const workspacePath = useWorkspaces(snapshot => snapshot.items.find(item => item.sessionIds.includes(sessionId))?.path) + const home = useHost(facts => facts.home) + const { getTriggerProps } = useContextMenu() + const path = current ?? createdIn ?? workspacePath + if (path === undefined) return null + const shown = abbreviateHomePath(path, home) + const { directory, name } = pathPartsOf(shown) + const parent = ROOT.test(directory) ? directory : directory.replace(/[/\\]+$/, '') + const target = { kind: 'directory', value: { sessionId, path } } as const + return ( +
    + + + + + + {name} + {parent !== '' && {parent}} + + + + + {renderFactorySlot('contextMenu.button', { target, label: t('project.actions') })} +
    + ) +} diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css new file mode 100644 index 0000000000..f16ef86393 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -0,0 +1,373 @@ +/* The panel floats in the Chat View's aside layer, a zero-height box across + the top of the Chat frame that passes pointer events through. The layer + inherits the scrollport's --dsh-conversation-viewport-height and + --dsh-composer-height and publishes --dsh-chat-aside-gutter, the inline + space between the transcript column and the frame's end edge. */ + +/* The docked panel's inline metrics: 40px clear of the transcript column, + past its width handle, 8px from the end edge, and at least 300px wide. The + panel's width and the dock probe both derive from them, so the gutter that + docks the panel is exactly the one that holds its minimum width. */ +.panel, +.dockProbe { + --panel-clear: 40px; + --panel-edge: 8px; + --panel-min-width: 300px; +} + +.panel { + position: absolute; + top: 12px; + right: var(--panel-edge); + box-sizing: border-box; + width: clamp( + var(--panel-min-width), + calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge)), + 360px + ); + /* Stops above the composer stack, whose seat fades and takes presses across the body's full width. */ + max-height: calc(var(--dsh-conversation-viewport-height, 100dvh) - var(--dsh-composer-height, 152px) - 24px); + overflow-y: auto; + overscroll-behavior: contain; + /* The bar has a place of its own: the content keeps its width whether or not + the panel scrolls, and the end inset stays 8px. A transparent end border + over the panel's own background holds the bar 2px from the edge, as the + sidebar does, and the track margin keeps the thumb out of the rounded corners. */ + scrollbar-gutter: stable; + --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); + --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); + --dsh-scrollbar-track-margin: 12px; + padding: 6px calc(8px - 2px - var(--dsh-scrollbar-width)) 6px 8px; + border: 0; + border-right: 2px solid transparent; + /* The standard menu tier: a compact summary surface, not an enclosing panel. */ + border-radius: var(--dsw-radius-lg); + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-bg-layer-1); + box-shadow: var(--dsw-elevation-panel); + pointer-events: auto; + animation: dsh-session-panel-enter 120ms ease-out; +} + +/* Over the transcript the panel is narrower than docked, so it covers less of + the transcript, and takes the prominent elevation. */ +.panel[data-session-panel='overlay'] { + width: min(280px, calc(100% - 2 * var(--panel-edge))); + box-shadow: var(--dsw-elevation-prominent); +} + +/* The dock probe tells the plugin whether the gutter holds the docked panel + without a pixel measurement: it is 1px wide from the gutter that fits the + panel's minimum width and 0 below it, a width under 0 being used as 0. A + size observer on it therefore reports only when the docking decision + flips, not while the window resizes on one side of it or the transcript + grows. It has no height and takes no pointer events. */ +.dockProbe { + position: absolute; + top: 0; + right: 0; + width: calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px); + max-width: 1px; + height: 0; + visibility: hidden; + pointer-events: none; +} + +.section { + padding: 4px 0 6px; +} + +/* An empty body hides its section: a plain section renders into one outlet + anchor, and a shared section renders its own row outlet inside it. */ +.section:has(> .body > [data-slot]:empty), +.section:has(> .body > [data-slot] > [data-slot]:only-child:empty) { + display: none; +} + +.section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty)) + ~ .section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty)) { + margin-top: 2px; + padding-top: 8px; + border-top: 0.5px solid var(--dsw-alias-border-l2); +} + +.head { + display: flex; + align-items: center; + gap: 8px; + min-height: 24px; + padding: 0 6px; +} + +/* Secondary ink at medium weight: apart from the primary rows below and the tertiary counts beside it. */ +.title { + flex: 0 1 auto; + min-width: 0; + margin: 0; + overflow: hidden; + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xxs-12); + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* Takes what the title leaves and clips first, so long progress never squeezes the title. */ +.actions { + display: inline-flex; + flex: 1 1000 0; + align-items: center; + justify-content: flex-end; + gap: 2px; + min-width: 0; + overflow: hidden; +} + +.actions:has(> [data-slot]:empty) { + display: none; +} + +@keyframes dsh-session-panel-enter { + from { opacity: 0; transform: translateY(-4px); } + to { opacity: 1; transform: translateY(0); } +} + +@media (prefers-reduced-motion: reduce) { + .panel { + animation: none; + } +} + +/* Rows. The rows of every section share one look without sharing a + component: each contributor writes its row's markup and marks the parts, + and these rules lay them out. + + [data-session-panel-row] the row: one 28px line + [data-row-part='body'] the icon and the text; a + + ) +} diff --git a/packages/client/ui-session-panel/src/client/element-ids.ts b/packages/client/ui-session-panel/src/client/element-ids.ts new file mode 100644 index 0000000000..f6e881ee55 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/element-ids.ts @@ -0,0 +1,20 @@ +/** DOM ids that connect a Session's toggle and panel across their separate slot entries. */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' + +/** + * Id of a Session's panel element, which the toggle names in `aria-controls`. + * @param sessionId - Session that owns the panel. + * @returns the element id. + */ +export function panelElementId(sessionId: SessionId): string { + return `dsh-session-panel-${sessionId}` +} + +/** + * Id of a Session's toggle, which receives focus when its overlay closes from the keyboard. + * @param sessionId - Session whose header holds the toggle. + * @returns the element id. + */ +export function toggleElementId(sessionId: SessionId): string { + return `dsh-session-panel-toggle-${sessionId}` +} diff --git a/packages/client/ui-session-panel/src/client/index.ts b/packages/client/ui-session-panel/src/client/index.ts new file mode 100644 index 0000000000..e75283bca3 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/index.ts @@ -0,0 +1,109 @@ +/** + * Session panel plugin, browser half: a Session header toggle and a floating + * panel in the Chat View's aside. The panel draws the titles of the sections + * other plugins register, lays out the rows they mark, offers the fold control + * their lists end with and the details their rows show on hover, and ships the + * Environment section with the working folder row. + */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-chat/client' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-connection/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { EnvironmentSection } from './EnvironmentSection.tsx' +import { PanelDetails } from './PanelDetails.tsx' +import { PanelFold } from './PanelFold.tsx' +import { ProjectRow } from './ProjectRow.tsx' +import { SessionPanel } from './SessionPanel.tsx' +import { SessionPanelToggle } from './SessionPanelToggle.tsx' +import { sectionSource } from './sections.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from './slots.ts' +import { SessionPanelState } from './visibility.ts' +import { de, en, es, fr, ja, NS, pt, ru, zh, type SessionPanelKey } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Session panel copy. */ + sessionPanel: SessionPanelKey + } +} + +export type { + EnvironmentSectionProps, PanelDetailsFact, PanelDetailsProps, PanelFoldProps, ProjectRowInjected, ProjectRowProps, SessionPanelDockable, + SessionPanelIndicatorOwnerProps, SessionPanelInjected, SessionPanelPresentation, SessionPanelProbes, SessionPanelProps, + SessionPanelSectionEntry, SessionPanelSectionOwnerProps, SessionPanelToggleInjected, SessionPanelToggleProps, SessionPanelVisibility, +} from './slots.ts' + +/** Required services: the slot registry, dictionaries, and the Host facts of the Remote carrier. */ +export const inject = ['slots', 'locale', 'remote'] + +/** + * Client plugin body: register the dictionaries, the fold control and row + * details Factories, the header toggle, the panel, and the Environment section + * with its project row. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-session-panel: dictionaries') + const t = ctx.locale.bind(NS) + const state = new SessionPanelState() + ctx.effect(() => () => { state.dispose() }, 'ui-session-panel: overlay follower and dock probes') + const sections = sectionSource(ctx) + const host: ObservableSnapshot = { + getSnapshot: () => ctx.remote.$host, + subscribe: listener => ctx.on('connection/reset', listener), + } + + ctx.slots.registerFactory({ name: 'conversation.session.panel.fold', scope: 'root' }, PanelFold) + ctx.slots.registerFactory({ name: 'conversation.session.panel.details', scope: 'root' }, PanelDetails) + + ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({ + name: 'conversation.session.header.utilities', + id: 'session-panel', + // The first utility: left of change requests, sharing, and the schedule catalog. + order: -10, + locale: NS, + children: { + 'conversation.session.panel.indicator': { kind: 'list', scope: 'session', inline: true }, + }, + inject: (): SessionPanelToggleInjected => ({ + hooks: { visibility: state.visibility, dockable: state.dockable }, + toggle: (sessionId) => { state.toggle(sessionId) }, + }), + }, SessionPanelToggle)) + + ctx.slots.inject('conversation.chat.aside', () => ctx.slots.register({ + name: 'conversation.chat.aside', + locale: NS, + children: { + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + }, + inject: (): SessionPanelInjected => ({ + hooks: { visibility: state.visibility, sections, probes: state.probes }, + createProbeRef: (sessionId, probe) => state.createProbeRef(sessionId, probe), + closeOverlay: (sessionId) => { state.closeOverlay(sessionId) }, + }), + }, SessionPanel)) + + ctx.slots.inject('conversation.session.panel.section', () => ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'environment', + order: 0, + label: () => t('section.environment'), + children: { + 'conversation.session.panel.environment.row': { kind: 'list', scope: 'session' }, + }, + }, EnvironmentSection)) + + ctx.slots.inject('conversation.session.panel.environment.row', () => ctx.slots.register({ + name: 'conversation.session.panel.environment.row', + id: 'project', + order: 0, + locale: NS, + inject: (): ProjectRowInjected => ({ hooks: { host } }), + }, ProjectRow)) +} diff --git a/packages/client/ui-session-panel/src/client/locales.ts b/packages/client/ui-session-panel/src/client/locales.ts new file mode 100644 index 0000000000..1264e8ad94 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/locales.ts @@ -0,0 +1,95 @@ +/** `sessionPanel` namespace dictionaries. */ + +/** Dictionary namespace owned by this plugin. */ +export const NS = 'sessionPanel' + +/** Simplified Chinese dictionary (the key-set source of truth). */ +export const zh = { + 'panel.name': '会话面板', + 'toggle.show': '显示会话面板', + 'toggle.hide': '隐藏会话面板', + 'toggle.unavailable': '切换到「对话」视图后可显示会话面板', + 'section.environment': '环境', + 'project.label': '工作目录', + 'project.actions': '工作目录操作', +} as const + +/** Every key of the `sessionPanel` namespace. */ +export type SessionPanelKey = keyof typeof zh + +/** English dictionary, key-identical to the Chinese source of truth. */ +export const en: Record = { + 'panel.name': 'Session panel', + 'toggle.show': 'Show session panel', + 'toggle.hide': 'Hide session panel', + 'toggle.unavailable': 'Switch to the Chat view to show the session panel', + 'section.environment': 'Environment', + 'project.label': 'Working folder', + 'project.actions': 'Working folder actions', +} + +/** Japanese dictionary. */ +export const ja = { + 'panel.name': 'セッションパネル', + 'toggle.show': 'セッションパネルを表示', + 'toggle.hide': 'セッションパネルを非表示', + 'toggle.unavailable': '「チャット」ビューに切り替えるとセッションパネルを表示できます', + 'section.environment': '環境', + 'project.label': '作業フォルダー', + 'project.actions': '作業フォルダーの操作', +} satisfies Record + +/** Spanish dictionary. */ +export const es = { + 'panel.name': 'Panel de la sesión', + 'toggle.show': 'Mostrar el panel de la sesión', + 'toggle.hide': 'Ocultar el panel de la sesión', + 'toggle.unavailable': 'Cambia a la vista Chat para mostrar el panel de la sesión', + 'section.environment': 'Entorno', + 'project.label': 'Carpeta de trabajo', + 'project.actions': 'Acciones de la carpeta de trabajo', +} satisfies Record + +/** French dictionary. */ +export const fr = { + 'panel.name': 'Panneau de session', + 'toggle.show': 'Afficher le panneau de session', + 'toggle.hide': 'Masquer le panneau de session', + 'toggle.unavailable': 'Passez à la vue Discussion pour afficher le panneau de session', + 'section.environment': 'Environnement', + 'project.label': 'Dossier de travail', + 'project.actions': 'Actions sur le dossier de travail', +} satisfies Record + +/** German dictionary. */ +export const de = { + 'panel.name': 'Sitzungsbereich', + 'toggle.show': 'Sitzungsbereich anzeigen', + 'toggle.hide': 'Sitzungsbereich ausblenden', + 'toggle.unavailable': 'Wechseln Sie zur Ansicht „Chat“, um den Sitzungsbereich anzuzeigen', + 'section.environment': 'Umgebung', + 'project.label': 'Arbeitsordner', + 'project.actions': 'Aktionen für den Arbeitsordner', +} satisfies Record + +/** Russian dictionary. */ +export const ru = { + 'panel.name': 'Панель сеанса', + 'toggle.show': 'Показать панель сеанса', + 'toggle.hide': 'Скрыть панель сеанса', + 'toggle.unavailable': 'Переключитесь на вид «Чат», чтобы показать панель сеанса', + 'section.environment': 'Среда', + 'project.label': 'Рабочая папка', + 'project.actions': 'Действия с рабочей папкой', +} satisfies Record + +/** Brazilian Portuguese dictionary. */ +export const pt = { + 'panel.name': 'Painel da sessão', + 'toggle.show': 'Mostrar painel da sessão', + 'toggle.hide': 'Ocultar painel da sessão', + 'toggle.unavailable': 'Mude para a visualização Chat para mostrar o painel da sessão', + 'section.environment': 'Ambiente', + 'project.label': 'Pasta de trabalho', + 'project.actions': 'Ações da pasta de trabalho', +} satisfies Record diff --git a/packages/client/ui-session-panel/src/client/sections.ts b/packages/client/ui-session-panel/src/client/sections.ts new file mode 100644 index 0000000000..fcc9feed5e --- /dev/null +++ b/packages/client/ui-session-panel/src/client/sections.ts @@ -0,0 +1,66 @@ +/** Projection of the section list's registrations into the titles the panel draws. */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import { resolveSlotLabel, type StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionPanelSectionEntry } from './slots.ts' + +const SECTION_SLOT = 'conversation.session.panel.section' + +/** + * Project live section registrations in display order. A registration + * without a label cannot be titled; it is reported and left out. + * @param entries - shadowing winners of the section list in ledger order. + * @param report - receives one message per unlabeled registration. + * @returns sections ordered by ascending `order`, then registration order. + */ +export function projectSections( + entries: readonly StoredEntry[], report: (message: string) => void, +): readonly SessionPanelSectionEntry[] { + const rows: (SessionPanelSectionEntry & { readonly order: number })[] = [] + for (const entry of entries) { + /* v8 ignore next -- list registration validates id at load. */ + const id = entry.options.id ?? '' + const label = resolveSlotLabel(entry.options.label) + if (label === undefined || label === '') { + report(`ui-session-panel: section "${id}" from ${entry.registrant ?? 'an unknown registrant'} has no label and is not shown`) + continue + } + rows.push({ id, label, order: entry.options.order ?? 0 }) + } + return rows.sort((a, b) => a.order - b.order).map(({ id, label }) => ({ id, label })) +} + +/** + * Observable section roster: recomputed when the section list's ledger or + * the active locale changes, and identity-stable between changes. + * @param ctx - client context whose slot registry and locale the roster follows. + * @returns the section source. + */ +export function sectionSource(ctx: ClientContext): ObservableSnapshot { + let version = -1 + let revision = -1 + let sections: readonly SessionPanelSectionEntry[] = [] + return { + getSnapshot: () => { + const nextVersion = ctx.slots.getVersion(SECTION_SLOT) + const nextRevision = ctx.locale.getSnapshot().revision + if (nextVersion !== version || nextRevision !== revision) { + const reportOnce = version !== nextVersion + version = nextVersion + revision = nextRevision + sections = projectSections(ctx.slots.entriesOfSlot(SECTION_SLOT), (message) => { + if (reportOnce) console.error(message) + }) + } + return sections + }, + subscribe: (listener) => { + const offLedger = ctx.slots.subscribe(SECTION_SLOT, listener) + const offLocale = ctx.locale.subscribe(listener) + return () => { + offLedger() + offLocale() + } + }, + } +} diff --git a/packages/client/ui-session-panel/src/client/slots.ts b/packages/client/ui-session-panel/src/client/slots.ts new file mode 100644 index 0000000000..67eb471b26 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/slots.ts @@ -0,0 +1,226 @@ +/** Session panel slot declarations and composed component props. */ +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { + InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, +} from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { StateDotState } from '@deepseek-ai/dsh-client-ui-primitives' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-chat/client' +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type { NS } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** + * Sections of the Session panel. `id` addresses the section, `order` sorts + * the sections ascending, and the required `label` is the section title, + * which the panel draws. A section with nothing to show renders nothing, + * and the panel hides its title with it. + */ + 'conversation.session.panel.section': { + kind: 'list' + scope: 'session' + owner: SessionPanelSectionOwnerProps + } + /** Trailing controls of one section title, keyed by the section's `id`. */ + 'conversation.session.panel.section.actions': { kind: 'keyed'; scope: 'session' } + /** + * Marks over the panel toggle, such as an attention dot. Each occupant is + * one element: the toggle sizes it to a 6px dot at the glyph's corner, and + * the occupant sets its `background` and includes text that names it for + * assistive technology, which becomes part of the toggle's name. Occupants + * overlap, and a higher `order` paints above a lower one. An occupant that + * only repeats what the panel shows renders nothing while `panelShown`. + */ + 'conversation.session.panel.indicator': { + kind: 'list' + scope: 'session' + inline: true + owner: SessionPanelIndicatorOwnerProps + } + /** Rows of the built-in Environment section in ascending `order`; they receive the section's owner values. */ + 'conversation.session.panel.environment.row': { kind: 'list'; scope: 'session'; owner: SessionPanelSectionOwnerProps } + } + interface SlotFactoryMap { + /** + * The fold control of a panel list. A list shows at most five rows of a + * group and then this control as its last row, which shows the rest or + * folds them again; a list folds only when that hides two rows or more, + * since the control takes a row itself. The list keeps the fold state and + * decides which rows show. + */ + 'conversation.session.panel.fold': { scope: 'root'; props: PanelFoldProps } + /** + * The details of one panel row, for the content of the row's HoverCard: the + * row's full name, secondary lines such as its owner, its state, and its + * measures. A row whose single line clips or leaves these out shows them + * here. + */ + 'conversation.session.panel.details': { scope: 'root'; props: PanelDetailsProps } + } +} + +/** What a panel row's hover card says about the row. */ +export interface PanelDetailsProps { + /** + * The full name of what the row shows; it wraps instead of clipping. Omit it + * when the name can run long, such as a command, and the row's own view + * shows it in full. + */ + readonly title?: string | undefined + /** Lines in secondary type under the title, such as the owner; each stops after six lines. */ + readonly lines?: readonly string[] | undefined + /** The state, after its dot. */ + readonly status?: { readonly state: StateDotState; readonly label: string } | undefined + /** Measures on one line, at most one of each kind. */ + readonly facts?: readonly PanelDetailsFact[] | undefined +} + +/** One measure in a panel row's hover card. */ +export interface PanelDetailsFact { + /** What the measure counts, which selects its icon: a database for `tokens`, a clock for `duration`. */ + readonly kind: 'tokens' | 'duration' + /** The measure as the card shows it, such as "3.3M tok" or "6m 56s". */ + readonly label: string +} + +/** Props of the fold control that ends a folded panel list. */ +export interface PanelFoldProps { + /** Whether the list shows every row; the control then folds it again. */ + readonly expanded: boolean + /** Visible text for the current state, such as "Show 14 more" or "Show less". */ + readonly label: string + /** Accessible name for the current state; it starts with `label` and names what the list holds. */ + readonly name: string + /** Show every row, or fold the list again. */ + readonly onToggle: () => void +} + +/** How the panel currently shows. */ +export type SessionPanelPresentation = + /** Beside the transcript in the Chat View's end gutter. */ + | 'docked' + /** Over the transcript, opened from the toggle while the gutter is too narrow. */ + | 'overlay' + +/** Values every section receives from the panel. */ +export interface SessionPanelSectionOwnerProps { + /** Current presentation; sections may lower their density in the overlay. */ + readonly presentation: SessionPanelPresentation + /** Close the overlay, for example after a row opened another surface; no effect while docked. */ + readonly dismissOverlay: () => void +} + +/** Values every toggle indicator receives from the toggle. */ +export interface SessionPanelIndicatorOwnerProps { + /** Whether the panel shows, docked or as an overlay. */ + readonly panelShown: boolean +} + +/** One section the panel draws, projected from the section list's registrations. */ +export interface SessionPanelSectionEntry { + /** Registration id. */ + readonly id: string + /** Localized title. */ + readonly label: string +} + +/** Panel visibility shared by the toggle and the panel. */ +export interface SessionPanelVisibility { + /** Whether the panel docks while the gutter has room; persisted across reloads. */ + readonly pinned: boolean + /** Session whose overlay is open, or null. */ + readonly overlay: SessionId | null +} + +/** + * Whether each Session whose Chat View holds a panel has room to dock it: + * true when the end gutter of at least one of its Chat Views holds the docked + * panel. A Session without an entry shows no Chat View. + */ +export type SessionPanelDockable = ReadonlyMap + +/** + * Whether the end gutter of each mounted panel's Chat View holds the docked + * panel, by the id the panel gave its dock probe. + */ +export type SessionPanelProbes = ReadonlyMap + +/** Business face of the header toggle. */ +export interface SessionPanelToggleInjected { + /** Shared visibility and each Session's room to dock; the renderer binds them as `useVisibility` and `useDockable`. */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly dockable: ObservableSnapshot + } + /** + * Show or hide the panel. With room to dock this flips the docking + * preference and closes any overlay; otherwise it opens or closes the + * Session's overlay. No effect while no Chat View shows the Session. + * @param sessionId - Session whose header holds the toggle. + */ + readonly toggle: (sessionId: SessionId) => void +} + +/** Business face of the panel. */ +export interface SessionPanelInjected { + /** + * Shared visibility, the projected section roster, and each dock probe's + * room; the renderer binds them as `useVisibility`, `useSections`, and `useProbes`. + */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly sections: ObservableSnapshot + readonly probes: ObservableSnapshot + } + /** + * Create the ref of one mounted panel's dock probe, the element whose + * stylesheet width says whether the Chat View's end gutter holds the docked + * panel. The plugin observes the element while it is attached and records + * the probe's room under `probe`, and the Session's for the toggle. + * @param sessionId - Session the panel's Chat View shows. + * @param probe - identity of the panel within the page. + * @returns the ref callback for the probe element; detaching withdraws the probe. + */ + readonly createProbeRef: (sessionId: SessionId, probe: string) => (element: HTMLElement | null) => void + /** + * Close the Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays. + */ + readonly closeOverlay: (sessionId: SessionId) => void +} + +/** Business face of the project row. */ +export interface ProjectRowInjected { + /** Host facts from the connection's ready frame; the renderer binds them as `useHost`. */ + readonly hooks: { readonly host: ObservableSnapshot } +} + +/** Full props of the header toggle. */ +export type SessionPanelToggleProps = + PropsRuntime<'conversation.session.header.utilities'> + & PropsRenderSlots<'conversation.session.panel.indicator'> + & InjectFace + & PropsLocale + +/** Full props of the panel. */ +export type SessionPanelProps = + PropsRuntime<'conversation.chat.aside'> + & PropsRenderSlots<'conversation.session.panel.section' | 'conversation.session.panel.section.actions'> + & InjectFace + & PropsLocale + +/** Full props of the built-in Environment section. */ +export type EnvironmentSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderSlots<'conversation.session.panel.environment.row'> + +/** Full props of the project row. */ +export type ProjectRowProps = + PropsRuntime<'conversation.session.panel.environment.row'> + & PropsRenderFactories + & InjectFace + & PropsLocale diff --git a/packages/client/ui-session-panel/src/client/visibility.ts b/packages/client/ui-session-panel/src/client/visibility.ts new file mode 100644 index 0000000000..2e4b036036 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/visibility.ts @@ -0,0 +1,188 @@ +/** Session panel visibility: the persisted docking preference, the transient overlay, the dock probes, and the presentation. */ +import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionPanelDockable, SessionPanelPresentation, SessionPanelProbes, SessionPanelVisibility } from './slots.ts' + +/** localStorage key of the docking preference. */ +export const PINNED_STORAGE_KEY = 'dsh.sessionPanel.pinned' + +const NO_SESSIONS: SessionPanelDockable = new Map() +const NO_PROBES: SessionPanelProbes = new Map() + +/** + * Decide how the panel shows for one Session. + * @param fits - whether the gutter can hold the docked panel. + * @param visibility - shared visibility state. + * @param sessionId - Session whose panel is decided. + * @returns the presentation, or `hidden` when the panel renders nothing. + */ +export function presentationOf( + fits: boolean, visibility: SessionPanelVisibility, sessionId: SessionId, +): SessionPanelPresentation | 'hidden' { + if (fits) return visibility.pinned ? 'docked' : 'hidden' + return visibility.overlay === sessionId ? 'overlay' : 'hidden' +} + +/** + * Visibility shared by every Session's toggle and panel, and whether each + * mounted panel and each Session has room to dock. The panel's stylesheet + * decides the room: each mounted panel renders a dock probe that is 1px wide + * while its Chat View's end gutter holds the docked panel and 0 otherwise, + * and this state observes only that probe, so it hears the decision flip + * and nothing while the window resizes on one side of it or the transcript + * grows. Docking follows one preference for all Sessions; at most one + * Session's overlay is open, and it closes once its Session has room to dock + * or no Chat View shows that Session any longer. + */ +export class SessionPanelState { + // A stored value other than `false` keeps the default: the panel docks. + private readonly pinned = createSnapshotStore(true, { persist: { name: PINNED_STORAGE_KEY } }) + private readonly overlay = createSnapshotStore(null) + private readonly room = createSnapshotStore(NO_SESSIONS) + private readonly fits = createSnapshotStore(NO_PROBES) + /** The Session of every attached probe. */ + private readonly owners = new Map() + /** Stops observing each attached probe. */ + private readonly detachers = new Set<() => void>() + private current: SessionPanelVisibility = { pinned: this.pinned.getSnapshot() !== false, overlay: null } + /** Stops following the open overlay's gutter. */ + private unfollow: () => void = () => {} + + /** Combined visibility; the snapshot keeps its identity until a member changes. */ + readonly visibility: ObservableSnapshot = { + getSnapshot: () => { + const pinned = this.pinned.getSnapshot() !== false + const overlay = this.overlay.getSnapshot() + if (pinned !== this.current.pinned || overlay !== this.current.overlay) this.current = { pinned, overlay } + return this.current + }, + subscribe: (listener) => { + const offPinned = this.pinned.subscribe(listener) + const offOverlay = this.overlay.subscribe(listener) + return () => { + offPinned() + offOverlay() + } + }, + } + + /** + * Whether each Session with a mounted panel has room to dock it: true while + * any of its probes does. The snapshot keeps its identity until a Session + * gains or loses its entry or its room changes. + */ + readonly dockable: ObservableSnapshot = this.room + + /** + * Whether each attached probe's gutter holds the docked panel. The snapshot + * keeps its identity until a probe attaches, detaches, or flips. + */ + readonly probes: ObservableSnapshot = this.fits + + /** + * Create the element-ref lifecycle of one mounted panel's dock probe. + * Attaching the element enters the probe without room and observes its + * size; a probe at least 1px wide has room. Detaching stops the + * observation and withdraws the probe. Without `ResizeObserver` the probe + * stays without room, so the panel shows only as an overlay. + * @param sessionId - Session the panel's Chat View shows. + * @param probe - identity of the panel within the page. + * @returns the ref callback for the probe element. + */ + createProbeRef(sessionId: SessionId, probe: string): (element: HTMLElement | null) => void { + let detach: (() => void) | undefined + return (element) => { + detach?.() + detach = element === null ? undefined : this.attach(sessionId, probe, element) + } + } + + /** + * Show or hide the panel from a Session's toggle. With room to dock this + * flips the docking preference and closes any overlay; otherwise it opens + * or closes the Session's overlay. No effect while no Chat View shows the Session. + * @param sessionId - Session whose header holds the toggle. + */ + toggle(sessionId: SessionId): void { + const dockable = this.room.getSnapshot().get(sessionId) + if (dockable === undefined) return + if (dockable) { + this.pinned.set(!this.visibility.getSnapshot().pinned) + this.setOverlay(null) + return + } + this.setOverlay(this.overlay.getSnapshot() === sessionId ? null : sessionId) + } + + /** + * Close a Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays open. + */ + closeOverlay(sessionId: SessionId): void { + if (this.overlay.getSnapshot() === sessionId) this.setOverlay(null) + } + + /** Stop following the open overlay's Session and stop observing every attached probe. */ + dispose(): void { + this.stopFollowing() + for (const detach of [...this.detachers]) detach() + } + + private stopFollowing(): void { + this.unfollow() + this.unfollow = () => {} + } + + private setOverlay(sessionId: SessionId | null): void { + this.stopFollowing() + this.overlay.set(sessionId) + if (sessionId === null) return + const check = (): void => { + if (this.room.getSnapshot().get(sessionId) !== false) this.closeOverlay(sessionId) + } + this.unfollow = this.room.subscribe(check) + } + + private attach(sessionId: SessionId, probe: string, element: HTMLElement): () => void { + this.report(sessionId, probe, false) + const measure: ResizeObserverCallback = (entries) => { + for (const entry of entries) this.report(sessionId, probe, entry.contentRect.width >= 1) + } + const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure) + observer?.observe(element) + const detach = (): void => { + // The ref callback and dispose may both detach; the first one withdraws the probe. + if (!this.detachers.delete(detach)) return + observer?.disconnect() + this.report(sessionId, probe, null) + } + this.detachers.add(detach) + return detach + } + + /** Record one probe's room, or its withdrawal, publishing only what changed. */ + private report(sessionId: SessionId, probe: string, dockable: boolean | null): void { + const fits = this.fits.getSnapshot() + if (fits.get(probe) !== (dockable ?? undefined)) { + const next = new Map(fits) + if (dockable === null) { + next.delete(probe) + this.owners.delete(probe) + } else { + next.set(probe, dockable) + this.owners.set(probe, sessionId) + } + this.fits.set(next) + } + let any: boolean | undefined + for (const [id, owner] of this.owners) { + if (owner === sessionId) any = any === true || this.fits.getSnapshot().get(id) === true + } + const room = this.room.getSnapshot() + if (room.get(sessionId) === any) return + const next = new Map(room) + if (any === undefined) next.delete(sessionId) + else next.set(sessionId, any) + this.room.set(next) + } +} diff --git a/packages/client/ui-session-panel/src/css-modules.d.ts b/packages/client/ui-session-panel/src/css-modules.d.ts new file mode 100644 index 0000000000..8811db1264 --- /dev/null +++ b/packages/client/ui-session-panel/src/css-modules.d.ts @@ -0,0 +1,4 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} diff --git a/packages/client/ui-session-panel/src/index.ts b/packages/client/ui-session-panel/src/index.ts new file mode 100644 index 0000000000..76ee1f0c6a --- /dev/null +++ b/packages/client/ui-session-panel/src/index.ts @@ -0,0 +1,9 @@ +/** + * Node half of the Session panel plugin. The browser half in `src/client/` + * owns every contribution; this entry exists so the package appears as an + * ordinary Loader row. + * @module @deepseek-ai/dsh-client-ui-session-panel + */ + +/** Loader-visible no-op body; the browser half carries the feature. */ +export function apply(): void {} diff --git a/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts new file mode 100644 index 0000000000..f909fdccca --- /dev/null +++ b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts @@ -0,0 +1,145 @@ +/** + * ui-session-panel plugin halves: the browser entry's dictionaries, fold + * control Factory, header toggle, panel, Environment section, and project row against the real + * SlotRegistry, the inject faces those entries receive, the section roster + * projection, fiber teardown removing every contribution (HMR safety), and + * the inert node entry. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { apply, inject } from '../src/client/index.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from '../src/client/slots.ts' +import { apply as applyNode } from '../src/index.ts' + +const SID = 'session-1' as SessionId + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** Boot the browser half over a real slot tree that declares the header utilities and the Chat aside. */ +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotRegistry).await() + ctx.slots.register({ + name: 'root', + children: { + 'conversation.session.header.utilities': { kind: 'list', scope: 'session' }, + 'conversation.chat.aside': { kind: 'single', scope: 'session' }, + }, + } as never, () => null) + const host = { home: '/Users/me', isLoopback: true } + ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never) + ctx.provide('remote', { $on: () => () => {}, $host: host } as never) + ctx.provide('configForms', { developerTools: { enabled: createSnapshotStore(true) }, get: () => stubConfigForm().scope } as never) + await ctx.plugin({ inject: localeInject, apply: applyLocale }).await() + ctx.locale.setLocale('zh') + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + return { ctx, fiber, host } +} + +/** Inject face of one registration, called for the test Session. */ +function faceOf(ctx: Context, slot: string, id: string | undefined): unknown { + const entry = ctx.slots.entries(slot as never).find(candidate => candidate.options.id === id) + const face = entry?.inject as ((sessionId: SessionId) => unknown) | undefined + if (face === undefined) throw new Error(`${slot} entry ${id ?? '(single)'} registered no inject face`) + return face(SID) +} + +describe('ui-session-panel browser half', () => { + it('declares the services it binds', () => { + expect(inject).toEqual(['slots', 'locale', 'remote']) + }) + + it('registers the fold control and row details Factories, the toggle first among the header utilities, the panel in the Chat aside, the Environment section, and the project row', async () => { + const { ctx } = await bench() + expect(ctx.slots.snapshot('factory:conversation.session.panel.fold')).toHaveLength(1) + expect(ctx.slots.snapshot('factory:conversation.session.panel.details')).toHaveLength(1) + const toggle = ctx.slots.entries('conversation.session.header.utilities').find(entry => entry.options.id === 'session-panel') + expect(toggle?.options.order).toBe(-10) + expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(1) + const section = ctx.slots.entries('conversation.session.panel.section').find(entry => entry.options.id === 'environment') + expect(section?.options.order).toBe(0) + expect(ctx.slots.entries('conversation.session.panel.environment.row').map(entry => entry.options.id)).toEqual(['project']) + }) + + it('hands the toggle the room to dock the panel tracks, and both the shared visibility', async () => { + const { ctx, fiber } = await bench() + const toggle = faceOf(ctx, 'conversation.session.header.utilities', 'session-panel') as SessionPanelToggleInjected + const panel = faceOf(ctx, 'conversation.chat.aside', undefined) as SessionPanelInjected + expect(toggle.hooks.visibility).toBe(panel.hooks.visibility) + const attach = panel.createProbeRef(SID, 'main') + // The node suite has no DOM or ResizeObserver; the probe enters without room and stays unobserved. + attach({} as HTMLElement) + expect(panel.hooks.probes.getSnapshot().get('main')).toBe(false) + expect(toggle.hooks.dockable.getSnapshot().get(SID)).toBe(false) + toggle.toggle(SID) + expect(panel.hooks.visibility.getSnapshot()).toEqual({ pinned: true, overlay: SID }) + panel.closeOverlay(SID) + expect(panel.hooks.visibility.getSnapshot().overlay).toBeNull() + toggle.toggle(SID) + // Disposing the plugin withdraws the probe and stops the open overlay from following the room to dock. + await fiber.dispose() + expect(toggle.hooks.dockable.getSnapshot().has(SID)).toBe(false) + attach(null) + expect(panel.hooks.visibility.getSnapshot().overlay).toBe(SID) + }) + + it('projects the section roster in the active locale and keeps it stable between changes', async () => { + const { ctx } = await bench() + const panel = faceOf(ctx, 'conversation.chat.aside', undefined) as SessionPanelInjected + const roster = panel.hooks.sections + const first = roster.getSnapshot() + expect(first).toEqual([{ id: 'environment', label: '环境' }]) + expect(roster.getSnapshot()).toBe(first) + const listener = vi.fn() + const off = roster.subscribe(listener) + ctx.locale.setLocale('en') + expect(listener).toHaveBeenCalled() + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + const dispose = ctx.slots.register({ name: 'conversation.session.panel.section', id: 'untitled', order: 5 }, () => null) + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + ctx.locale.setLocale('zh') + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + dispose() + off() + }) + + it('gives the project row the Host facts and follows connection resets', async () => { + const { ctx, host } = await bench() + const row = faceOf(ctx, 'conversation.session.panel.environment.row', 'project') as ProjectRowInjected + expect(row.hooks.host.getSnapshot()).toBe(host) + const listener = vi.fn() + const off = row.hooks.host.subscribe(listener) + ctx.emit('connection/reset' as never) + expect(listener).toHaveBeenCalledTimes(1) + off() + }) + + it('removes every contribution with the fiber (HMR safety)', async () => { + const { ctx, fiber } = await bench() + await fiber.dispose() + expect(ctx.slots.snapshot('factory:conversation.session.panel.fold')).toHaveLength(0) + expect(ctx.slots.snapshot('factory:conversation.session.panel.details')).toHaveLength(0) + expect(ctx.slots.entries('conversation.session.header.utilities')).toHaveLength(0) + expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(0) + expect(ctx.slots.entries('conversation.session.panel.section')).toHaveLength(0) + }) +}) + +describe('ui-session-panel node half', () => { + it('contributes no host behavior', () => { + expect(applyNode).not.toThrow() + }) +}) diff --git a/packages/client/ui-session-panel/tests/components.client.spec.tsx b/packages/client/ui-session-panel/tests/components.client.spec.tsx new file mode 100644 index 0000000000..81cf2211d5 --- /dev/null +++ b/packages/client/ui-session-panel/tests/components.client.spec.tsx @@ -0,0 +1,548 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { useRef, type ReactNode } from 'react' +import { useModalLayer } from '@deepseek-ai/dsh-client-ui-primitives' +import { bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { EnvironmentSection } from '../src/client/EnvironmentSection.tsx' +import { PanelDetails } from '../src/client/PanelDetails.tsx' +import { PanelFold } from '../src/client/PanelFold.tsx' +import { ProjectRow } from '../src/client/ProjectRow.tsx' +import { SessionPanel } from '../src/client/SessionPanel.tsx' +import { SessionPanelToggle } from '../src/client/SessionPanelToggle.tsx' +import type { + EnvironmentSectionProps, PanelDetailsProps, ProjectRowProps, SessionPanelDockable, SessionPanelProbes, SessionPanelProps, + SessionPanelSectionEntry, SessionPanelSectionOwnerProps, SessionPanelToggleProps, SessionPanelVisibility, +} from '../src/client/slots.ts' +import { SessionPanelState } from '../src/client/visibility.ts' +import { en, zh } from '../src/client/locales.ts' + +const SID = 'session-1' as SessionId +const t = makeTranslate(zh) as SessionPanelToggleProps['t'] +const DOCKED: SessionPanelVisibility = { pinned: true, overlay: null } + +function selectorOf(value: T) { + return (select: (current: T) => S): S => select(value) +} + +beforeEach(() => { + vi.stubGlobal('ResizeObserver', class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} + }) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true, addEventListener() {}, removeEventListener() {} }))) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +/** Whether a hovered anchor's tooltip shows before and at 500ms of hover. */ +function tooltipAfterHover(anchor: Element): { readonly early: boolean; readonly at500: boolean } { + vi.useFakeTimers() + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(499) }) + const early = screen.queryByRole('tooltip', { hidden: true }) !== null + act(() => { vi.advanceTimersByTime(1) }) + return { early, at500: screen.queryByRole('tooltip', { hidden: true }) !== null } +} + +describe('SessionPanelToggle', () => { + function toggleProps(dockable: boolean | undefined, visibility: SessionPanelVisibility, toggle = vi.fn()) { + const renderSlot = vi.fn(() => 需要处理) + const entries: SessionPanelDockable = new Map(dockable === undefined ? [] : [[SID, dockable]]) + const props = { + sessionId: SID, useDockable: selectorOf(entries), useVisibility: selectorOf(visibility), toggle, renderSlot, t, + } as SessionPanelToggleProps + return { props, toggle, renderSlot } + } + + it('names the panel together with its indicators and reports the docked panel as expanded', () => { + const { props, renderSlot } = toggleProps(true, DOCKED) + render() + const button = screen.getByRole('button', { name: '会话面板 需要处理' }) + expect(button.getAttribute('aria-expanded')).toBe('true') + expect(button.getAttribute('aria-controls')).toBe(`dsh-session-panel-${SID}`) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', { panelShown: true }) + }) + + it('flips docking with room to dock and opens the overlay without it', () => { + const wide = toggleProps(true, DOCKED) + render() + fireEvent.click(screen.getByRole('button')) + expect(wide.toggle).toHaveBeenCalledWith(SID) + cleanup() + const narrow = toggleProps(false, DOCKED) + render() + const button = screen.getByRole('button') + expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.hasAttribute('aria-controls')).toBe(false) + fireEvent.click(button) + expect(narrow.toggle).toHaveBeenCalledWith(SID) + }) + + it('reports an open overlay as expanded', () => { + const { props } = toggleProps(false, { pinned: false, overlay: SID }) + render() + expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('true') + }) + + it('tells its indicators whether the panel shows', () => { + const { props, renderSlot } = toggleProps(false, DOCKED) + render() + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', { panelShown: false }) + }) + + it('shows its tooltip after 500ms of hover', () => { + const { props } = toggleProps(true, DOCKED) + render() + expect(tooltipAfterHover(screen.getByRole('button'))).toEqual({ early: false, at500: true }) + }) + + it('is unavailable and says why while no Chat View shows the Session', () => { + const { props } = toggleProps(undefined, { pinned: true, overlay: SID }) + render() + const button = screen.getByRole('button') + expect(button.getAttribute('aria-disabled')).toBe('true') + expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.hasAttribute('aria-controls')).toBe(false) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(button) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('切换到「对话」视图后可显示会话面板') + }) +}) + +describe('SessionPanel', () => { + const SECTIONS: readonly SessionPanelSectionEntry[] = [ + { id: 'environment', label: '环境' }, + { id: 'change-requests', label: '变更请求' }, + ] + + /** Ids of the probes the rendered panels created, so a later props object answers for the mounted panel. */ + const probeIds = new Set() + afterEach(() => { probeIds.clear() }) + + /** Panel props whose dock probes all have, or all lack, room to dock. */ + function panelProps(dockable: boolean, visibility: SessionPanelVisibility, closeOverlay = vi.fn()) { + const owners: SessionPanelSectionOwnerProps[] = [] + const renderSlot = ((key: string, owner: object, opts?: { only?: string; entryKey?: string }): ReactNode => { + if (key === 'conversation.session.panel.section.actions') { + return opts?.entryKey === 'change-requests' ? : null + } + owners.push(owner as SessionPanelSectionOwnerProps) + return

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

    + }) as SessionPanelProps['renderSlot'] + const attached = vi.fn<(element: HTMLElement | null) => void>() + const createProbeRef = vi.fn((_sessionId: SessionId, probe: string) => { + probeIds.add(probe) + return attached + }) + const props = { + sessionId: SID, + useVisibility: selectorOf(visibility), + useSections: selectorOf(SECTIONS), + useProbes: (select: (probes: SessionPanelProbes) => S): S => select(new Map([...probeIds].map(id => [id, dockable]))), + createProbeRef, + closeOverlay, + renderSlot, + t, + } as SessionPanelProps + return { props, owners, closeOverlay, createProbeRef, attached } + } + + it('attaches its dock probe through the injected ref once and detaches it on unmount', () => { + const { props, createProbeRef, attached } = panelProps(true, DOCKED) + const view = render() + const probe = view.container.querySelector('[data-session-panel-probe]') + expect(probe).not.toBeNull() + expect(createProbeRef.mock.calls).toEqual([[SID, expect.any(String)]]) + expect(attached.mock.calls).toEqual([[probe]]) + // A later render keeps the ref, so the probe is neither detached nor attached again. + const next = panelProps(true, DOCKED) + view.rerender() + expect(next.createProbeRef).not.toHaveBeenCalled() + expect(attached).toHaveBeenCalledTimes(1) + view.unmount() + expect(attached.mock.calls.at(-1)).toEqual([null]) + }) + + it('renders again only when its dock probe flips', () => { + const observed: { readonly element: Element; readonly callback: ResizeObserverCallback }[] = [] + vi.stubGlobal('ResizeObserver', class { + private readonly callback: ResizeObserverCallback + constructor(callback: ResizeObserverCallback) { this.callback = callback } + observe(element: Element): void { observed.push({ element, callback: this.callback }) } + unobserve(): void {} + disconnect(): void {} + }) + const state = new SessionPanelState() + const base = panelProps(false, DOCKED) + const props = { + ...base.props, + useProbes: bindSnapshotSelector(state.probes), + createProbeRef: (sessionId: SessionId, probe: string) => state.createProbeRef(sessionId, probe), + } as SessionPanelProps + const view = render() + const resize = (width: number): void => { + act(() => { + for (const { element, callback } of observed) { + callback([{ target: element, contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver) + } + }) + } + expect(observed.map(entry => entry.element)).toEqual([view.container.querySelector('[data-session-panel-probe]')]) + expect(screen.queryByRole('complementary')).toBeNull() + expect(state.dockable.getSnapshot().get(SID)).toBe(false) + resize(1) + expect(screen.getByRole('complementary').getAttribute('data-session-panel')).toBe('docked') + // CSS sizes the docked panel; no measured width reaches its style. + expect(screen.getByRole('complementary').getAttribute('style')).toBeNull() + const settled = base.owners.length + resize(1) + expect(base.owners).toHaveLength(settled) + // A probe under 1px wide sits within a pixel below the gutter that docks the panel. + resize(0.5) + expect(screen.queryByRole('complementary')).toBeNull() + expect(state.dockable.getSnapshot().get(SID)).toBe(false) + view.unmount() + expect(state.dockable.getSnapshot().has(SID)).toBe(false) + }) + + it('renders only its dock probe while hidden', () => { + const { props } = panelProps(true, { pinned: false, overlay: null }) + const view = render() + expect(view.container.querySelector('[data-session-panel]')).toBeNull() + expect(view.container.children).toHaveLength(1) + expect(view.container.firstElementChild?.hasAttribute('data-session-panel-probe')).toBe(true) + }) + + it('docks with one titled region per section in roster order and each section body', () => { + const { props, owners } = panelProps(true, DOCKED) + render() + const panel = screen.getByRole('complementary', { name: '会话面板' }) + expect(panel.getAttribute('data-session-panel')).toBe('docked') + expect(panel.id).toBe(`dsh-session-panel-${SID}`) + const regions = screen.getAllByRole('region') + expect(regions.map(region => region.getAttribute('aria-labelledby'))).toEqual([ + `dsh-session-panel-${SID}-environment`, `dsh-session-panel-${SID}-change-requests`, + ]) + expect(screen.getByRole('heading', { name: '变更请求' })).toBeTruthy() + expect(screen.getByText('environment body')).toBeTruthy() + expect(screen.getByRole('button', { name: '刷新' })).toBeTruthy() + expect(owners.every(owner => owner.presentation === 'docked')).toBe(true) + }) + + it('closes the overlay on Escape from inside and returns focus to the toggle', () => { + const { props, owners, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + document.body.append(toggle) + try { + render() + const panel = screen.getByRole('complementary') + expect(panel.getAttribute('data-session-panel')).toBe('overlay') + fireEvent.keyDown(document, { key: 'Enter' }) + expect(closeOverlay).not.toHaveBeenCalled() + screen.getByRole('button', { name: '刷新' }).focus() + fireEvent.keyDown(document.activeElement as Element, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(toggle) + owners[0]?.dismissOverlay() + expect(closeOverlay).toHaveBeenCalledTimes(2) + } finally { + toggle.remove() + } + }) + + it('closes the overlay on Escape from the page without moving focus', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + render() + const outside = document.createElement('input') + document.body.append(outside) + try { + outside.focus() + fireEvent.keyDown(outside, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(outside) + } finally { + outside.remove() + } + }) + + it('closes the overlay on an outside pointerdown but not on the panel, the toggle, or an open menu', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + const menu = document.createElement('div') + menu.setAttribute('role', 'menu') + const item = document.createElement('button') + menu.append(item) + document.body.append(toggle, menu) + try { + render() + fireEvent.pointerDown(screen.getByText('environment body')) + fireEvent.pointerDown(toggle) + fireEvent.pointerDown(item) + expect(closeOverlay).not.toHaveBeenCalled() + fireEvent.pointerDown(document.body) + expect(closeOverlay).toHaveBeenCalledWith(SID) + } finally { + toggle.remove() + menu.remove() + } + }) + + it('leaves Escape to other handlers while docked, after another handler took it, or behind a modal', () => { + const docked = panelProps(true, DOCKED) + render() + fireEvent.keyDown(document, { key: 'Escape' }) + fireEvent.pointerDown(document.body) + expect(docked.closeOverlay).not.toHaveBeenCalled() + cleanup() + const overlay = panelProps(false, { pinned: true, overlay: SID }) + render() + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) + event.preventDefault() + document.dispatchEvent(event) + expect(overlay.closeOverlay).not.toHaveBeenCalled() + // A modal opened over the overlay registers its Escape after the panel's, so the panel sees it first. + function Modal() { + const dialog = useRef(null) + useModalLayer(dialog, true, () => {}) + return
    + } + const modal = render() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(overlay.closeOverlay).not.toHaveBeenCalled() + modal.unmount() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(overlay.closeOverlay).toHaveBeenCalledWith(SID) + }) + + it('leaves Escape to an input method composing text, including the key that ends the composition', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + render() + fireEvent(document, new Event('compositionstart')) + fireEvent.keyDown(document, { key: 'Escape', isComposing: true }) + fireEvent(document, new Event('compositionend')) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(closeOverlay).not.toHaveBeenCalled() + fireEvent.keyUp(document, { key: 'Escape' }) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + }) + + it('hands focus to the toggle when the panel hides with the keyboard inside it', () => { + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + const outside = document.createElement('button') + document.body.append(toggle, outside) + try { + const docked = panelProps(true, DOCKED) + const view = render() + const control = screen.getByRole('button', { name: '刷新' }) + control.focus() + // Moves within the panel, and blurs that name no next target, keep the keyboard inside. + fireEvent.focusOut(control, { relatedTarget: screen.getByRole('complementary') }) + fireEvent.focusOut(control, { relatedTarget: null }) + view.rerender() + expect(document.activeElement).toBe(toggle) + // Focus that already left the panel stays where it went. + view.rerender() + screen.getByRole('button', { name: '刷新' }).focus() + outside.focus() + view.rerender() + expect(document.activeElement).toBe(outside) + // A panel that hides without having held focus moves nothing. + view.rerender() + view.rerender() + expect(document.activeElement).toBe(outside) + } finally { + toggle.remove() + outside.remove() + } + }) +}) + +describe('EnvironmentSection', () => { + it('renders its rows straight into the section body with the section owner values', () => { + const renderSlot = vi.fn(() => row) + const dismissOverlay = vi.fn<() => void>() + render(<>{EnvironmentSection({ presentation: 'overlay', dismissOverlay, renderSlot } as Pick as EnvironmentSectionProps)}) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.environment.row', { presentation: 'overlay', dismissOverlay }) + expect(screen.getByText('row')).toBeTruthy() + }) +}) + +describe('ProjectRow', () => { + function rowProps(over: { + workingDirectory?: string | null + workspacePath?: string + cwd?: string + home?: string + }, open = vi.fn()) { + const renderFactorySlot = vi.fn((_name: string, input: { label: string }) => ) + const props = { + sessionId: SID, + useProjection: (key: string) => key === 'workingDirectory' ? over.workingDirectory : undefined, + useWorkspaces: selectorOf({ + items: over.workspacePath === undefined ? [] : [{ path: over.workspacePath, sessionIds: [SID] }], + }), + useSessions: selectorOf({ byId: over.cwd === undefined ? {} : { [SID]: { cwd: over.cwd } } }), + useHost: selectorOf({ home: over.home, isLoopback: true }), + useContextMenu: contextMenuHook(open), + renderFactorySlot, + t, + } as ProjectRowProps + return { props, renderFactorySlot, open } + } + + function folderOf(container: HTMLElement): { name: string | null; parent: string | null } { + const folder = container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement + const [name, parent] = [...folder.children] + return { name: name?.textContent ?? null, parent: parent?.textContent ?? null } + } + + it('shows the working directory as its name and parent folder, with the label and full path in the tooltip', () => { + const { props, renderFactorySlot } = rowProps({ + workingDirectory: '/Users/me/projects/app/.worktrees/fix', + cwd: '/Users/me/projects/app', + workspacePath: '/Users/me/projects/app', + home: '/Users/me', + }) + const view = render() + expect(folderOf(view.container)).toEqual({ name: 'fix', parent: '~/projects/app/.worktrees' }) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('工作目录\n~/projects/app/.worktrees/fix') + fireEvent.blur(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement) + expect(tooltipAfterHover(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement)) + .toEqual({ early: false, at500: true }) + expect(renderFactorySlot).toHaveBeenCalledWith('contextMenu.button', expect.objectContaining({ + target: { kind: 'directory', value: { sessionId: SID, path: '/Users/me/projects/app/.worktrees/fix' } }, + label: '工作目录操作', + })) + expect(renderFactorySlot.mock.calls[0]?.[1]).not.toHaveProperty('size') + expect(screen.getByRole('button', { name: '工作目录操作' })).toBeTruthy() + }) + + it('marks its parts for the panel\'s row rules: icon and folder in the body, then the More button as the row menu', () => { + const view = render() + const row = view.container.querySelector('[data-session-panel-row]') as HTMLElement + expect(row.hasAttribute('data-session-panel-project')).toBe(true) + expect([...row.children].map(part => part.getAttribute('data-row-part'))).toEqual(['body', 'menu']) + const [body, menu] = [...row.children] as [HTMLElement, HTMLElement] + expect(body.tagName).toBe('SPAN') + expect([...body.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content']) + expect(body.children[0]?.getAttribute('aria-hidden')).toBe('true') + expect(body.children[1]?.textContent).toBe('app/srv') + expect(menu.querySelector('button')?.textContent).toBe('工作目录操作') + }) + + it('falls back to the directory the Session was created in and opens the directory menu on right-click', () => { + const { props, open } = rowProps({ cwd: '/srv/app', workspacePath: '/srv' }) + const view = render() + expect(folderOf(view.container)).toEqual({ name: 'app', parent: '/srv' }) + fireEvent.contextMenu(view.container.querySelector('[data-session-panel-project]') as HTMLElement) + expect(open).toHaveBeenCalledWith({ kind: 'directory', value: { sessionId: SID, path: '/srv/app' } }, expect.anything()) + }) + + it('falls back to the listing Workspace when no directory is recorded, keeping a root parent and omitting an absent one', () => { + const atRoot = render() + expect(folderOf(atRoot.container)).toEqual({ name: 'srv', parent: '/' }) + atRoot.unmount() + const atHome = render() + expect(folderOf(atHome.container)).toEqual({ name: '~', parent: null }) + }) + + it('renders nothing before the Session directory is known', () => { + const { props } = rowProps({}) + const view = render() + expect(view.container.innerHTML).toBe('') + }) +}) + +describe('PanelFold', () => { + type FoldProps = FactoryComponentPropsOf<'conversation.session.panel.fold'> + + /** Render the control with the props a list passes; the renderer's standard seats are left out, as the control reads none. */ + function fold(expanded: boolean) { + const onToggle = vi.fn<() => void>() + const props = { + expanded, onToggle, + label: expanded ? 'Show less' : 'Show 14 more', + name: expanded ? 'Show less (subagents)' : 'Show 14 more (subagents)', + } as Pick as FoldProps + const view = render() + return { onToggle, row: view.container.firstElementChild as HTMLElement } + } + + it('is a panel row whose body is the button, with a down chevron in the icon part while rows are held back', () => { + const { row, onToggle } = fold(false) + expect(row.getAttribute('data-session-panel-row')).toBe('fold') + expect([...row.children].map(part => `${part.tagName}:${part.getAttribute('data-row-part') ?? ''}`)).toEqual(['BUTTON:body']) + const button = screen.getByRole('button', { name: 'Show 14 more (subagents)' }) + expect(button.getAttribute('aria-expanded')).toBe('false') + expect([...button.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content']) + expect(button.children[0]?.getAttribute('aria-hidden')).toBe('true') + expect(button.querySelector('svg')?.getAttribute('data-icon')).toBe('dsw-icon-chevron-down-outline-regular') + expect(button.children[1]?.textContent).toBe('Show 14 more') + fireEvent.click(button) + expect(onToggle).toHaveBeenCalledOnce() + }) + + it('points the chevron up and reports expanded once the list shows every row', () => { + const { row } = fold(true) + const button = screen.getByRole('button', { name: 'Show less (subagents)' }) + expect(button.getAttribute('aria-expanded')).toBe('true') + expect(row.querySelector('svg')?.getAttribute('data-icon')).toBe('dsw-icon-chevron-up-outline-regular') + expect(row.querySelector('[data-row-part="content"]')?.textContent).toBe('Show less') + }) +}) + +describe('PanelDetails', () => { + /** Render the details with the props a row passes; the renderer's standard seats are left out, as the details read none. */ + function details(input: PanelDetailsProps): HTMLElement { + const view = render(} />) + return view.container.querySelector('[data-session-panel-details]') as HTMLElement + } + + it('stacks the title, lines, state, and measures in order, each measure after the icon of its kind', () => { + const root = details({ + title: 'Survey open-source harnesses', + lines: ['Owner: open-source-arch'], + status: { state: 'done', label: 'Completed' }, + facts: [{ kind: 'tokens', label: '3.3M tok' }, { kind: 'duration', label: '6m 56s' }], + }) + expect([...root.children].map(child => child.textContent)) + .toEqual(['Survey open-source harnesses', 'Owner: open-source-arch', 'Completed', '3.3M tok6m 56s']) + expect(root.children[2]?.querySelector('[data-state="done"]')).not.toBeNull() + const facts = [...(root.children[3] as HTMLElement).children] + expect(facts.map(fact => [fact.getAttribute('data-fact'), fact.querySelector('svg')?.getAttribute('data-icon')])).toEqual([ + ['tokens', 'dsw-icon-database-outline-regular'], + ['duration', 'dsw-icon-clock-outline-regular'], + ]) + expect(facts.every(fact => fact.firstElementChild?.getAttribute('aria-hidden') === 'true')).toBe(true) + }) + + it('renders only the title when nothing else is given', () => { + expect(details({ title: 'sleep 30' }).children).toHaveLength(1) + }) + + it('starts with the lines when the title is omitted', () => { + const root = details({ lines: ['bash'], status: { state: 'ongoing', label: 'running' } }) + expect([...root.children].map(child => child.textContent)).toEqual(['bash', 'running']) + }) +}) + +describe('dictionaries', () => { + it('keeps the English dictionary key-identical to the Chinese source of truth', () => { + expect(Object.keys(en).sort()).toEqual(Object.keys(zh).sort()) + }) +}) diff --git a/packages/client/ui-session-panel/tests/sections.client.spec.ts b/packages/client/ui-session-panel/tests/sections.client.spec.ts new file mode 100644 index 0000000000..5500f97256 --- /dev/null +++ b/packages/client/ui-session-panel/tests/sections.client.spec.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest' +import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import { projectSections } from '../src/client/sections.ts' + +function entry(id: string, order: number | undefined, label: StoredEntry['options']['label'], registrant?: string): StoredEntry { + return { + component: () => null, + options: { id, ...order === undefined ? {} : { order }, ...label === undefined ? {} : { label } }, + ...registrant === undefined ? {} : { registrant }, + } +} + +describe('projectSections', () => { + it('orders sections by ascending order, keeping registration order for ties, and resolves locale thunks', () => { + const report = vi.fn() + const sections = projectSections([ + entry('later', 100, 'Change requests'), + entry('first', 0, () => 'Environment'), + entry('tie', 100, 'Outputs'), + entry('default', undefined, 'Default order'), + ], report) + expect(sections).toEqual([ + { id: 'first', label: 'Environment' }, + { id: 'default', label: 'Default order' }, + { id: 'later', label: 'Change requests' }, + { id: 'tie', label: 'Outputs' }, + ]) + expect(report).not.toHaveBeenCalled() + }) + + it('reports and leaves out a section that cannot be titled', () => { + const report = vi.fn() + const sections = projectSections([ + entry('untitled', 0, undefined, 'acme-plugin'), + entry('blank', 1, ''), + entry('titled', 2, 'Titled'), + ], report) + expect(sections).toEqual([{ id: 'titled', label: 'Titled' }]) + expect(report).toHaveBeenCalledTimes(2) + expect(report.mock.calls[0]?.[0]).toContain('"untitled" from acme-plugin') + expect(report.mock.calls[1]?.[0]).toContain('"blank" from an unknown registrant') + }) +}) diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts new file mode 100644 index 0000000000..fb87b56c88 --- /dev/null +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -0,0 +1,155 @@ +/** + * The Session panel's stylesheet as CSS text. jsdom has no layout, so the + * component suite cannot show that the dock probe is 1px wide exactly from + * the gutter that holds the docked panel, or that marked rows get one + * geometry; this reads the declarations and evaluates the docking ones for + * gutters around that boundary. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/client/SessionPanel.module.css', import.meta.url)), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, ' ') + +/** Declarations of the rule with exactly this selector list, with whitespace collapsed. */ +function declarationsOf(selector: string): Record { + const pattern = selector.split(',').map(part => part.trim().replace(/[.[\]():*+^$\\'=]/g, '\\$&')).join('\\s*,\\s*') + const rule = new RegExp(`(?:^|[{}])\\s*${pattern}\\s*\\{([^{}]*)\\}`).exec(css) + if (rule === null) throw new Error(`SessionPanel.module.css has no \`${selector}\` rule`) + const entries = (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean).map((part): [string, string] => { + const colon = part.indexOf(':') + return [part.slice(0, colon).trim(), part.slice(colon + 1).replace(/\s+/g, ' ').replace(/\( /g, '(').replace(/ \)/g, ')').trim()] + }) + return Object.fromEntries(entries) +} + +const px = (value: string | undefined): number => { + const match = /^(-?\d+(?:\.\d+)?)px$/.exec(value ?? '') + if (match === null) throw new Error(`not a px length: ${String(value)}`) + return Number(match[1]) +} + +describe('SessionPanel.module.css docking geometry', () => { + const metrics = declarationsOf('.panel, .dockProbe') + const clear = px(metrics['--panel-clear']) + const edge = px(metrics['--panel-edge']) + const minWidth = px(metrics['--panel-min-width']) + + it('derives the docked width and the dock probe from one set of metrics', () => { + expect([clear, edge, minWidth]).toEqual([40, 8, 300]) + const panel = declarationsOf('.panel') + expect(panel['right']).toBe('var(--panel-edge)') + expect(panel['width']).toBe( + 'clamp(var(--panel-min-width), calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge)), 360px)', + ) + const probe = declarationsOf('.dockProbe') + expect(probe['width']).toBe( + 'calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px)', + ) + expect(probe['max-width']).toBe('1px') + }) + + it('makes the probe 1px wide exactly from the gutter that holds the panel at its minimum width', () => { + // The declarations above, evaluated: a width below 0 is used as 0, and max-width caps the probe at 1px. + const probeWidth = (gutter: number): number => Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1)) + const dockedWidth = (gutter: number): number => Math.min(360, Math.max(minWidth, gutter - clear - edge)) + expect([probeWidth(0), probeWidth(347), probeWidth(347.5), probeWidth(348), probeWidth(900)]).toEqual([0, 0, 0.5, 1, 1]) + // At the first gutter that docks, the panel is at its minimum width and keeps both clearances. + expect(dockedWidth(348)).toBe(minWidth) + expect(348 - dockedWidth(348) - edge).toBe(clear) + expect([dockedWidth(377), dockedWidth(500)]).toEqual([329, 360]) + }) + + it('keeps the probe out of sight, out of the layout flow, and away from the pointer', () => { + expect(declarationsOf('.dockProbe')).toMatchObject({ + 'position': 'absolute', 'height': '0', 'visibility': 'hidden', 'pointer-events': 'none', + }) + }) + + it('floats the overlay narrower than the docked panel, at the same edge inset', () => { + expect(declarationsOf(".panel[data-session-panel='overlay']")['width']).toBe('min(280px, calc(100% - 2 * var(--panel-edge)))') + }) +}) + +describe('SessionPanel.module.css row rules', () => { + /** A rule for marked row markup: `.panel :where()`. */ + const row = (inner: string, tail = ''): Record => declarationsOf(`.panel :where(${inner})${tail}`) + + it('lays a marked row out as one 28px line with the icon and the menu on fixed columns', () => { + expect(row('[data-session-panel-row]')).toMatchObject({ + 'display': 'flex', 'align-items': 'center', 'gap': '8px', 'min-height': '28px', 'padding': '0 6px', + }) + expect(row("[data-session-panel-row] > [data-row-part='body']")).toMatchObject({ flex: '1 1 auto', height: '28px', gap: '8px' }) + // 6px of padding and half of the 16px box put the icon's center 14px from the row's start, and the menu's from its end. + expect(row("[data-session-panel-row] [data-row-part='icon']")).toMatchObject({ width: '16px', height: '16px', flex: 'none' }) + expect(row("[data-session-panel-row] > [data-row-part='menu']")).toMatchObject({ 'width': '16px', 'justify-content': 'center' }) + expect(row("[data-session-panel-row] [data-row-part='content']")).toMatchObject({ + 'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', + }) + }) + + it('grows a row with a detail line and keeps the icon level with the first line', () => { + const tall = "[data-session-panel-row] > [data-row-part='body']:has([data-row-part='detail'])" + expect(row(tall)).toEqual({ 'align-items': 'flex-start', 'height': 'auto', 'padding': '4px 0' }) + expect(row(`${tall} > [data-row-part='icon']`)).toEqual({ height: '20px' }) + expect(row("[data-session-panel-row] [data-row-part='lines']")).toMatchObject({ 'display': 'flex', 'flex-direction': 'column', 'min-width': '0' }) + expect(row("[data-session-panel-row] [data-row-part='detail']")).toMatchObject({ + 'color': 'var(--dsw-alias-label-tertiary)', 'font-size': '12px', 'line-height': '17px', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', + }) + // The two-line rules follow the one-line ones they adjust, since every rule for a part has the same specificity. + const order = (selector: string): number => { + const at = css.indexOf(`.panel :where(${selector}) {`) + expect(at).toBeGreaterThan(-1) + return at + } + expect(order(tall)).toBeGreaterThan(order("[data-session-panel-row] > button[data-row-part='body']")) + expect(order(`${tall} > [data-row-part='icon']`)).toBeGreaterThan(order("[data-session-panel-row] [data-row-part='icon']")) + }) + + it('makes a button body the action of the whole row and rings the row when it has keyboard focus', () => { + expect(row("[data-session-panel-row] > button[data-row-part='body']", '::after')).toMatchObject({ position: 'absolute', inset: '0' }) + expect(row("[data-session-panel-row] > [data-row-part='trailing'], [data-session-panel-row] > [data-row-part='menu']")) + .toMatchObject({ 'position': 'relative', 'z-index': '1' }) + expect(row("[data-session-panel-row]:has(> button[data-row-part='body']:focus-visible)")['outline-offset']).toBe('-2px') + }) + + it('gives a plain button in the menu a 24px target and a tertiary glyph without a fill', () => { + expect(row("[data-session-panel-row] > [data-row-part='menu']", ' button')).toMatchObject({ + width: '24px', height: '24px', margin: '-4px', background: 'transparent', color: 'var(--dsw-alias-label-tertiary)', + }) + }) + + it('highlights only a row with an action or a menu that renders something, and keeps an open menu and its row shown', () => { + const interactive = "[data-session-panel-row]:has(> button[data-row-part='body'], > [data-row-part='menu']:not(:empty))" + expect(row("[data-session-panel-row] > [data-row-part='menu']:empty")).toEqual({ display: 'none' }) + // Only an open control in the menu part keeps the row highlighted; an expanded body button does not. + expect(row("[data-session-panel-row]:has(> [data-row-part='menu'] [aria-expanded='true'])")) + .toEqual({ background: 'var(--dsw-alias-interactive-bg-hover)' }) + expect(css).not.toMatch(/:has\(\[aria-expanded='true'\]\)\)\s*\{\s*background/) + expect(row("[data-session-panel-row] > [data-row-part='menu']:has([aria-expanded='true'])")['opacity']).toBe('1') + // Hover rules stay inside the hover media query, where the menu hides until the row is hovered or focused. + const hover = /@media \(hover: hover\) \{([\s\S]*?)\n\}/.exec(css)?.[1] ?? '' + expect(hover).toContain(`.panel :where(${interactive}:hover)`) + expect(hover).toMatch(/\[data-row-part='menu'\]\) \{\s*opacity: 0;/) + expect(css.replace(/@media \(hover: hover\) \{[\s\S]*?\n\}/g, '')).not.toContain(':hover') + }) + + it('sets a fold control in the quiet type of the section counts with a 14px chevron, darker on hover and keyboard focus', () => { + const fold = "[data-session-panel-row='fold']" + expect(row(fold)).toEqual({ + 'color': 'var(--dsw-alias-label-tertiary)', 'font': 'var(--dsw-font-xxs-12)', 'font-variant-numeric': 'tabular-nums', + }) + expect(row(`${fold} [data-row-part='icon']`, ' svg')).toEqual({ width: '14px', height: '14px' }) + expect(row(`${fold}:has(> button:focus-visible)`)).toEqual({ color: 'var(--dsw-alias-label-secondary)' }) + expect(row(`${fold}:hover`)).toEqual({ color: 'var(--dsw-alias-label-secondary)' }) + // The fold rules follow the row rules they adjust, since every rule for a part has the same specificity. + const at = (selector: string, tail = ''): number => { + const index = css.indexOf(`.panel :where(${selector})${tail} {`) + expect(index).toBeGreaterThan(-1) + return index + } + expect(at(fold)).toBeGreaterThan(at('[data-session-panel-row]')) + expect(at(`${fold} [data-row-part='icon']`, ' svg')).toBeGreaterThan(at("[data-session-panel-row] [data-row-part='icon']", ' svg')) + }) +}) diff --git a/packages/client/ui-session-panel/tests/visibility.client.spec.ts b/packages/client/ui-session-panel/tests/visibility.client.spec.ts new file mode 100644 index 0000000000..29ee583e7a --- /dev/null +++ b/packages/client/ui-session-panel/tests/visibility.client.spec.ts @@ -0,0 +1,263 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { PINNED_STORAGE_KEY, SessionPanelState, presentationOf } from '../src/client/visibility.ts' + +const A = 'session-a' as SessionId +const B = 'session-b' as SessionId + +/** What the stubbed ResizeObserver holds for each observed probe element. */ +interface Observation { + /** Deliver one size report for the element. */ + readonly report: (width: number) => void + /** Whether the observer was disconnected. */ + disconnected: boolean +} + +const observations = new Map() +let nextProbe = 0 + +beforeEach(() => { + localStorage.clear() + observations.clear() + vi.stubGlobal('ResizeObserver', class { + private readonly callback: ResizeObserverCallback + private readonly targets: Observation[] = [] + constructor(callback: ResizeObserverCallback) { this.callback = callback } + observe(element: Element): void { + const observation: Observation = { + report: (width) => { this.callback([{ target: element, contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver) }, + disconnected: false, + } + this.targets.push(observation) + observations.set(element, observation) + } + + unobserve(): void {} + disconnect(): void { for (const observation of this.targets) observation.disconnected = true } + }) +}) + +afterEach(() => { + localStorage.clear() + vi.unstubAllGlobals() +}) + +/** + * One mounted panel's dock probe: its id, a size report for its element, and + * its detachment, as the panel's ref drives them. + */ +function probeOf(state: SessionPanelState, sessionId: SessionId, width = 0) { + nextProbe += 1 + const id = `probe-${nextProbe}` + const element = document.createElement('span') + const ref = state.createProbeRef(sessionId, id) + ref(element) + const observation = observations.get(element) + if (observation === undefined) throw new Error('the probe element is not observed') + if (width > 0) observation.report(width) + return { id, element, observation, resize: observation.report, detach: () => { ref(null) } } +} + +/** A state whose Chat Views show `A` and `B` without room to dock. */ +function newState() { + const state = new SessionPanelState() + return { state, a: probeOf(state, A), b: probeOf(state, B) } +} + +describe('presentationOf', () => { + it.each([ + [true, true, null, 'docked'], + [true, true, A, 'docked'], + [true, false, null, 'hidden'], + [true, false, A, 'hidden'], + [false, true, null, 'hidden'], + [false, false, null, 'hidden'], + [false, true, A, 'overlay'], + [false, false, A, 'overlay'], + [false, true, B, 'hidden'], + ] as const)('fits=%s pinned=%s overlay=%s shows %s', (fits, pinned, overlay, expected) => { + expect(presentationOf(fits, { pinned, overlay }, A)).toBe(expected) + }) +}) + +describe('SessionPanelState dock probes', () => { + it('enters an attached probe without room and gives it room from 1px of width', () => { + const state = new SessionPanelState() + expect(state.probes.getSnapshot().size).toBe(0) + const probe = probeOf(state, A) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + // Within a pixel below the gutter that docks the panel the probe is narrower than 1px. + probe.resize(0.5) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + probe.resize(1) + expect(state.probes.getSnapshot().get(probe.id)).toBe(true) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + probe.resize(0) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + }) + + it('gives a Session room while any of its probes has it, and drops the Session once its last probe detaches', () => { + const state = new SessionPanelState() + const main = probeOf(state, A, 1) + const embedded = probeOf(state, A) + expect(state.probes.getSnapshot()).toEqual(new Map([[main.id, true], [embedded.id, false]])) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + main.detach() + expect(main.observation.disconnected).toBe(true) + expect(state.probes.getSnapshot()).toEqual(new Map([[embedded.id, false]])) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + embedded.resize(1) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + embedded.detach() + expect(state.dockable.getSnapshot().has(A)).toBe(false) + expect(state.probes.getSnapshot().size).toBe(0) + // A second detachment of the same element withdraws nothing more. + const before = state.dockable.getSnapshot() + embedded.detach() + expect(state.dockable.getSnapshot()).toBe(before) + }) + + it('publishes only when a probe flips or a Session changes its room', () => { + const state = new SessionPanelState() + const main = probeOf(state, A, 1) + const probes = state.probes.getSnapshot() + const dockable = state.dockable.getSnapshot() + let probeCalls = 0 + let sessionCalls = 0 + const offProbes = state.probes.subscribe(() => { probeCalls += 1 }) + const offSessions = state.dockable.subscribe(() => { sessionCalls += 1 }) + main.resize(1) + expect(state.probes.getSnapshot()).toBe(probes) + expect(state.dockable.getSnapshot()).toBe(dockable) + // A second Chat View without room changes the probes, not the Session's room. + const embedded = probeOf(state, A) + expect([probeCalls, sessionCalls]).toEqual([1, 0]) + main.resize(0) + expect([probeCalls, sessionCalls]).toEqual([2, 1]) + embedded.detach() + expect([probeCalls, sessionCalls]).toEqual([3, 1]) + offProbes() + offSessions() + }) + + it('keeps a probe without room where ResizeObserver is missing', () => { + vi.stubGlobal('ResizeObserver', undefined) + const state = new SessionPanelState() + const ref = state.createProbeRef(A, 'unobserved') + ref(document.createElement('span')) + expect(state.probes.getSnapshot().get('unobserved')).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + ref(null) + expect(state.dockable.getSnapshot().has(A)).toBe(false) + }) + + it('stops observing every attached probe on dispose, after which a detachment withdraws nothing', () => { + const { state, a, b } = newState() + state.dispose() + expect([a.observation.disconnected, b.observation.disconnected]).toEqual([true, true]) + expect(state.probes.getSnapshot().size).toBe(0) + expect(state.dockable.getSnapshot().size).toBe(0) + const before = state.probes.getSnapshot() + a.detach() + expect(state.probes.getSnapshot()).toBe(before) + }) +}) + +describe('SessionPanelState visibility', () => { + it('docks by default and keeps the snapshot identity until a member changes', () => { + const { state } = newState() + const first = state.visibility.getSnapshot() + expect(first).toEqual({ pinned: true, overlay: null }) + expect(state.visibility.getSnapshot()).toBe(first) + }) + + it('flips and persists the docking preference when the gutter has room, closing any overlay', () => { + const { state, a } = newState() + state.toggle(A) + expect(state.visibility.getSnapshot().overlay).toBe(A) + a.resize(1) + expect(state.visibility.getSnapshot().overlay).toBeNull() + state.toggle(A) + expect(state.visibility.getSnapshot()).toEqual({ pinned: false, overlay: null }) + expect(localStorage.getItem(PINNED_STORAGE_KEY)).toBe('false') + expect(new SessionPanelState().visibility.getSnapshot().pinned).toBe(false) + state.toggle(A) + expect(state.visibility.getSnapshot().pinned).toBe(true) + }) + + it('opens and closes one Session overlay without touching the docking preference', () => { + const { state } = newState() + state.toggle(A) + state.toggle(B) + expect(state.visibility.getSnapshot()).toEqual({ pinned: true, overlay: B }) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBe(B) + state.toggle(B) + expect(state.visibility.getSnapshot().overlay).toBeNull() + state.toggle(A) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBeNull() + }) + + it('ignores the toggle of a Session that no Chat View shows', () => { + const state = new SessionPanelState() + const before = state.visibility.getSnapshot() + state.toggle(A) + expect(state.visibility.getSnapshot()).toBe(before) + }) + + it('treats a stored value other than false as the default', () => { + localStorage.setItem(PINNED_STORAGE_KEY, '"yes"') + expect(newState().state.visibility.getSnapshot().pinned).toBe(true) + }) + + it('notifies subscribers of both members and stops after unsubscribe', () => { + const { state, a } = newState() + let calls = 0 + const off = state.visibility.subscribe(() => { calls += 1 }) + state.toggle(A) + a.resize(1) + state.toggle(A) + const seen = calls + expect(seen).toBeGreaterThanOrEqual(2) + off() + state.toggle(A) + expect(calls).toBe(seen) + }) + + it('closes an overlay once its gutter can dock the panel, without reopening it when the gutter narrows again', () => { + const { state, a } = newState() + state.toggle(A) + a.resize(0.5) + expect(state.visibility.getSnapshot().overlay).toBe(A) + a.resize(1) + expect(state.visibility.getSnapshot()).toEqual({ pinned: true, overlay: null }) + a.resize(0) + expect(presentationOf(false, state.visibility.getSnapshot(), A)).toBe('hidden') + }) + + it('closes an overlay once no Chat View shows its Session, so returning to it shows no overlay', () => { + const { state, a } = newState() + state.toggle(A) + a.detach() + expect(state.visibility.getSnapshot().overlay).toBeNull() + probeOf(state, A) + expect(presentationOf(false, state.visibility.getSnapshot(), A)).toBe('hidden') + }) + + it('follows only the open overlay, and nothing after dispose', () => { + const { state, a } = newState() + state.toggle(A) + state.toggle(B) + // A's Chat View no longer matters once B holds the overlay. + a.detach() + expect(state.visibility.getSnapshot().overlay).toBe(B) + // Dispose withdraws B's probe too, but nothing follows the overlay any longer. + state.dispose() + expect(state.dockable.getSnapshot().has(B)).toBe(false) + expect(state.visibility.getSnapshot().overlay).toBe(B) + }) +}) diff --git a/packages/client/ui-session-panel/tsconfig.json b/packages/client/ui-session-panel/tsconfig.json new file mode 100644 index 0000000000..e868af02be --- /dev/null +++ b/packages/client/ui-session-panel/tsconfig.json @@ -0,0 +1,66 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" + }, + { + "path": "../../api/workspace-controller/tsconfig.client.json" + }, + { + "path": "../connection/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-chat/tsconfig.client.json" + }, + { + "path": "../ui-context-menu" + }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-session" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../core/session" + }, + { + "path": "../../util/workspace-path" + }, + { + "path": "../../session/working-directory" + }, + { + "path": "../../workspace/workspace" + } + ] +} diff --git a/packages/client/ui-session-panel/tsdown.config.ts b/packages/client/ui-session-panel/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-session-panel/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-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-right/README.i18n.yaml b/packages/client/ui-sidebar-right/README.i18n.yaml index ae8159f93c..0fbcd1aa5d 100644 --- a/packages/client/ui-sidebar-right/README.i18n.yaml +++ b/packages/client/ui-sidebar-right/README.i18n.yaml @@ -36,8 +36,8 @@ en: b6c64c7649203e12 zh: c9341bbfd548a5eb /deepseek-ai-dsh-client-ui-sidebar-right/the-guide: - en: 68fd575ef382223e - zh: 1ab1653ee20c64e9 + en: 2cc38fa6666dbc17 + zh: 1063018c8fe95012 /deepseek-ai-dsh-client-ui-sidebar-right/copy: en: 67386560b71672a4 zh: 35cf8cb7ddf618ce diff --git a/packages/client/ui-sidebar-right/README.md b/packages/client/ui-sidebar-right/README.md index b336f6f165..7fac795ae6 100644 --- a/packages/client/ui-sidebar-right/README.md +++ b/packages/client/ui-sidebar-right/README.md @@ -126,7 +126,7 @@ A tab type can declare `multiple: true` for independent instances such as termin Default pages depend on the number of registered guide entries, not tab types or open tabs. Exactly one entry opens its page directly; zero or multiple entries open the guide. Explicitly adding a guide always opens the guide. Closing follows the [sole-docked-tab rule](#state). -The guide tab is a muted compass over one entry capsule per `guide` entry the registered types contributed, in `order`, centred in the body; the guide has no words of its own. A capsule shows the entry's glyph — or the guide's quieter cube placeholder when the entry registered none — and its title; while at most four entries are listed, an entry that registered a `description` shows it under the title, and a longer list drops every description. Picking a default capsule or a **More tools** row calls `tab.actions.openTab(entry.kind, { replaceTab: true })` and then `tab.actions.close()`, so the guide gives way to the page it opened and closes itself when that page was revealed; the open-page shortcut from a focused guide does the same. A pane holds at most one guide tab. The strip's add control is drawn only while its pane holds none and opens one there with `openTab('guide', { paneId, revealIfOpened: false })`, so a guide in another pane does not capture the click; opening the guide into a pane that already has one focuses it instead; a guide dragged, dropped, or docked into such a pane merges into it — the arriving guide closes and the pane's own is focused; `duplicateTab` on the guide records nothing. A split, an expanded empty root pane, and the pane a sole tab vacates by dropping on its own edge use the same default-page rule, one tab per new pane; the self-edge drop leaves the dragged tab focused. A plain `openTab('guide')` opens or focuses the guide only within the active or named pane. Splitting an empty pane does nothing and returns no new pane. The product allows two horizontal panes, initially equal, with divider ratios limited to 20%–80%. Insufficient width blocks a new split; with two panes already present, a body drop moves the tab between panes instead of creating a third. At the two-pane limit, split controls are disabled with a focusable reason; closing back to one pane enables them. +The guide tab is a muted compass over one entry capsule per `guide` entry the registered types contributed, in `order`, centred in the body; a guide taller than its pane starts at the top and scrolls. The guide has no words of its own. A capsule shows the entry's glyph — or the guide's quieter cube placeholder when the entry registered none — and its title; while at most four entries are listed, an entry that registered a `description` shows it under the title, and a longer list drops every description. Picking a default capsule or a **More tools** row calls `tab.actions.openTab(entry.kind, { replaceTab: true })` and then `tab.actions.close()`, so the guide gives way to the page it opened and closes itself when that page was revealed; the open-page shortcut from a focused guide does the same. A pane holds at most one guide tab. The strip's add control is drawn only while its pane holds none and opens one there with `openTab('guide', { paneId, revealIfOpened: false })`, so a guide in another pane does not capture the click; opening the guide into a pane that already has one focuses it instead; a guide dragged, dropped, or docked into such a pane merges into it — the arriving guide closes and the pane's own is focused; `duplicateTab` on the guide records nothing. A split, an expanded empty root pane, and the pane a sole tab vacates by dropping on its own edge use the same default-page rule, one tab per new pane; the self-edge drop leaves the dragged tab focused. A plain `openTab('guide')` opens or focuses the guide only within the active or named pane. Splitting an empty pane does nothing and returns no new pane. The product allows two horizontal panes, initially equal, with divider ratios limited to 20%–80%. Insufficient width blocks a new split; with two panes already present, a body drop moves the tab between panes instead of creating a third. At the two-pane limit, split controls are disabled with a focusable reason; closing back to one pane enables them. ## Copy diff --git a/packages/client/ui-sidebar-right/README.zh.md b/packages/client/ui-sidebar-right/README.zh.md index 039062a104..54aef8cc2f 100644 --- a/packages/client/ui-sidebar-right/README.zh.md +++ b/packages/client/ui-sidebar-right/README.zh.md @@ -126,7 +126,7 @@ root 作用域的 `sidebar.right.tab.guide.actions` list 有注册项时,引 默认页取决于已注册的引导入口数,不取决于 tab 类型数或已打开的 tab 数。恰好一个入口时直接打开对应页面;没有入口或有多个入口时打开引导页。显式添加引导页始终打开引导页。关闭遵循[唯一停靠 tab 规则](#state)。 -引导 tab 是一枚弱化的罗盘,下方是各已注册类型贡献的每个 `guide` 条目一个入口胶囊,按 `order` 排列并在正文中居中;引导页自己没有文字。胶囊显示条目的图标——条目没注册图标时用引导页自己更浅的立方体占位符——和标题;列出的条目不超过四个时,注册了 `description` 的条目在标题下显示它,更长的列表则去掉所有描述。点击默认胶囊或**更多工具**菜单行会调用 `tab.actions.openTab(entry.kind, { replaceTab: true })`,再调用 `tab.actions.close()`,于是引导页让位给它打开的页,该页被揭示时引导页关闭自己;在聚焦的引导页上用快捷键打开页时也是如此。一个格最多持有一个引导 tab。tab 条的添加控件只在该格没有引导 tab 时绘制,并以 `openTab('guide', { paneId, revealIfOpened: false })` 在该格打开一个,这样别的格里的引导页不会截走这次点击;把引导页开进已有引导页的格则改为聚焦它;把引导页拖入、放入或收回到这样的格会合并进去——来者关闭,该格自己的被聚焦;对引导页 `duplicateTab` 不记录任何东西。分栏、展开且为空的根格、以及唯一 tab 拖到本格边缘分屏后腾出的格使用相同的默认页规则,每个新格一个 tab;这种本格边缘拖放让被拖的 tab 保持聚焦。普通的 `openTab('guide')` 只在活跃或指定分栏内打开或聚焦引导页。对空分栏执行 split 不产生变化,也不返回新分栏。产品最多保留左右两格,默认均分,分隔条限定在 20%~80%。宽度不足以容纳两格时不允许新分栏;已有两格时,正文拖放用于跨格移动,不再创建第三格。达到两格上限时禁用分栏控件并提供可聚焦的原因提示;关闭回单格后重新启用。 +引导 tab 是一枚弱化的罗盘,下方是各已注册类型贡献的每个 `guide` 条目一个入口胶囊,按 `order` 排列并在正文中居中;引导页高于所在格时从顶部开始排列并可滚动。引导页自己没有文字。胶囊显示条目的图标——条目没注册图标时用引导页自己更浅的立方体占位符——和标题;列出的条目不超过四个时,注册了 `description` 的条目在标题下显示它,更长的列表则去掉所有描述。点击默认胶囊或**更多工具**菜单行会调用 `tab.actions.openTab(entry.kind, { replaceTab: true })`,再调用 `tab.actions.close()`,于是引导页让位给它打开的页,该页被揭示时引导页关闭自己;在聚焦的引导页上用快捷键打开页时也是如此。一个格最多持有一个引导 tab。tab 条的添加控件只在该格没有引导 tab 时绘制,并以 `openTab('guide', { paneId, revealIfOpened: false })` 在该格打开一个,这样别的格里的引导页不会截走这次点击;把引导页开进已有引导页的格则改为聚焦它;把引导页拖入、放入或收回到这样的格会合并进去——来者关闭,该格自己的被聚焦;对引导页 `duplicateTab` 不记录任何东西。分栏、展开且为空的根格、以及唯一 tab 拖到本格边缘分屏后腾出的格使用相同的默认页规则,每个新格一个 tab;这种本格边缘拖放让被拖的 tab 保持聚焦。普通的 `openTab('guide')` 只在活跃或指定分栏内打开或聚焦引导页。对空分栏执行 split 不产生变化,也不返回新分栏。产品最多保留左右两格,默认均分,分隔条限定在 20%~80%。宽度不足以容纳两格时不允许新分栏;已有两格时,正文拖放用于跨格移动,不再创建第三格。达到两格上限时禁用分栏控件并提供可聚焦的原因提示;关闭回单格后重新启用。 ## 文案 diff --git a/packages/client/ui-sidebar-right/src/client/tab-inventory.ts b/packages/client/ui-sidebar-right/src/client/tab-inventory.ts index 1dfc139518..1fc33eeb1b 100644 --- a/packages/client/ui-sidebar-right/src/client/tab-inventory.ts +++ b/packages/client/ui-sidebar-right/src/client/tab-inventory.ts @@ -21,19 +21,21 @@ export class SidebarTabInventory { /** Read saved layouts once before the root service is published. */ constructor() { + let keys: readonly (string | null)[] = [] try { - if (typeof localStorage === 'undefined') return - const keys = Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) - for (const key of keys) { - if (key === null || !key.startsWith(`${sidebarPersistence}.`)) continue - const sessionId = key.slice(sidebarPersistence.length + 1) as SessionId - const saved = readSidebarLayout(sessionId) - if (saved !== undefined) this.sessions.set(sessionId, Object.values(saved.layout.tabs).map(tab => ({ - sessionId, tabId: tab.id, kind: tab.kind, contentId: tab.contentId, - }))) - } - this.publish() - } catch (_storageUnavailable) { /* Adopted in-memory layouts still publish their open tabs. */ } + keys = typeof localStorage === 'undefined' ? [] : Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) + } catch (_storageUnavailable) { + // Inaccessible storage holds no saved layouts; adopted in-memory layouts still publish their open tabs. + } + for (const key of keys) { + if (key === null || !key.startsWith(`${sidebarPersistence}.`)) continue + const sessionId = key.slice(sidebarPersistence.length + 1) as SessionId + const saved = readSidebarLayout(sessionId) + if (saved !== undefined) this.sessions.set(sessionId, Object.values(saved.layout.tabs).map(tab => ({ + sessionId, tabId: tab.id, kind: tab.kind, contentId: tab.contentId, + }))) + } + this.publish() } /** diff --git a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css index b78983aa2d..f3d2133213 100644 --- a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css +++ b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css @@ -2,23 +2,26 @@ stylesheet does not carry them. Tokens only. */ /* The capsules form one centred column at the column's own 14px gap, lifted - above the body's middle by the spacer below. The minimum height centres a - short guide while allowing a tall guide to grow into the pane's scroller. */ + above the body's middle by the spacer below. The guide fills the tab body, + which clips, and scrolls itself; `safe` centring starts a guide taller than + the pane at its top so every capsule stays reachable. The block padding + keeps a scrolled-to-end capsule's focus ring off the pane's edge. */ .guide { --dsl-guide-entry-radius: var(--dsw-radius-xl); display: flex; + flex: 1 1 auto; flex-direction: column; gap: 14px; align-items: center; - justify-content: center; + justify-content: safe center; box-sizing: border-box; - min-height: 100%; - padding: 0 24px; + padding: 14px 24px; + overflow-y: auto; } /* The lift, as a share of the pane's height (a column flex basis resolves against it): the centred column rises 5% of the pane, and a short pane - gives it up before the capsules clip. */ + gives it up before the column overflows. */ .guide::after { content: ''; flex: 0 1 10%; diff --git a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx index 4cff92b514..6c73fa8869 100644 --- a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx +++ b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx @@ -9,8 +9,9 @@ * cannot be outvoted by accident. * * The shipped guide is a muted compass over the pinned entry capsules every - * registered type contributed, centred in the body, with no heading, as a - * browser start page shows its doors without a caption. While at most four + * registered type contributed, centred in the body (scrolling from the top when + * taller than the pane), with no heading, as a browser start page shows its + * doors without a caption. While at most four * capsules are visible, a capsule with a description shows it under the title; * a longer list drops every description to stay light. A More card follows * while `sidebar.right.tab.guide.actions` has registrations. diff --git a/packages/client/ui-skill/src/client/SkillRow.tsx b/packages/client/ui-skill/src/client/SkillRow.tsx index cee91367cf..fb3c3710ca 100644 --- a/packages/client/ui-skill/src/client/SkillRow.tsx +++ b/packages/client/ui-skill/src/client/SkillRow.tsx @@ -27,16 +27,17 @@ function firstLine(text: string): string { /** Skill names are the only call argument the compact row presents. */ function skillName(argsRaw: string, callId: string): string { + let parsed: unknown try { - const parsed: unknown = JSON.parse(argsRaw) - if (typeof parsed === 'object' && parsed !== null) { - const name = (parsed as Record).name - if (typeof name === 'string' && name !== '') return firstLine(name) - } - } catch { + parsed = JSON.parse(argsRaw) + } catch (_truncatedArgs) { // Streaming can expose a truncated JSON prefix; its first line is still // more useful than replacing the call with an unrelated catalog lookup. } + if (typeof parsed === 'object' && parsed !== null) { + const name = (parsed as Record).name + if (typeof name === 'string' && name !== '') return firstLine(name) + } return argsRaw === '' ? callId : firstLine(argsRaw) } diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 7381b1f9d5..855eca71ba 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: 77677cfa89b26de8 + zh: 83909430c95f3a6b /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..e1a6e31218 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. -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..eaf55b25f9 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 与宽度控制。 -每个打开的目录菜单宽度均为 360px,外层内边距为 6px,并受布局视口可用宽度约束。仅当 Team 模式已开启、存在至少一个未删除的共享任务且 footer 扩展可用时,根菜单才显示不可折叠的“子智能体”和“共享任务”标题。“子智能体”标题使用 Users 图标,仅统计直接条目,依次显示已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。空的“子智能体”区域仅在同时展示共享任务时显示“暂无子智能体”。Team 模式关闭或没有共享任务时,菜单仅显示 subagent 列表,不显示区域标题、共享任务模块、空状态文案或分隔线;真实的任务记录错误仍以独立警告显示。共享任务上方保留 4px 外边距,不显示分隔线。两个区域标题均保留 7px 图标与文字间距,并在统计数量前额外留出 4px。仅菜单本身滚动,各区域不单独滚动。在兼容 WebKit 的浏览器中,原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 +分栏的标题控件(`conversation.session.panel.section.actions`,键为 `subagents`)显示直接成员进度:依次为已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。分栏把运行中的子智能体排在最前,最近开始的在前,然后是其余的,最近更新的在前。它只显示五行,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变;展开某个分支后,该分支自己的行全部显示。会话没有子智能体且目录读取未失败时,分栏连同标题一起隐藏。直接子智能体运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;外部任务不计入。会话面板负责分栏滚动,目录树不单独滚动。面包屑切换器菜单宽度为 360px,外层内边距为 6px,并受布局视口可用宽度约束,仅菜单本身滚动。在兼容 WebKit 的浏览器中,其原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 -根会话目录通过 `conversation.session.header.actions.subagent.footer` 提供共享任务扩展。子会话与祖先面包屑目录只显示导航,不显示区域标题。 +面包屑切换器菜单只显示导航。 -宽布局下,根会话数量触发器在没有运行中 child 时,于 14px 图标位内显示 14px Users 图标,否则显示共享 ongoing loader,不带下拉箭头。标题行变窄时,静态预设文字在宽度不超过 540px 时隐藏,数量文字在不超过 460px 时隐藏。紧凑触发器始终显示 Users 图标,包括 child 运行期间;运行指示器仍在菜单内显示。它与更多及侧边栏控件一致:28×28px 操作区域,无内边距,15px 图标位内显示 15px 图标,使用次级前景色以及 ghost 悬停和按下背景。页头操作在紧凑布局中间距为 8px,宽布局中为 10px。纯图标工具提示提供完整数量。调整宽度不会丢失触发器焦点。subagent 切换器保留描述优先的文本与原有图标。 +切换器标题最宽 244px,超出时以省略号截断,后接上下双向箭头图标。当前 Session 的标题使用主前景色、字重 500;祖先标题使用三级前景色、常规字重。 ### 浏览目录 -数量、负责人及侧边栏操作的工具提示在悬停 500ms 后显示。悬停文字可见的触发器 150ms 后打开目录;指针离开触发器和目录后,经过 120ms 关闭。点击后代数量触发器会打开并固定目录,或关闭已固定的目录。纯图标数量触发器不会因悬停而打开,包括等待悬停打开期间切换到窄布局的情况。点击可切换固定菜单的开关状态;ArrowDown 会打开并固定菜单,并将焦点移至首行。点击外部或按 Escape 可关闭已固定的菜单。点击会将焦点移入面板,此时 ArrowDown/Home 进入首个树行,ArrowUp/End 进入最后一个树行;Escape 在焦点原本位于面板内时将其送回。点击面包屑标题会导航至对应会话。 +侧边栏操作的工具提示在悬停 500ms 后显示。非触摸指针悬停切换器 150ms 后打开其菜单;指针离开切换器和菜单后,经过 120ms 关闭。点击当前 Session 的标题会打开并固定菜单,并将焦点移入菜单,已固定的菜单不因指针离开而关闭;点击祖先标题则导航至该祖先。在切换器上按 ArrowDown 会打开菜单,并将焦点移至首行;菜单已打开时,焦点移入菜单,行加载完成后移至首行。点击外部或按 Escape 可关闭菜单;焦点原本位于菜单内时,Escape 将焦点送回切换器。 -目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。点击或通过键盘打开菜单时,读取当前目录及其直属子节点的目录;展开分支时对该分支执行相同操作。每次打开操作通过现有投影读取器依次读取直接子节点,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。悬停与渲染不触发读取。已开始的单层读取可能在菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 +目录行显示创建描述(缺少时使用可用的 Session title)和智能体名称,名称在同级子智能体中唯一:切换器菜单中名称位于标题下方;会话面板中每行只占 28px 一行,悬停 500ms 后的悬停卡片显示标题、作为负责人的名称、活动状态与模式,以及 token 总计和精确耗时。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距。在会话面板中,它们遵循面板的列:状态图标中心距行起始 14px,标题从 30px 开始,侧边栏箭头中心距行末端 14px。在切换器菜单中,可点击内容使用 6px 水平内边距和 7px 间距,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头:点击区域 24px,在面板和切换器菜单中都是悬停时箭头变深、没有底色。主标题使用 13px 文字,次级名称使用 12px。切换器菜单中的行将描述与名称换行完整展示,包括在触屏上;面板中的标题以省略号截断,行的无障碍名称仍包含名称、模式、活动状态与度量。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的列宽(面板中 16px,切换器菜单中 14px),并将较小的圆点居中,使 title 与 loading 状态对齐。切换器菜单中,尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时;面板中的行只以 12px 文字显示简短耗时。在目录树中,Enter 或 Space 打开获得焦点的行,ArrowRight/ArrowLeft 展开和折叠分支,ArrowUp/ArrowDown、Home 与 End 在行间移动。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。准备一层时,通过现有投影读取器依次读取其目录及直接子节点的目录,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。已开始的单层读取可能在面板隐藏或菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 ### 续接对话 @@ -61,17 +61,17 @@ kind: "package-reference" ### 目录派生 -页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 +「子智能体」分栏、其进度控件与面包屑切换器通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需逐树订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。显示分栏、渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空切换器菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 -每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 +会话面板负责分栏的显示、滚动和关闭。切换器菜单是挂载到 body 的 `MenuSurface`;CSS 锚点让菜单跟随其标题,并按布局视口限制尺寸。浏览器缩放和平移时菜单随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 -显式激活菜单、展开分支或重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 +在切换器标题上固定打开的点击或按 ArrowDown、展开分支以及重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点;准备被拒绝时记录到控制台。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。 ### 耗时、完成状态与 token -每个可见目录层在包含运行中 child 时独立推进时钟;折叠该层或关闭菜单会释放时钟。token 用量总计为四个互不重叠的 `tokenUsage` 桶之和。`subagentTiming` 投影会累加已结束轮次的耗时,并提供 `latestTurnCompleted`,用于成功圆点与已完成数量;新轮次开始时会清除该完成状态,直到自身的 `turn/end` 到达。耗时仅在运行中 child 存在未结束轮次时每秒递增一次,并在 child 变为 inactive 后冻结;被中断的未结束轮次以其同一切面的 `active.through` 为上界,绝不使用更新的会话元数据。 +每个可见目录层在包含运行中 child 时独立推进时钟;折叠该层、隐藏面板或关闭切换器菜单会释放时钟。token 用量总计为四个互不重叠的 `tokenUsage` 桶之和。`subagentTiming` 投影会累加已结束轮次的耗时,并提供 `lastTurnCompleted`,用于成功圆点与已完成数量;新轮次开始时会清除该完成状态,直到自身的 `turn/end` 到达。耗时仅在运行中 child 存在未结束轮次时每秒递增一次,并在 child 变为 inactive 后冻结;被中断的未结束轮次以其同一切面的 `active.through` 为上界,绝不使用更新的会话元数据。 ### 编辑器选举 @@ -79,7 +79,7 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 模式未知的目录项仍可见、可点击,没有标签时显示子会话 id。读取子历史并确认受支持模式前,输入区保持只读;读取失败在该子会话中报告。 -会话树菜单高亮遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover)。每个分支展开控件的点击区域覆盖左侧 28px 空间与所在行的完整高度,不与相邻行重叠;仅原位的 12px 图标旋转,点击展开控件不会触发行导航或侧边栏导航。悬停展开控件仅高亮箭头;悬停导航主体或键盘聚焦时仍保留背景高亮。细连接线使用三级边框颜色,与首行图标中心对齐,跨过预留的展开控件空间连接叶子状态图标,末端竖线止于对应图标中心。 +目录行高亮使用[嵌套几何规则](../../../docs/ui-radius.zh.md#nested-hover)中的标准菜单项圆角。每个分支展开控件的点击区域覆盖左侧 28px 空间与所在行的完整高度,不与相邻行重叠;仅原位的 12px 图标旋转,点击展开控件不会触发行导航或侧边栏导航。悬停展开控件仅高亮箭头;悬停导航主体或键盘聚焦时仍保留背景高亮。细连接线使用三级边框颜色,与首行图标中心对齐,跨过预留的展开控件空间连接叶子状态图标,末端竖线止于对应图标中心。 @@ -90,7 +90,8 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 以下页面覆盖对话界面、宿主 seam 与设计笔记。 -- [ui-conversation](../ui-conversation/README.zh.md)——承载页头操作与编辑器链的聊天界面。 +- [ui-conversation](../ui-conversation/README.zh.md)——承载面包屑谱系与编辑器链的聊天界面。 +- [ui-session-panel](../ui-session-panel/README.zh.md)——承载「子智能体」分栏的会话面板。 - [ui-input-trigger](../ui-input-trigger/README.zh.md)——承载 `@` source 的建议机制。 - [subagent](../../subagent/subagent/README.zh.md)——可继续 child 背后的宿主能力 seam。 - [历史Web subagent 对话](../../../.agents/notes/archived/feature/2026-07-27-web-subagent-conversations.md)——目录与编辑器规范。 @@ -125,6 +126,7 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 - **非完成的 inactive 结果仍合并显示**:目录能区分最近一次正常完成与其他 inactive 状态,但不区分失败、取消、拒绝、token 耗尽或尚无已结束轮次的 child;UI 不公开 Activation 身份,停止能力仅限编辑器上针对运行中可继续 child 的当前轮次 Stop。 - **祖先菜单的未缓存分支需要键盘激活**:悬停不读取,点击祖先标题会导航。聚焦标题后按 ArrowDown,可在不离开当前 Session 的情况下准备这一层。 - **单层发现会在中断后停止**:意外的读取拒绝会停止后续兄弟节点,并记录到控制台。重连可能在直接子节点读取前中断发现;需再次显式打开菜单来准备这一层。 +- **会话面板分栏没有层级激活**:显示分栏不读取任何内容,因此 Session 列表未缓存其目录的直接子智能体在分栏中没有展开箭头,直到其目录到达,例如打开它自己的对话后,或在兄弟会话的面包屑切换器中准备这一层后。 - **`@` 引用仍是显示标题文本**:重复或改名后的 label 会有歧义,因此它们刻意不获得继续执行语义。 diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index f6b08201bc..0f3ac4e008 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -34,10 +34,11 @@ "@deepseek-ai/dsh-client-resources", "@deepseek-ai/dsh-client-ui-chat", "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives", - "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-input-trigger", + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel", "@deepseek-ai/dsh-client-ui-session-status", + "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-workspace" ], "platform": "web" @@ -52,28 +53,29 @@ "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", + "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-api-session-controller": "workspace:*", - "@deepseek-ai/dsh-client-connection": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", - "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", - "@deepseek-ai/dsh-client-ui-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", - "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", - "@deepseek-ai/dsh-agent-team": "workspace:*" + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css similarity index 74% rename from packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css rename to packages/client/ui-subagent/src/client/SubagentCatalog.module.css index c450098395..86cc042428 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css @@ -11,7 +11,6 @@ margin-left: 6px; } -.trigger, .switcherTrigger { display: inline-flex; align-items: center; @@ -26,10 +25,6 @@ cursor: pointer; } -.trigger { - gap: 4px; -} - .switcherTrigger { gap: 4px; min-width: 0; @@ -57,25 +52,6 @@ flex: none; } -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-primary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-primary); - } -} - .switcherTrigger:focus-visible { color: var(--dsw-alias-label-primary); } @@ -100,55 +76,6 @@ transition: transform 120ms ease; } -.trigger .compactIcon { - display: none; -} - -/* The title-row container drops passive preset text at 540px; this action yields later. */ -@container (max-width: 460px) { - .trigger .compactIcon { - display: block; - } - - .trigger .textModeActivity { - display: none; - } - - .trigger .count { - display: none; - } - - .trigger { - box-sizing: border-box; - width: 28px; - height: 28px; - padding: 0; - justify-content: center; - color: var(--dsw-alias-label-secondary); - } - - .trigger .activitySlot, - .trigger .activitySlot > svg { - width: 15px; - height: 15px; - } - - .trigger:focus-visible { - color: var(--dsw-alias-label-secondary); - } - - .trigger:active { - background: var(--dsw-alias-interactive-bg-active); - } - - @media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - background: var(--dsw-alias-interactive-bg-hover); - } - } -} - .menu { position: fixed; z-index: 100; @@ -193,47 +120,112 @@ } } -.sectionHeader { - display: flex; - align-items: flex-start; - gap: 7px; - padding: 4px 7px 8px; -} - -.sectionIcon { - display: grid; - flex: none; - place-items: center; - width: 14px; - height: 24px; - color: var(--dsw-alias-label-tertiary); -} - -.sectionTitle { - flex: none; - margin: 0; - color: var(--dsw-alias-label-primary); - font-size: 13px; - font-weight: 500; - line-height: 24px; -} - +/* Progress beside the Session panel section title, one line that clips before the title does. */ .sectionProgress { - margin-inline-start: 4px; - flex: 1 1 auto; min-width: 0; - padding-top: 2px; + overflow: hidden; color: var(--dsw-alias-label-tertiary); - font-size: 13px; - line-height: 20px; - overflow-wrap: anywhere; + font: var(--dsw-font-xxs-12); + font-variant-numeric: tabular-nums; + text-overflow: ellipsis; + white-space: nowrap; } -.sectionEmpty { - margin: 0; - padding: 0 7px 8px 28px; +/* The panel toggle sizes and places this dot; it names the state for assistive technology. */ +.runningIndicator { + background: var(--dsw-alias-state-business-primary); +} + +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +/* The Session panel section supplies the inset and scrolling. Rows share the + panel's columns: the status glyph's center 14px from the row start, text at + 30px, and the chevron's center 14px from the row end. */ +.sectionBody { + display: flex; + flex-direction: column; + min-width: 0; +} + +/* One 28px line per row: the name clips, and its owner, state, and tokens show in the row's hover card. */ +.sectionBody .row { + gap: 8px; + min-height: 28px; + padding: 4px 6px; +} + +.sectionBody .clickarea { + gap: 8px; + border-radius: var(--dsw-radius-sm); +} + +.sectionBody .rowActivitySlot { + width: 16px; + height: 20px; +} + +.sectionBody .disclosure, +.sectionBody .disclosureSpace { + width: 16px; + height: 20px; +} + +.sectionBody .label { + overflow: hidden; + line-height: 20px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sectionBody .duration { + flex: none; color: var(--dsw-alias-label-tertiary); font-size: 12px; + font-variant-numeric: tabular-nums; + line-height: 20px; + white-space: nowrap; +} + +/* The tree's spine sits on the status column's center, and leaves a parent row + just below its 6px dot. Each row sits in its hover card's anchor wrapper. */ +.sectionBody .children { + --branch-anchor-y: 14px; + margin-left: 14px; +} + +.sectionBody .children::before { + top: -10px; + height: 10px; +} + +.sectionBody .children > .node > :first-child > .row::before { + content: ''; + position: absolute; + top: calc(var(--branch-anchor-y) - 0.25px); + left: -3px; + width: 9px; + border-top: 0.5px solid var(--dsw-alias-border-l3); +} + +.sectionBody .children > .node > :first-child > .row:has(> .disclosureSpace)::before { + width: 33px; +} + +/* In the panel's columns the arrow's 24px target centers on the trailing column + and overhangs the 20px line, so the row keeps its 28px. */ +.sectionBody .sidebarButton, +.sectionBody .sidebarSpace { + align-self: center; + width: 24px; + height: 24px; + margin: -2px -4px; } .node { @@ -390,7 +382,6 @@ grid-row: 2; } -.sidebarButton, .sidebarSpace { box-sizing: border-box; flex: none; @@ -405,26 +396,32 @@ color: var(--dsw-alias-label-primary); } +/* The arrow shares its row's highlight: a 24px target whose glyph darkens + without a fill, in the panel and in the switcher menu alike. In the menu it + keeps the 28px trailing column the current row's check also fills. */ .sidebarButton { + box-sizing: border-box; display: inline-flex; + flex: none; align-items: center; justify-content: center; - padding: 6px; + width: 24px; + height: 24px; + margin: 6px 2px; + padding: 0; border: 0; - border-radius: var(--dsw-radius-sm); + border-radius: var(--dsw-radius-xs); background: transparent; color: var(--dsw-alias-label-tertiary); cursor: pointer; } .sidebarButton:focus-visible { - background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } @media (hover: hover) { .sidebarButton:hover { - background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } } diff --git a/packages/client/ui-subagent/src/client/SubagentCatalog.tsx b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx new file mode 100644 index 0000000000..ced031b05b --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx @@ -0,0 +1,602 @@ +/** Subagent catalog tree shared by the Session panel section and the breadcrumb switcher. */ +import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +import type { + SessionListState, SessionProjectionMap, SessionProjectionSnapshot, SessionSummary, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + HoverCard, IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconRefreshOutlineRegular, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-token-meter/client' +import css from './SubagentCatalog.module.css' + +/** One Session's direct subagents with their live activity. */ +export type SubagentCatalogSnapshot = Omit & { + state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' + entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] +} + +/** Catalogs of every Session whose projections the Client holds. */ +export type Catalogs = Readonly> + +/** Business actions supplied by the slot registrations. */ +export type SubagentCatalogInjected = { + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + /** Read this catalog and its direct children after explicit activation or retry. */ + prepareCatalog: (parentSessionId: SessionId) => Promise +} + +interface CatalogRowsProps { + parentSessionId: SessionId + currentSessionId: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: Readonly> + expanded: ReadonlySet + level: number + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + toggleBranch: (childSessionId: SessionId) => void + closeCatalog: () => void + panelDetails: CatalogTreeProps['panelDetails'] +} + +/** + * List the focusable rows of a catalog tree in display order. + * @param root - the tree or an element that contains it. + * @returns the rows that accept focus. + */ +export function treeItems(root: HTMLElement): HTMLElement[] { + return Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) +} + +/** Compact token count shared in shape with the conversation stats strip. */ +function formatTokens(value: number, t: TranslateNS): string { + const scaled = (next: number): string => next >= 100 + ? String(Math.round(next)) + : String(Math.round(next * 10) / 10) + if (value < 1_000) return String(value) + if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) + return t('tokens.million', { value: scaled(value / 1_000_000) }) +} + +/** Sum the four disjoint durable provider-usage buckets. */ +function tokenTotal( + usage: SessionProjectionMap['tokenUsage'] | undefined, +): number | undefined { + return usage === undefined + ? undefined + : usage.uncachedInputTokens + usage.outputTokens + + usage.cacheReadTokens + usage.cacheWriteTokens +} + +/** Exact whole-second active-turn duration for one catalog row. */ +function activityDuration( + summary: SessionSummary | undefined, + activity: 'running' | 'inactive', + now: number, +): number | undefined { + if (summary === undefined) return undefined + const timing: SessionProjectionMap['subagentTiming'] | undefined + = summary.projectionValues?.subagentTiming + if (timing === undefined) return undefined + if (timing.active === undefined) return timing.settledMs + const end = activity === 'running' + ? now + : timing.active.through + return timing.settledMs + Math.max(0, end - timing.active.since) +} + +interface DurationParts { + seconds: number + minutes: number + hours: number + days: number + totalMinutes: number + totalHours: number +} + +function splitDuration(ms: number): DurationParts { + const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) + const totalMinutes = Math.floor(totalSeconds / 60) + const totalHours = Math.floor(totalMinutes / 60) + return { + seconds: totalSeconds % 60, + minutes: totalMinutes % 60, + hours: totalHours % 24, + days: Math.floor(totalHours / 24), + totalMinutes, + totalHours, + } +} + +/** Format a duration with decreasing visual precision at larger scales. */ +function formatDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) + if (days >= 365) { + const years = Math.floor(days / 365) + const months = Math.floor((days % 365) / 30) + return months === 0 + ? t('duration.years', { years }) + : t('duration.yearsMonths', { years, months }) + } + if (days >= 30) { + const months = Math.floor(days / 30) + const remainingDays = days % 30 + return remainingDays === 0 + ? t('duration.months', { months }) + : t('duration.monthsDays', { months, days: remainingDays }) + } + if (days > 0) { + return hours === 0 + ? t('duration.days', { days }) + : t('duration.daysHours', { days, hours }) + } + if (totalHours > 0) { + return t('duration.hours', { + hours: totalHours, + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) + } + if (totalMinutes > 0) { + return t('duration.minutes', { + minutes: totalMinutes, + seconds: String(seconds).padStart(2, '0'), + }) + } + return t('duration.seconds', { seconds }) +} + +/** Preserve exact whole seconds for hover and accessible naming. */ +function formatExactDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days } = splitDuration(ms) + return days === 0 + ? formatDuration(ms, t) + : t('duration.exactDays', { + days, + hours: String(hours).padStart(2, '0'), + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) +} + +/** Render catalog loading without inventing child membership. */ +function CatalogLoadingRows({ t }: { t: TranslateNS }) { + return
    {t('loading.label')}
    +} + +/** Only confirmed child membership exposes a branch disclosure. */ +function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { + return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 + && summaries[entry.id]?.formatStatus !== 'migration-required' + && catalogs[entry.id]?.state !== 'migration-required' +} + +/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ +/** + * Name a catalog entry when it has no description. + * @param entry - catalog entry. + * @returns the entry's display name. + */ +export function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { + return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id +} + +/** Only a local child's last closed, normally completed turn receives the completed marker. */ +function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { + return entry.mode !== 'external' && entry.activity === 'inactive' + && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true +} + +/** Count direct catalog members without treating external or other inactive entries as completed. */ +function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + let completed = 0 + let active = 0 + let inactive = 0 + let external = 0 + for (const entry of entries) { + if (entry.mode === 'external') external++ + else if (entry.activity === 'running') active++ + else if (completedEntry(entry, summaries[entry.id])) completed++ + else inactive++ + } + return [ + ...completed > 0 ? [t('progress.completed', { count: completed })] : [], + ...active > 0 ? [t('progress.active', { count: active })] : [], + ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], + ...external > 0 ? [t('progress.external', { count: external })] : [], + ].join('\u2002·\u2002') +} + +/** Render one catalog level and recurse only through explicitly expanded rows. */ +function CatalogRows({ + parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, + openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, panelDetails, t, +}: CatalogRowsProps & { t: TranslateNS }) { + const dense = panelDetails !== undefined + const [now, setNow] = useState(() => Date.now()) + const running = catalog.entries.some(entry => entry.activity === 'running') + useEffect(() => { + if (!running) return + const timer = setInterval(() => { setNow(Date.now()) }, 1_000) + return () => { clearInterval(timer) } + }, [running]) + const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 + const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) + return ( + <> + {catalog.state === 'idle' && catalog.entries.length === 0 && ( +
    {t('load.idle')}
    + )} + {emptyLoading && ( + + )} + {catalog.state === 'error' && ( +
    + {catalog.error?.message ?? t('load.error')} + +
    + )} + {catalog.entries.map((entry) => { + const external = entry.mode === 'external' + const childCatalog = catalogs[entry.id] + const isCurrent = entry.id === currentSessionId + const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' + || childCatalog?.state === 'migration-required' + const canExpand = canExpandCatalog(entry, catalogs, summaries) + const isExpanded = canExpand && expanded.has(entry.id) + const summary = summaries[entry.id] + const description = entry.label || summary?.title + const name = entryName(entry) + const primaryLabel = description || name + const secondaryLabel = description ? name : undefined + const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') + : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') + const completed = completedEntry(entry, summary) + const activity = external ? undefined : entry.activity === 'running' + ? t('activity.running') + : completed + ? t('activity.completed') + : t('activity.inactive') + const secondary = [secondaryLabel, mode, activity] + .filter(value => value !== undefined) + .join(' · ') + const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) + const durationMs = activityDuration( + summary, + entry.activity, + now, + ) + const tokenMetric = totalTokens === undefined + ? undefined + : t('tokens.total', { value: formatTokens(totalTokens, t) }) + const durationMetric = durationMs === undefined + ? undefined + : { + compact: formatDuration(durationMs, t), + exact: formatExactDuration(durationMs, t), + } + const metrics = [tokenMetric, durationMetric?.exact] + .filter(value => value !== undefined) + .join(' · ') + const dotState = entry.activity === 'running' ? 'ongoing' : completed ? 'done' : 'idle' + + const open = (): void => { + if (external) return + openChild({ + parentSessionId, + childSessionId: entry.id, + mode: entry.mode, + }) + closeCatalog() + } + const handleKey = (event: KeyboardEvent): void => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + event.stopPropagation() + open() + } else if ( + (event.key === 'ArrowRight' && canExpand && !isExpanded) + || (event.key === 'ArrowLeft' && isExpanded) + ) { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + } + const toggle = (event: MouseEvent): void => { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + + const row = ( +
    value !== '').join(' ')} + {...canExpand ? { 'aria-expanded': isExpanded } : {}} + className={css.row} + onClick={open} + onKeyDown={handleKey} + > + {!canExpand + ? reserveDisclosure && + : ( + + )} +
    + + + + + {primaryLabel} + {!dense && secondaryLabel !== undefined && ( + {secondaryLabel} + )} + + {dense + ? durationMetric !== undefined && {durationMetric.compact} + : metrics !== '' && ( + + {tokenMetric !== undefined && {tokenMetric}} + {durationMetric !== undefined && ( + {durationMetric.compact} + )} + + )} + {isCurrent + ? ( + + + + ) + : external ? : ( + + + + )} +
    +
    + ) + const details = panelDetails?.({ + title: primaryLabel, + lines: secondaryLabel === undefined ? [] : [t('hover.owner', { name: secondaryLabel })], + status: { state: dotState, label: [activity, mode].filter(value => value !== undefined).join(' · ') }, + facts: [ + ...tokenMetric === undefined ? [] : [{ kind: 'tokens' as const, label: tokenMetric }], + ...durationMetric === undefined ? [] : [{ kind: 'duration' as const, label: durationMetric.exact }], + ], + }) + + return ( +
    + {dense ? : row} + {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( +
    + {t('load.error')} + +
    + )} + {childCatalog !== undefined && isExpanded && ( +
    + +
    + )} +
    + ) + })} + + ) +} + +/** + * Build every held Session's catalog from its projection and live status. + * @param projections - projection snapshots by Session. + * @param summaries - Session list rows by id. + * @param statuses - live Session statuses. + * @returns catalogs keyed by parent Session. + */ +export function deriveCatalogs( + projections: SessionListState['projectionsBySession'], + summaries: SessionListState['byId'], + statuses: SessionStatusSnapshot, +): Catalogs { + return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { + const projected = snapshot.values.subagentCatalog + const state = snapshot.state === 'idle' + ? projected === undefined ? 'idle' : 'ready' + : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state + return [id, { + state, + error: snapshot.error, + entries: (projected ?? []).map(entry => ({ + ...entry, + activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true + ? 'running' as const : 'inactive' as const, + })), + } satisfies SubagentCatalogSnapshot] + })) +} + +/** + * The direct subagents of `catalog`'s Session plus progress, as one phrase such as "2 of 3 done". + * @param catalog - catalog whose entries are counted. + * @param summaries - Session list rows by id. + * @param t - subagent copy. + * @returns the progress phrase, or an empty string without entries. + */ +export function progressOf(catalog: SubagentCatalogSnapshot, summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + return catalogProgress(catalog.entries, summaries, t) +} + +/** + * Bind catalog preparation as a fire-and-forget level read; a rejection is + * logged, and the next activation or retry prepares the level again. + * @param prepareCatalog - the injected catalog action. + * @returns a callback that prepares one level. + */ +export function levelPreparer(prepareCatalog: SubagentCatalogInjected['prepareCatalog']): (sessionId: SessionId) => void { + return (sessionId) => { + void prepareCatalog(sessionId).catch((error: unknown) => { + console.error('[ui-subagent] catalog discovery failed:', error) + }) + } +} + +/** Props of one subagent tree. */ +export interface CatalogTreeProps { + /** Session whose direct catalog roots the tree. */ + rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId?: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: CatalogRowsProps['summaries'] + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + /** Read a level's catalog and its direct children; the tree calls it on branch expansion and retry. */ + prepareLevel: (parentSessionId: SessionId) => void + /** Called after a row opened a Session, so a surrounding popover or overlay can close. */ + onOpened: () => void + /** Focus the first row on mount, as a keyboard-opened popover does. */ + focusFirst?: boolean + /** + * Renders the Session panel's row details. With it the tree lists one-line + * rows, as the Session panel does, and each row shows its name, owner, + * state, and measures in a hover card. + */ + panelDetails?: ((details: PanelDetailsProps) => ReactNode) | undefined + t: TranslateNS +} + +/** + * Render a subagent tree with expandable branches and roving arrow-key focus. + * A row offers expansion only after its own catalog has entries; expanding it + * prepares that level, and collapsing a branch also collapses its descendants. + * @param props - catalog data, actions, and copy. + * @returns the tree. + */ +export function CatalogTree({ + rootSessionId, currentSessionId, catalog, catalogs, summaries, + openChild, openChildAside, prepareLevel, onOpened, focusFirst = false, panelDetails, t, +}: CatalogTreeProps) { + const [expanded, setExpanded] = useState>(() => new Set()) + const treeRef = useRef(null) + useEffect(() => { + // Effects run after commit, when the tree element is attached. + if (focusFirst) treeItems(treeRef.current as HTMLDivElement)[0]?.focus() + }, [focusFirst]) + + const closeBranch = (root: SessionId): void => { + const closing = new Set() + const visit = (parentSessionId: SessionId): void => { + if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return + closing.add(parentSessionId) + for (const entry of catalogs[parentSessionId]?.entries ?? []) visit(entry.id) + } + visit(root) + setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) + } + + const toggleBranch = (childSessionId: SessionId): void => { + if (expanded.has(childSessionId)) { + closeBranch(childSessionId) + return + } + setExpanded(current => new Set(current).add(childSessionId)) + prepareLevel(childSessionId) + } + + const navigate = (event: KeyboardEvent): void => { + const items = treeItems(event.currentTarget) + const index = items.indexOf(document.activeElement as HTMLElement) + const focusAt = (next: number): void => { items[(next + items.length) % items.length]?.focus() } + if (items.length === 0) return + if (event.key === 'Home') focusAt(0) + else if (event.key === 'End') focusAt(items.length - 1) + else if (event.key === 'ArrowDown') focusAt(index + 1) + else if (event.key === 'ArrowUp') focusAt(index < 0 ? items.length - 1 : index - 1) + else return + event.preventDefault() + } + + return ( +
    + +
    + ) +} diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index 8cbb5be217..aff8538a83 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -1,182 +1,22 @@ -import { useMemo, useEffect, useId, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +/** Breadcrumb switcher for subagent Sessions: the current title opens its siblings' tree. */ +import { useMemo, useEffect, useId, useRef, useState } from 'react' import { createPortal } from 'react-dom' -import { - type SessionProjectionMap, type SessionSummary, - type SessionProjectionSnapshot, -} from '@deepseek-ai/dsh-api-session-controller/client' -import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { - IconChevronRightOutlineRegular, IconRefreshOutlineRegular, IconUsersOutlineRegular, - IconCheckOutlineRegular, MenuSurface, StateDot, Tooltip, -} from '@deepseek-ai/dsh-client-ui-primitives' -import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { MenuSurface } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import { NS } from './locales.ts' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import type {} from '@deepseek-ai/dsh-token-meter/client' -import type {} from '@deepseek-ai/dsh-agent-team/client' -import type {} from './slots.ts' -import css from './SubagentHeaderLineage.module.css' +import { + CatalogTree, deriveCatalogs, entryName, levelPreparer, treeItems, type SubagentCatalogInjected, type SubagentCatalogSnapshot, +} from './SubagentCatalog.tsx' +import css from './SubagentCatalog.module.css' -type SubagentCatalogSnapshot = Omit & { - state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' - entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] -} -type Catalogs = Readonly> - -/** Business actions supplied by the slot registration. */ -export type SubagentCatalogInjected = { - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - /** Read this catalog and its direct children after explicit activation or retry. */ - prepareCatalog: (parentSessionId: SessionId) => Promise -} - -/** Root catalog actions and availability of its optional footer. */ -export type SubagentCatalogActionInjected = SubagentCatalogInjected & { - hooks: { - /** Whether the catalog footer currently has a registered contributor. */ - footerAvailable: HostObservable - } -} +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' /** Full props for the session-header lineage renderer. */ export type SubagentHeaderLineageProps = PropsRuntime<'conversation.session.header.lineage'> & InjectFace & PropsLocale -interface CatalogRowsProps { - parentSessionId: SessionId - currentSessionId: SessionId | undefined - catalog: SubagentCatalogSnapshot - catalogs: Catalogs - summaries: Readonly> - expanded: ReadonlySet - level: number - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - toggleBranch: (childSessionId: SessionId) => void - closeCatalog: () => void -} - -function treeItems(root: HTMLDivElement | null): HTMLElement[] { - return root === null - ? [] - : Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) -} - -/** Compact token count shared in shape with the conversation stats strip. */ -function formatTokens(value: number, t: TranslateNS): string { - const scaled = (next: number): string => next >= 100 - ? String(Math.round(next)) - : String(Math.round(next * 10) / 10) - if (value < 1_000) return String(value) - if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) - return t('tokens.million', { value: scaled(value / 1_000_000) }) -} - -/** Sum the four disjoint durable provider-usage buckets. */ -function tokenTotal( - usage: SessionProjectionMap['tokenUsage'] | undefined, -): number | undefined { - return usage === undefined - ? undefined - : usage.uncachedInputTokens + usage.outputTokens - + usage.cacheReadTokens + usage.cacheWriteTokens -} - -/** Exact whole-second active-turn duration for one catalog row. */ -function activityDuration( - summary: SessionSummary | undefined, - activity: 'running' | 'inactive', - now: number, -): number | undefined { - if (summary === undefined) return undefined - const timing: SessionProjectionMap['subagentTiming'] | undefined - = summary.projectionValues?.subagentTiming - if (timing === undefined) return undefined - if (timing.active === undefined) return timing.settledMs - const end = activity === 'running' - ? now - : timing.active.through - return timing.settledMs + Math.max(0, end - timing.active.since) -} - -interface DurationParts { - seconds: number - minutes: number - hours: number - days: number - totalMinutes: number - totalHours: number -} - -function splitDuration(ms: number): DurationParts { - const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) - const totalMinutes = Math.floor(totalSeconds / 60) - const totalHours = Math.floor(totalMinutes / 60) - return { - seconds: totalSeconds % 60, - minutes: totalMinutes % 60, - hours: totalHours % 24, - days: Math.floor(totalHours / 24), - totalMinutes, - totalHours, - } -} - -/** Format a duration with decreasing visual precision at larger scales. */ -function formatDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) - if (days >= 365) { - const years = Math.floor(days / 365) - const months = Math.floor((days % 365) / 30) - return months === 0 - ? t('duration.years', { years }) - : t('duration.yearsMonths', { years, months }) - } - if (days >= 30) { - const months = Math.floor(days / 30) - const remainingDays = days % 30 - return remainingDays === 0 - ? t('duration.months', { months }) - : t('duration.monthsDays', { months, days: remainingDays }) - } - if (days > 0) { - return hours === 0 - ? t('duration.days', { days }) - : t('duration.daysHours', { days, hours }) - } - if (totalHours > 0) { - return t('duration.hours', { - hours: totalHours, - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) - } - if (totalMinutes > 0) { - return t('duration.minutes', { - minutes: totalMinutes, - seconds: String(seconds).padStart(2, '0'), - }) - } - return t('duration.seconds', { seconds }) -} - -/** Preserve exact whole seconds for hover and accessible naming. */ -function formatExactDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days } = splitDuration(ms) - return days === 0 - ? formatDuration(ms, t) - : t('duration.exactDays', { - days, - hours: String(hours).padStart(2, '0'), - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) -} - function SubagentSwitcherIcon() { return ( }) { - return
    {t('loading.label')}
    -} -/** Only confirmed child membership exposes a branch disclosure. */ -function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { - return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 - && summaries[entry.id]?.formatStatus !== 'migration-required' - && catalogs[entry.id]?.state !== 'migration-required' -} - -/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ -function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { - return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id -} - -/** Only a local child's last closed, normally completed turn receives the completed marker. */ -function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { - return entry.mode !== 'external' && entry.activity === 'inactive' - && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true -} - -/** Count direct catalog members without treating external or other inactive entries as completed. */ -function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { - let completed = 0 - let active = 0 - let inactive = 0 - let external = 0 - for (const entry of entries) { - if (entry.mode === 'external') external++ - else if (entry.activity === 'running') active++ - else if (completedEntry(entry, summaries[entry.id])) completed++ - else inactive++ - } - return [ - ...completed > 0 ? [t('progress.completed', { count: completed })] : [], - ...active > 0 ? [t('progress.active', { count: active })] : [], - ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], - ...external > 0 ? [t('progress.external', { count: external })] : [], - ].join('\u2002·\u2002') -} - -/** Render one catalog level and recurse only through explicitly expanded rows. */ -function CatalogRows({ - parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, - openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, t, -}: CatalogRowsProps & { t: TranslateNS }) { - const [now, setNow] = useState(() => Date.now()) - const running = catalog.entries.some(entry => entry.activity === 'running') - useEffect(() => { - if (!running) return - const timer = setInterval(() => { setNow(Date.now()) }, 1_000) - return () => { clearInterval(timer) } - }, [running]) - const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 - const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) - return ( - <> - {catalog.state === 'idle' && catalog.entries.length === 0 && ( -
    {t('load.idle')}
    - )} - {emptyLoading && ( - - )} - {catalog.state === 'error' && ( -
    - {catalog.error?.message ?? t('load.error')} - -
    - )} - {catalog.entries.map((entry) => { - const external = entry.mode === 'external' - const childCatalog = catalogs[entry.id] - const isCurrent = entry.id === currentSessionId - const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' - || childCatalog?.state === 'migration-required' - const canExpand = canExpandCatalog(entry, catalogs, summaries) - const isExpanded = canExpand && expanded.has(entry.id) - const summary = summaries[entry.id] - const description = entry.label || summary?.title - const name = entryName(entry) - const primaryLabel = description || name - const secondaryLabel = description ? name : undefined - const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') - : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') - const completed = completedEntry(entry, summary) - const activity = external ? undefined : entry.activity === 'running' - ? t('activity.running') - : completed - ? t('activity.completed') - : t('activity.inactive') - const secondary = [secondaryLabel, mode, activity] - .filter(value => value !== undefined) - .join(' · ') - const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) - const durationMs = activityDuration( - summary, - entry.activity, - now, - ) - const tokenMetric = totalTokens === undefined - ? undefined - : t('tokens.total', { value: formatTokens(totalTokens, t) }) - const durationMetric = durationMs === undefined - ? undefined - : { - compact: formatDuration(durationMs, t), - exact: formatExactDuration(durationMs, t), - } - const metrics = [tokenMetric, durationMetric?.exact] - .filter(value => value !== undefined) - .join(' · ') - - const open = (): void => { - if (external) return - openChild({ - parentSessionId, - childSessionId: entry.id, - mode: entry.mode, - }) - closeCatalog() - } - const handleKey = (event: KeyboardEvent): void => { - if (event.key === 'Enter' || event.key === ' ') { - event.preventDefault() - event.stopPropagation() - open() - } else if ( - (event.key === 'ArrowRight' && canExpand && !isExpanded) - || (event.key === 'ArrowLeft' && isExpanded) - ) { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - } - const toggle = (event: MouseEvent): void => { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - - return ( -
    -
    value !== '').join(' ')} - {...canExpand ? { 'aria-expanded': isExpanded } : {}} - className={css.row} - onClick={open} - onKeyDown={handleKey} - > - {!canExpand - ? reserveDisclosure && - : ( - - )} -
    - - - - - {primaryLabel} - {secondaryLabel !== undefined && ( - {secondaryLabel} - )} - - {metrics !== '' && ( - - {tokenMetric !== undefined && {tokenMetric}} - {durationMetric !== undefined && ( - - {durationMetric.compact} - - )} - - )} - {isCurrent - ? ( - - - - ) - : external ? : ( - - - - )} -
    -
    - {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( -
    - {t('load.error')} - -
    - )} - {childCatalog !== undefined && isExpanded && ( -
    - -
    - )} -
    - ) - })} - - ) -} - -interface CatalogDropdownSharedProps extends InjectFace { - /** Session whose direct catalog roots the tree. */ +interface SwitcherProps extends InjectFace { + /** Parent Session whose direct catalog roots the tree. */ rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId: SessionId + /** Visible title included in the switcher's hover target. */ + displayTitle: string + /** Optional ancestor navigation when the combined title is clicked. */ + openTitle?: () => void useSessions: SubagentHeaderLineageProps['useSessions'] useSessionStatus: SubagentHeaderLineageProps['useSessionStatus'] t: TranslateNS - /** Section labels are useful only beside a visible shared-task list. */ - hasSharedTasks?: boolean - /** Retain an empty catalog's entry for shared tasks or a task-board error. */ - hasBoardContent?: boolean - renderFooter?: () => ReactNode } -type CatalogDropdownProps = CatalogDropdownSharedProps & ( - | { - /** Descendant-count control. */ - variant: 'count' - currentSessionId?: never - displayTitle?: never - openTitle?: never - } - | { - /** Current-title sibling switcher. */ - variant: 'switcher' - /** Selected descendant highlighted in the catalog. */ - currentSessionId: SessionId - /** Visible title included in the switcher's hover target. */ - displayTitle: string - /** Optional ancestor navigation when the combined title is clicked. */ - openTitle?: () => void - } -) - -/** One trigger-plus-tree dropdown over the catalog rooted at `rootSessionId`. */ -function CatalogDropdown(props: CatalogDropdownProps) { - const { - rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, hasSharedTasks = false, - } = props - const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined +/** + * Title-and-chevron dropdown over the parent's subagent tree. Hover opens it + * after 150ms and leaving both surfaces closes it after 120ms; a click pins it + * until an outside press or Escape. With `openTitle`, a click navigates to the + * ancestor instead. Hovering reads nothing; a pinning click or ArrowDown + * prepares the parent's level. + * @param props - tree root, current Session, title, Session hooks, actions, and copy. + * @returns the switcher. + */ +function Switcher({ + rootSessionId, currentSessionId, displayTitle, openTitle, + useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, +}: SwitcherProps) { const projections = useSessions(state => state.projectionsBySession) const summaries = useSessions(state => state.byId) const statuses = useSessionStatus(value => value) - const catalogs = useMemo(() => { - return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { - const projected = snapshot.values.subagentCatalog - const state = snapshot.state === 'idle' - ? projected === undefined ? 'idle' : 'ready' - : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state - return [id, { - state, - error: snapshot.error, - entries: (projected ?? []).map(entry => ({ - ...entry, - activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true - ? 'running' as const : 'inactive' as const, - })), - } satisfies SubagentCatalogSnapshot] - })) - }, [projections, summaries, statuses]) - const catalog = catalogs[rootSessionId] - const prepareLevel = (sessionId: SessionId): void => { - void prepareCatalog(sessionId).catch((error: unknown) => { - console.error('[ui-subagent] catalog discovery failed:', error) - }) - } - const [open, setOpen] = useState(false) - const [expanded, setExpanded] = useState>(() => new Set()) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + const catalog: SubagentCatalogSnapshot = catalogs[rootSessionId] ?? { entries: [], state: 'idle', error: null } + const prepareLevel = levelPreparer(prepareCatalog) + const [open, setOpen] = useState<'closed' | 'hover' | 'pinned' | 'keyboard'>('closed') const rootRef = useRef(null) const triggerRef = useRef(null) - const countRef = useRef(null) - const activityId = useId() const menuRef = useRef(null) - const anchorName = `--dsh-subagents-${activityId.replaceAll(':', '')}` - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - // A click-opened (pinned) menu ignores hover-out; only explicit dismissal closes it. - const pinnedRef = useRef(false) - const currentEntry = currentSessionId === undefined - ? undefined - : catalog?.entries.find(entry => entry.id === currentSessionId) - const switcherDisplayTitle = currentEntry !== undefined - ? currentEntry.label || entryName(currentEntry) - : displayTitle - const directChildren = catalog?.entries ?? [] - const directCount = directChildren.length - const runningCount = directChildren.filter(entry => entry.activity === 'running').length - const progress = catalogProgress(directChildren, summaries, t) - const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other' - const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other' - const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent - ? { entries: [], state: 'idle', error: null } - : undefined) + const anchorName = `--dsh-subagents-${useId().replaceAll(':', '')}` + const hoverTimer = useRef | undefined>(undefined) + const currentEntry = catalog.entries.find(entry => entry.id === currentSessionId) + const title = currentEntry !== undefined ? currentEntry.label || entryName(currentEntry) : displayTitle + const shown = open !== 'closed' - const cancelHoverClose = (): void => { - if (hoverCloseTimer.current === undefined) return - clearTimeout(hoverCloseTimer.current) - hoverCloseTimer.current = undefined + const cancelHover = (): void => { + clearTimeout(hoverTimer.current) + hoverTimer.current = undefined } - - const cancelHoverOpen = (): void => { - if (hoverOpenTimer.current === undefined) return - clearTimeout(hoverOpenTimer.current) - hoverOpenTimer.current = undefined - } - - const changeOpen = (next: boolean, restoreFocus = false): void => { - cancelHoverOpen() - cancelHoverClose() - if (next) { - const trigger = triggerRef.current - /* v8 ignore next -- a queued callback can outlive the trigger */ - if (trigger === null) return - setOpen(true) - } - else { - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - } + const close = (restoreFocus = false): void => { + cancelHover() + setOpen('closed') if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } - // CSS owns the header-width breakpoint; interaction reads its result only when scheduling hover. - const allowsHoverOpen = (): boolean => variant === 'switcher' - || (countRef.current !== null && getComputedStyle(countRef.current).display !== 'none') - - const scheduleHoverOpen = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (allowsHoverOpen()) changeOpen(true) - }, 150) - } - - const scheduleHoverClose = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (pinnedRef.current) return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - changeOpen(false) - }, 120) - } - - const closeBranch = (root: SessionId): void => { - const closing = new Set() - const visit = (parentSessionId: SessionId): void => { - if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return - closing.add(parentSessionId) - const branch = catalogs[parentSessionId] - for (const entry of branch?.entries ?? []) { - visit(entry.id) - } - } - visit(root) - setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) - } - - const toggleBranch = (childSessionId: SessionId): void => { - if (expanded.has(childSessionId)) { - closeBranch(childSessionId) - return - } - setExpanded(current => new Set(current).add(childSessionId)) - prepareLevel(childSessionId) - } - useEffect(() => { - if (!open) return + if (!shown) return const closeOutside = (event: PointerEvent): void => { - if ( - event.target instanceof Node - && !rootRef.current?.contains(event.target) - && !menuRef.current?.contains(event.target) - ) { - changeOpen(false) - } + if (event.target instanceof Node && !rootRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close() } - document.addEventListener('pointerdown', closeOutside) const dismiss = (event: globalThis.KeyboardEvent): void => { if (event.key !== 'Escape') return event.preventDefault() - changeOpen(false, menuRef.current?.contains(document.activeElement) === true) + close(menuRef.current?.contains(document.activeElement) === true) } + document.addEventListener('pointerdown', closeOutside) document.addEventListener('keydown', dismiss) return () => { document.removeEventListener('pointerdown', closeOutside) document.removeEventListener('keydown', dismiss) } - }, [open]) + }, [shown]) + useEffect(() => cancelHover, []) - useEffect(() => () => { - cancelHoverOpen() - cancelHoverClose() - }, []) - - const visible = presentedCatalog !== undefined - && (variant === 'switcher' - || props.hasBoardContent || presentedCatalog.state === 'error' - || presentedCatalog.entries.length > 0) - useEffect(() => { - if (visible) return - cancelHoverOpen() - cancelHoverClose() - if (!open) return - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - }, [visible, open]) - - if (!visible) return null - - const focusAt = (index: number): void => { - const items = treeItems(menuRef.current) - if (items.length === 0) return - items[(index + items.length) % items.length]?.focus() + const hoverIn = (pointerType: string): void => { + if (pointerType === 'touch') return + cancelHover() + if (shown) return + hoverTimer.current = setTimeout(() => { setOpen('hover') }, 150) } - - const navigate = (event: KeyboardEvent): void => { - if (event.target instanceof Element - && event.target !== triggerRef.current && event.target !== menuRef.current - && event.target.closest('[role="tree"]') === null) return - const items = treeItems(menuRef.current) - const index = items.indexOf(document.activeElement as HTMLElement) - if (event.key === 'Home') { - event.preventDefault() - focusAt(0) - } else if (event.key === 'End') { - event.preventDefault() - focusAt(items.length - 1) - } else if (event.key === 'ArrowDown') { - event.preventDefault() - focusAt(index + 1) - } else if (event.key === 'ArrowUp') { - event.preventDefault() - focusAt(index < 0 ? items.length - 1 : index - 1) - } + const hoverOut = (): void => { + cancelHover() + if (open !== 'hover') return + hoverTimer.current = setTimeout(() => { setOpen('closed') }, 120) } return ( -
    - + - - {variant === 'count' && runningCount > 0 && ( - - )} - {open && createPortal(( + {title} + + + {shown && createPortal(( { - if (event.pointerType !== 'touch') cancelHoverClose() + onKeyDown={(event) => { + // A pinned menu takes focus itself; the tree handles keys once a row has focus. + if (event.target !== event.currentTarget) return + const items = treeItems(event.currentTarget) + const row = event.key === 'ArrowDown' || event.key === 'Home' ? items[0] + : event.key === 'ArrowUp' || event.key === 'End' ? items.at(-1) : undefined + if (row === undefined) return + event.preventDefault() + row.focus() }} - onPointerLeave={scheduleHoverClose} + onPointerEnter={(event) => { if (event.pointerType !== 'touch') cancelHover() }} + onPointerLeave={hoverOut} >
    - {hasSharedTasks && ( -
    - -

    {t('section.title')}

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

    {t('section.empty')}

    - )} -
    - { changeOpen(false) }} - t={t} - /> -
    - {props.renderFooter?.()} + { close() }} + focusFirst={open === 'keyboard'} + t={t} + />
    ), document.body)} @@ -829,56 +206,9 @@ function CatalogDropdown(props: CatalogDropdownProps) { ) } -/** Full props for the root-session catalog entry in the header actions band. */ -export type SubagentCatalogActionProps = - PropsRuntime<'conversation.session.header.actions'> & InjectFace & PropsLocale - & Omit, 'SessionProvider'> - /** - * Session-header catalog action for root sessions: the descendant count and - * its dropdown after the preset label in the header actions band. Child sessions render nothing - * here — their breadcrumb switcher in the lineage slot owns the same - * navigation. - * @param props - Session standard props plus the catalog actions and translator. - * @returns The count dropdown, or null on a child session. - */ -export function SubagentCatalogAction(props: SubagentCatalogActionProps) { - const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) - const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') - if (addressedChild || listedChild) return null - return -} - -/** Bind task-board visibility only in root conversations. */ -function RootCatalogAction({ - sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable, - openChild, openChildAside, refreshProjection, prepareCatalog, t, renderSlot, -}: SubagentCatalogActionProps) { - const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true - && team.tasks.some(task => task.status !== 'deleted')) - const hasTaskFailure = useProjection('agentTeam', team => team?.enabled === true && team.failure !== undefined) - const footerAvailable = useFooterAvailable(value => value) - return ( - renderSlot('conversation.session.header.actions.subagent.footer', {})} - useSessions={useSessions} - useSessionStatus={useSessionStatus} - openChild={openChild} - openChildAside={openChildAside} - refreshProjection={refreshProjection} - prepareCatalog={prepareCatalog} - t={t} - /> - ) -} - -/** - * Render one breadcrumb title together with its subagent navigation. + * Render one breadcrumb title together with its sibling switcher. The + * Session's own subagents are listed by the Session panel section. * @param props - Breadcrumb title, session standard props, and catalog actions. * @returns A title-and-chevron sibling switcher, or nothing on a root session. */ @@ -895,29 +225,21 @@ export function SubagentHeaderLineage({ const summary = state.byId[lineageSessionId] return summary?.origin === 'subagent' ? summary.parentId : undefined }) - const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t } - // Root sessions carry no breadcrumb; their descendant count lives in the - // header actions band (SubagentCatalogAction). if (parentId === undefined) return null return ( - <> - - {openTitle === undefined && ( - - )} - + ) } diff --git a/packages/client/ui-subagent/src/client/SubagentsSection.tsx b/packages/client/ui-subagent/src/client/SubagentsSection.tsx new file mode 100644 index 0000000000..deb1492470 --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentsSection.tsx @@ -0,0 +1,170 @@ +/** Session panel section listing the current Session's subagents. */ +import { useCallback, useMemo } from 'react' +import { HoverCardGroup } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' +import { + CatalogTree, deriveCatalogs, levelPreparer, progressOf, type Catalogs, type SubagentCatalogInjected, type SubagentCatalogSnapshot, +} from './SubagentCatalog.tsx' +import type { createSubagentsSectionStore } from './subagents-store.ts' +import css from './SubagentCatalog.module.css' + +/** Full props of the subagents section. */ +export type SubagentsSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderFactories + & InjectFace + & PropsStore> + & PropsLocale + +/** Rows the list shows before its fold control holds the rest back. */ +const FOLD_LIMIT = 5 + +const NO_ENTRIES: SubagentCatalogSnapshot['entries'] = [] + +/** Full props of the section's progress title control. */ +export type SubagentsProgressProps = + PropsRuntime<'conversation.session.panel.section.actions'> & PropsLocale + +/** Full props of the running dot on the Session panel toggle. */ +export type SubagentsRunningIndicatorProps = + PropsRuntime<'conversation.session.panel.indicator'> & PropsLocale + +function deriveSummaries(state: Parameters[0]>[0]) { + return state.byId +} + +/** + * Read every held Session's catalog from the standard Session hooks. + * @param props - Session list and status hooks. + * @returns catalogs keyed by parent Session, and the Session list rows. + */ +function useCatalogs({ useSessions, useSessionStatus }: Pick): { + readonly catalogs: Catalogs + readonly summaries: ReturnType +} { + const projections = useSessions(state => state.projectionsBySession) + const summaries = useSessions(deriveSummaries) + const statuses = useSessionStatus(value => value) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + return { catalogs, summaries } +} + +/** + * Order the section's rows: running subagents first, the most recently started + * first, then the others, the most recently active first. A running subagent + * sorts by the start of its open turn and another one by its Session's last + * update. A subagent the Client holds neither for sorts by when its parent + * created it: its turn timing is not read yet, or its Session is not in the + * Host list, whose stand-in row carries no update time. Rows that tie keep + * their catalog order. + * @param entries - the Session's direct subagents in catalog order. + * @param summaries - Session list rows by id. + * @returns the entries in display order. + */ +function sectionOrder( + entries: SubagentCatalogSnapshot['entries'], summaries: ReturnType, +): SubagentCatalogSnapshot['entries'] { + return entries + .map((entry) => { + const summary = summaries[entry.id] + const running = entry.activity === 'running' + // A Session is last updated after it is created, so the later of the two is the update time when the Client has one. + const at = running + ? summary?.projectionValues?.subagentTiming?.active?.since ?? entry.createdAt + : Math.max(summary?.updatedAt ?? 0, entry.createdAt) + return { entry, running, at } + }) + .sort((left, right) => Number(right.running) - Number(left.running) || right.at - left.at) + .map(row => row.entry) +} + +/** + * Render the Session's subagent tree, running subagents first and then the + * most recently active ones. The list shows five rows and then a fold control + * that shows the rest, once that holds back two rows or more; the choice is + * kept per Session. The section renders nothing while the Session has no + * subagents and no failed catalog read. Showing it reads nothing: rows offer + * expansion from locally known catalogs, and expanding a branch or retrying a + * failed read prepares that level. Opening a subagent closes the panel's + * overlay. + * @param props - Session hooks, panel owner values, the fold store, catalog actions, and copy. + * @returns the section body, or null with nothing to show. + */ +export function SubagentsSection({ + sessionId, dismissOverlay, useSessions, useSessionStatus, useStore, actions, openChild, openChildAside, prepareCatalog, + renderFactorySlot, t, +}: SubagentsSectionProps) { + const { catalogs, summaries } = useCatalogs({ useSessions, useSessionStatus }) + const catalog = catalogs[sessionId] + const unfolded = useStore(state => state.unfolded) + const prepareLevel = useMemo(() => levelPreparer(prepareCatalog), [prepareCatalog]) + const panelDetails = useCallback( + (details: PanelDetailsProps) => renderFactorySlot('conversation.session.panel.details', details), [renderFactorySlot], + ) + const ordered = useMemo(() => catalog === undefined ? NO_ENTRIES : sectionOrder(catalog.entries, summaries), [catalog, summaries]) + // Folding holds back two rows or more, since the fold control takes a row itself. + const foldable = ordered.length > FOLD_LIMIT + 1 + const shown = useMemo( + () => catalog === undefined ? undefined : { ...catalog, entries: foldable && !unfolded ? ordered.slice(0, FOLD_LIMIT) : ordered }, + [catalog, ordered, foldable, unfolded], + ) + if (shown === undefined || (shown.state !== 'error' && ordered.length === 0)) return null + const label = unfolded ? t('list.less') : t('list.more', { count: ordered.length - FOLD_LIMIT }) + return ( +
    + {/* Moving between rows swaps their hover cards without another dwell. */} + + + + {foldable && renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded, + label, + name: t('list.foldName', { label }), + onToggle: () => { actions.unfoldedSet(!unfolded) }, + })} +
    + ) +} + +/** + * Render the direct subagents' progress beside the section title. + * @param props - Session hooks and copy. + * @returns the progress phrase, or null without subagents. + */ +export function SubagentsProgress({ sessionId, useSessions, useSessionStatus, t }: SubagentsProgressProps) { + const { catalogs, summaries } = useCatalogs({ useSessions, useSessionStatus }) + const catalog = catalogs[sessionId] + const progress = catalog === undefined ? '' : progressOf(catalog, summaries, t) + if (progress === '') return null + return {progress} +} + +/** + * Show on the panel toggle that direct subagents run while the panel does not + * show them. External tasks do not count, as in the section's progress. + * @param props - Session hooks, whether the panel shows, and copy. + * @returns the dot with its name for assistive technology, or null with nothing to report. + */ +export function SubagentsRunningIndicator({ sessionId, panelShown, useSessions, useSessionStatus, t }: SubagentsRunningIndicatorProps) { + const { catalogs } = useCatalogs({ useSessions, useSessionStatus }) + const running = catalogs[sessionId]?.entries.filter(entry => entry.mode !== 'external' && entry.activity === 'running').length ?? 0 + if (panelShown || running === 0) return null + return ( + + {t('indicator.running', { count: running })} + + ) +} diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index d6fe29b2d8..9ab568f2ba 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -3,7 +3,10 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { SubagentCatalogAction, SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected } from './SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from './SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +import { SubagentsProgress, SubagentsRunningIndicator, SubagentsSection } from './SubagentsSection.tsx' +import { createSubagentsSectionStore } from './subagents-store.ts' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' @@ -12,11 +15,11 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type SubagentKey } from './locales.ts' -export type * from './slots.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { @@ -25,16 +28,17 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { - SubagentCatalogActionProps, SubagentCatalogInjected, SubagentCatalogActionInjected, SubagentHeaderLineageProps, -} from './SubagentHeaderLineage.tsx' +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +export type { SubagentHeaderLineageProps } from './SubagentHeaderLineage.tsx' +export type { SubagentsProgressProps, SubagentsRunningIndicatorProps, SubagentsSectionProps } from './SubagentsSection.tsx' export type { SubagentReadOnlyComposerProps, SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' /** * Required services for subagent presentation and navigation. `uiSession.sessionStatus` provides the - * `useSessionStatus` hook the lineage header renders with, so the plugin unloads and reloads with it. + * `useSessionStatus` hook the lineage header and the Session panel entries render with, so the plugin unloads and + * reloads with it. */ export const inject = ['sessions', 'uiWorkspace', 'slots', 'locale', 'sidebarRight', 'uiSession.sessionStatus'] @@ -48,11 +52,13 @@ function selectReadOnlySubagent(owner: ComposerChainProps): SubagentReadOnlyMatc } /** - * Client plugin body: register the subagent catalog and read-only composer seats. + * Client plugin body: register the breadcrumb switcher, the Session panel + * subagents section, and the read-only composer. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-subagent: dictionaries') + const t = ctx.locale.bind(NS) ctx.inject(['resources', 'sidebarRightTabs'], (scope) => { registerSidebarChat(scope, ctx.locale.bind(NS)) }) @@ -83,10 +89,6 @@ export function apply(ctx: ClientContext): void { void ctx.sessions.refreshProjections(parentSessionId) }, }) - const footerAvailable = { - getSnapshot: () => ctx.slots.entries('conversation.session.header.actions.subagent.footer').length > 0, - subscribe: (listener: () => void) => ctx.slots.subscribe('conversation.session.header.actions.subagent.footer', listener), - } ctx.slots.inject( 'conversation.session.header.lineage', () => ctx.slots.register({ @@ -95,20 +97,30 @@ export function apply(ctx: ClientContext): void { inject: catalogActions, }, SubagentHeaderLineage), ) - ctx.slots.inject( - 'conversation.session.header.actions', - () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'subagent-catalog', - // Between the preset label (-10) and background tasks (20). - order: 10, + ctx.slots.inject('conversation.session.panel.section', function* () { + yield ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'subagents', + // After change requests (100), before shared tasks (250). + order: 200, + label: () => t('section.title'), locale: NS, - inject: (sessionId): SubagentCatalogActionInjected => ({ - ...catalogActions(sessionId), hooks: { footerAvailable }, - }), - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, - }, SubagentCatalogAction), - ) + store: createSubagentsSectionStore(), + inject: catalogActions, + }, SubagentsSection) + yield ctx.slots.register({ + name: 'conversation.session.panel.section.actions', + key: 'subagents', + locale: NS, + }, SubagentsProgress) + }) + ctx.slots.inject('conversation.session.panel.indicator', () => ctx.slots.register({ + name: 'conversation.session.panel.indicator', + id: 'subagents.running', + // Below an attention mark, which paints above running dots. + order: 10, + locale: NS, + }, SubagentsRunningIndicator)) ctx.slots.inject( 'conversation.composer', () => ctx.slots.register({ diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 83754edd6c..0e1c80e59b 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -6,11 +6,14 @@ export const NS = 'subagent' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { 'section.title': '子智能体', - 'section.empty': '暂无子智能体', + 'indicator.running': '{count} 个子智能体运行中', 'progress.completed': '{count} 已完成', 'progress.active': '{count} 进行中', 'progress.inactive': '{count} 未运行', 'progress.external': '{count} 外部任务', + 'list.more': '显示其余 {count} 个', + 'list.less': '收起', + 'list.foldName': '{label}(子智能体)', 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}小时{minutes}分{seconds}秒', @@ -21,10 +24,10 @@ export const zh = { 'duration.years': '约{years}年', 'duration.yearsMonths': '约{years}年{months}个月', 'duration.exactDays': '{days}天{hours}小时{minutes}分{seconds}秒', - 'duration.exactTitle': '总活跃耗时:{duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': '负责人:{name}', 'loading.label': '正在加载子智能体…', 'load.idle': '尚未加载子智能体', 'load.error': '无法加载子智能体', @@ -39,10 +42,6 @@ export const zh = { 'activity.inactive': '当前未运行', 'branch.collapse': '收起 {label} 的下级子智能体', 'branch.expand': '展开 {label} 的下级子智能体', - 'count.total.one': '{count} 个子智能体', - 'count.total.other': '{count} 个子智能体', - 'count.running.one': '{count} 个子智能体,正在运行', - 'count.running.other': '{count} 个子智能体,正在运行', 'switcher.aria': '切换子智能体:{title}', 'tree.aria': '子智能体会话', 'open.sidebar': '在侧边栏打开', @@ -57,11 +56,14 @@ export const zh = { /** English dictionary, key-identical to the Chinese source of truth. */ export const en: Record = { 'section.title': 'Subagents', - 'section.empty': 'No subagents', + 'indicator.running': 'Subagents running: {count}', 'progress.completed': '{count} completed', 'progress.active': '{count} in progress', 'progress.inactive': '{count} not running', 'progress.external': '{count} external', + 'list.more': 'Show {count} more', + 'list.less': 'Show less', + 'list.foldName': '{label} (subagents)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -72,10 +74,10 @@ export const en: Record = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Total active duration: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': 'Owner: {name}', 'loading.label': 'Loading subagents…', 'load.idle': 'Subagents not loaded', 'load.error': 'Unable to load subagents', @@ -90,10 +92,6 @@ export const en: Record = { 'activity.inactive': 'not running', 'branch.collapse': 'Collapse {label} descendants', 'branch.expand': 'Expand {label} descendants', - 'count.total.one': '{count} subagent', - 'count.total.other': '{count} subagents', - 'count.running.one': '{count} subagent running', - 'count.running.other': '{count} subagents running', 'switcher.aria': 'Switch subagent: {title}', 'tree.aria': 'Subagent sessions', 'open.sidebar': 'Open in sidebar', @@ -111,11 +109,14 @@ export type SubagentKey = keyof typeof zh /** Japanese copy, checked against the English keys. */ export const ja = { 'section.title': 'サブエージェント', - 'section.empty': 'サブエージェントはありません', + 'indicator.running': '実行中のサブエージェント: {count}', 'progress.completed': '{count}件完了', 'progress.active': '{count}件進行中', 'progress.inactive': '{count}件停止中', 'progress.external': '{count}件外部タスク', + 'list.more': '残り{count}件を表示', + 'list.less': '折りたたむ', + 'list.foldName': '{label}(サブエージェント)', 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}時間{minutes}分{seconds}秒', @@ -126,10 +127,10 @@ export const ja = { 'duration.years': '約{years}年', 'duration.yearsMonths': '約{years}年{months}ヶ月', 'duration.exactDays': '{days}日{hours}時間{minutes}分{seconds}秒', - 'duration.exactTitle': '合計アクティブ時間: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': '担当:{name}', 'loading.label': 'サブエージェントを読み込み中…', 'load.idle': 'サブエージェントは未読み込みです', 'load.error': 'サブエージェントを読み込めません', @@ -144,10 +145,6 @@ export const ja = { 'activity.inactive': '停止中', 'branch.collapse': '{label}の子孫を折りたたむ', 'branch.expand': '{label}の子孫を展開', - 'count.total.one': 'サブエージェント{count}件', - 'count.total.other': 'サブエージェント{count}件', - 'count.running.one': '実行中のサブエージェント{count}件', - 'count.running.other': '実行中のサブエージェント{count}件', 'switcher.aria': 'サブエージェントを切り替え: {title}', 'tree.aria': 'サブエージェントセッション', 'open.sidebar': 'サイドバーで開く', @@ -162,11 +159,14 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { 'section.title': 'Subagentes', - 'section.empty': 'No hay subagentes', + 'indicator.running': 'Subagentes en ejecución: {count}', 'progress.completed': '{count} completado', 'progress.active': '{count} en progreso', 'progress.inactive': '{count} sin ejecutar', 'progress.external': '{count} externos', + 'list.more': 'Mostrar {count} más', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (subagentes)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -177,10 +177,10 @@ export const es = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Duración total activa: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': 'Tok {value}', + 'hover.owner': 'Responsable: {name}', 'loading.label': 'Cargando subagentes…', 'load.idle': 'Subagentes sin cargar', 'load.error': 'No se pueden cargar subagentes', @@ -195,10 +195,6 @@ export const es = { 'activity.inactive': 'no corriendo', 'branch.collapse': 'Contraer descendientes de {label}', 'branch.expand': 'Ampliar descendientes de {label}', - 'count.total.one': 'Subagente {count}', - 'count.total.other': 'Subagentes {count}', - 'count.running.one': 'Subagente {count} ejecutándose', - 'count.running.other': 'Subagentes {count} ejecutándose', 'switcher.aria': 'Cambiar subagente: {title}', 'tree.aria': 'Sesiones de subagente', 'open.sidebar': 'Abrir en la barra lateral', @@ -213,11 +209,14 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { 'section.title': 'Sous-agents', - 'section.empty': 'Aucun sous-agent', + 'indicator.running': 'Sous-agents en cours : {count}', 'progress.completed': '{count} terminé', 'progress.active': '{count} en cours', 'progress.inactive': '{count} à l’arrêt', 'progress.external': '{count} externes', + 'list.more': 'Afficher {count} de plus', + 'list.less': 'Afficher moins', + 'list.foldName': '{label} (sous-agents)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -228,10 +227,10 @@ export const fr = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': "Durée totale d'activité : {duration}", 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': 'Jeton {value}', + 'hover.owner': 'Responsable : {name}', 'loading.label': 'Chargement des sous-agents…', 'load.idle': 'Sous-agents non chargés', 'load.error': 'Impossible de charger les sous-agents', @@ -246,10 +245,6 @@ export const fr = { 'activity.inactive': 'ne fonctionne pas', 'branch.collapse': 'Réduire les descendants de {label}', 'branch.expand': 'Développer les descendants de {label}', - 'count.total.one': 'Sous-agent {count}', - 'count.total.other': 'Sous-agents {count}', - 'count.running.one': "Sous-agent {count} en cours d'exécution", - 'count.running.other': "Sous-agents {count} en cours d'exécution", 'switcher.aria': 'Changer de sous-agent : {title}', 'tree.aria': 'Sessions de sous-agents', 'open.sidebar': 'Ouvrir dans la barre latérale', @@ -264,11 +259,14 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { 'section.title': 'Subagenten', - 'section.empty': 'Keine Subagenten', + 'indicator.running': 'Laufende Subagenten: {count}', 'progress.completed': '{count} abgeschlossen', 'progress.active': '{count} in Bearbeitung', 'progress.inactive': '{count} nicht aktiv', 'progress.external': '{count} extern', + 'list.more': '{count} weitere anzeigen', + 'list.less': 'Weniger anzeigen', + 'list.foldName': '{label} (Subagenten)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -279,10 +277,10 @@ export const de = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Gesamte aktive Dauer: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value}-Token', + 'hover.owner': 'Zuständig: {name}', 'loading.label': 'Subagenten werden geladen…', 'load.idle': 'Subagenten nicht geladen', 'load.error': 'Subagenten können nicht geladen werden', @@ -297,10 +295,6 @@ export const de = { 'activity.inactive': 'läuft nicht', 'branch.collapse': '{label}-Nachkommen reduzieren', 'branch.expand': 'Erweitern Sie {label}-Nachkommen', - 'count.total.one': '{count}-Subagent', - 'count.total.other': '{count}-Subagenten', - 'count.running.one': '{count}-Subagent läuft', - 'count.running.other': '{count} Subagenten laufen', 'switcher.aria': 'Subagent wechseln: {title}', 'tree.aria': 'Subagentensitzungen', 'open.sidebar': 'In der Seitenleiste öffnen', @@ -315,11 +309,14 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { 'section.title': 'Субагенты', - 'section.empty': 'Нет субагентов', + 'indicator.running': 'Выполняется субагентов: {count}', 'progress.completed': '{count} завершено', 'progress.active': '{count} в процессе', 'progress.inactive': '{count} не выполняются', 'progress.external': '{count} внешних', + 'list.more': 'Показать ещё {count}', + 'list.less': 'Свернуть', + 'list.foldName': '{label} (субагенты)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -330,10 +327,10 @@ export const ru = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Общая активная продолжительность: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} ток', + 'hover.owner': 'Ответственный: {name}', 'loading.label': 'Загрузка субагентов…', 'load.idle': 'Субагенты не загружены', 'load.error': 'Невозможно загрузить субагенты', @@ -348,10 +345,6 @@ export const ru = { 'activity.inactive': 'не работает', 'branch.collapse': 'Свернуть потомков {label}', 'branch.expand': 'Развернуть потомков {label}', - 'count.total.one': 'Субагент {count}', - 'count.total.other': 'Субагенты {count}', - 'count.running.one': 'Субагент {count} работает', - 'count.running.other': 'Субагенты {count} работают', 'switcher.aria': 'Переключить субагент: {title}', 'tree.aria': 'Сеансы субагента', 'open.sidebar': 'Открыть в боковой панели', @@ -366,11 +359,14 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { 'section.title': 'Subagentes', - 'section.empty': 'Nenhum subagente', + 'indicator.running': 'Subagentes em execução: {count}', 'progress.completed': '{count} concluído', 'progress.active': '{count} em andamento', 'progress.inactive': '{count} sem execução', 'progress.external': '{count} externos', + 'list.more': 'Mostrar mais {count}', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (subagentes)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -381,10 +377,10 @@ export const pt = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}a {months}mês', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Duração total ativa: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} valor', + 'hover.owner': 'Responsável: {name}', 'loading.label': 'Carregando subagentes…', 'load.idle': 'Subagentes não carregados', 'load.error': 'Não foi possível carregar subagentes', @@ -399,10 +395,6 @@ export const pt = { 'activity.inactive': 'não está funcionando', 'branch.collapse': 'Recolher {label} descendentes', 'branch.expand': 'Expandir {label} descendentes', - 'count.total.one': '{count} subagente', - 'count.total.other': '{count} subagentes', - 'count.running.one': '{count} subagente em execução', - 'count.running.other': '{count} subagentes em execução', 'switcher.aria': 'Alternar subagente: {title}', 'tree.aria': 'Sessões de subagente', 'open.sidebar': 'Abrir na barra lateral', diff --git a/packages/client/ui-subagent/src/client/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(<>