feat(client): compose session row actions from slot lists

A Session row's "..." menu and its hover buttons become two list slots the
WorkspaceBrowser entry declares, `sidebar.workspaces.session.menu.item` and
`sidebar.workspaces.session.row.action`. The shipped actions register from
apply the way a client plugin does: pin (menu 100, button 200), rename (200),
fork (300), archive (menu 400, button 100). An entry receives only the row
identity, reads the pin and archive sets through Set hooks its own face
injects, decides its own visibility, renders `MenuItemButton` or one icon
button, and dismisses the menu through the slot-level `useMenuOpenState`
hook bound from the row's render occurrence.

Each action's behavior lives in its injected callbacks. `UiWorkspace` gains
`pinSession` and `unpinSession`; the pin write into the saved orders happens
there, through the viewing-store instance the apply creates and hands the
browser's registration as its handle (the ui-layout pattern), reading the
memberships current at completion. The rename dialog and the row-action
notice are `shell.overlay` entries fed by apply-closure observables through
the faces' `hooks`; the archived notice switches the archived filter
directly. WorkspaceBrowser threads no action callbacks, renders no toast,
and hosts no rename dialog; its title double-click raises the same rename
request.

In ui-primitives, `MenuItemButton` is the plain `role="menuitem"` row for
menus whose rows are components: it shares a data row's markup and styling
and needs no shared state, because `Menu` decides the keyboard walk from the
DOM and now runs the post-selection focus return once on the list's click
bubble for every row kind. `Menu` accepts such rows as `children` beside
`items`, which becomes optional together with `onSelect`; `separatorBefore`
lets a row start a group with the same hairline a separator entry draws. The
context-based `MenuAction` goes away with its extension group.
This commit is contained in:
imccyu committed 2026-09-20 12:20:24 +08:00
1 parent 5ca9b77c44
commit 21586fe28c
36 files changed
+2178 -1033

No files matched your search

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md
2026-09-17-session-row-menu-actions-slot.md: 21f17505a5e24c68b6b96a1eee34dbf76d9aa40f
2026-09-17-session-row-menu-actions-slot.zh.md: ae30d88dc8c2fb2b34ca2dc06fdb1eb5bb6c9f43
2026-09-17-session-row-menu-actions-slot.md: 936e0f2163d888102fdb6c083c57e6ba6e549714
2026-09-17-session-row-menu-actions-slot.zh.md: 906395fa9d5850260c042202c787cd9a4bc8b55b
@@ -1,4 +1,4 @@
# Agent Note: Session row menu action slot
# Agent Note: Session row actions as slot lists
Status: implemented
@@ -6,30 +6,30 @@ English | [中文](2026-09-17-session-row-menu-actions-slot.zh.md)
## Problem
The Session row menu was a closed list of actions owned by `ui-workspace`. A third-party client plugin could add a separate sidebar control, but it could not place an action beside Rename, Fork, and Archive without changing the owning package or copying the menu interaction.
The Session row's "..." menu and its hover buttons were closed lists owned by `ui-workspace`: the browser built the menu `items` by row state, rendered the pin and archive buttons itself, and dispatched every verb through callbacks it threaded down the tree, together with the toast and rename dialog those verbs needed. A client plugin could add a sidebar control of its own, but not an action beside the shipped ones without editing the owning package or copying the menu interaction.
## Decision
`ui-workspace` declares the root-scoped ordered-list slot `sidebar.workspaces.session.menu.action` under its `sidebar.workspaces` registration. Each contribution receives the target `sessionId` and row `displayTitle` (persisted title, project basename, then Session id); the contributing plugin keeps its services and mutations in its own registration closure.
`ui-workspace` declares two root-scoped `list` slots under its `sidebar.workspaces` registration — `sidebar.workspaces.session.menu.item` for the menu rows and `sidebar.workspaces.session.row.action` for the hover buttons — and registers its own actions into them from `apply` exactly as a client plugin would: `pin` (menu 100, button 200), `rename` (200), `fork` (300), `archive` (menu 400, button 100). The lists are the menu and the button strip: entries render in ascending `order`, a plugin action lands wherever its order says, and reusing a shipped id at another `priority` shadows that action through the registry's ordinary cell rules. There is no separate "extension group" and no separator.
The shared `MenuAction` primitive renders every contributed row inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Dynamic client bundles resolve `ui-primitives` directly from the host's implicit baseline through their loader `require`; they do not declare a runtime dependency or carry a second component protocol.
An entry receives only the row identity, `{ sessionId, displayTitle }`, and owns everything else. It reads the Host state it cares about through the standard hooks (`useWorkspaces` for the pin and archive sets) and decides its own visibility from it: pin renders nothing on an archived row because the Host keeps the two sets exclusive; archive never consults pin. Its whole behavior lives in its registration's `inject` face, so a component only calls one callback: `pinSession` delegates to `uiWorkspace.pinSession`, which performs the Host pin and then fronts the Session in its accounts' saved orders with `pinSessionOrder`, reading the memberships current at completion from the object-layer snapshots (`pin-order.ts`), beside `archiveSession`, which the same service already owned; the archive action's callback adds the notice. The service writes view order through the viewing-store instance the apply creates and hands the browser's registration as its handle, the pattern `ui-layout` uses for its layout store. The registry-global pin and archive sets reach the entries as Sets through the faces' `hooks`, derived once per Workspace snapshot, so a row reads its own membership with one lookup.
### Ordering and disclosure
The surfaces an action raises outlive the row menu, so they are this package's `shell.overlay` entries: the rename dialog and the row-action notice. An action reaches its surface through the plugin's own apply-closure observable, injected as a callback on the action side (`requestSessionRename`, `notify`) and as a `hooks` source on the surface side (`useRenameRequest`, `useToast`). The browser raises the same rename request from a title double-click and the same notice when an archived row is clicked; the archived notice's second action switches the archived filter to "show" through the same store instance, since the browser's view-options menu is no longer in the loop.
Rename, Fork, and Archive remain a fixed owner-defined group at the top. Contributions form a semantically separated group below them and follow list-slot ordering: lower `order` first, then the live ledger order. Equal-order packaged registrations keep registration sequence; equal-order dynamic registrations use the facade's decreasing shadowing priority, so the newer entry comes first. Priority otherwise selects the active registration inside one reused-id cell and does not override order across distinct ids. The group is visually and accessibly hidden when empty. The existing ellipsis menu remains the only disclosure layer; nested “More…” grouping is not part of the contract.
## Verification
Primitive tests cover selection, dismissal, focus restoration, submenu reset, the semantic separator, and keyboard order. Row tests cover owner props and built-in-before-plugin placement. The assembled Slot runtime test verifies that order remains primary across different priorities. A real Loader/Web scenario installs a dynamic package, opens a seeded Session menu in Chromium, snapshots the assembled menu, selects an action, and verifies dismissal, owner data, and fiber-lifetime cleanup.
Menu entries render `MenuItemButton`, the `ui-primitives` row component for menus whose rows are components: a plain row, markup and styling only. It joins the menu's keyboard walk and the focus return because `Menu` decides both from the DOM (the arrow walk queries the rows; the post-selection focus return runs once on the list's click bubble, for data rows and component rows alike). Closing is the owner's state for both kinds of row: data rows through the owner's `onSelect`, component rows through the slot-level `useMenuOpenState` hook — the declaration carries `inject: { hooks: { menuOpenState } }`, `SessionNodeItem` passes its `[open, setOpen]` pair as the occurrence's `hookContext`, and the factory hands the pair back. That is the channel `sidebar.right.pane.tab` already uses for `useTabInfo`.
## Alternatives considered
**Pass menu descriptors through the slot owner props.** This makes a render slot behave like a second data registry, exposes presentation policy through callbacks, and prevents ordinary slot components from owning their injected services.
**A React context between `Menu` and the row component.** Rejected: business components see zero React contexts ([client rules](../../../../packages/client/AGENTS.md)); the Menu-to-row relationship is parent-to-child through the slot system, so its control travels through the slot channels.
**Expose raw menu markup.** That would let plugins drift from the menu's accessibility, focus, and visual behavior. Requiring the shared `MenuAction` keeps one interaction contract for packaged and dynamically loaded contributions.
**Owner-supplied row capabilities.** Passing `pinned`/`archived` and `pin`/`archive`/`rename`/`fork` callbacks to entries, through owner props or a slot-level hook, keeps the browser the owner of every verb and makes the shipped actions thin wrappers over it. Rejected: these are not capabilities of a menu; each action's behavior is that action's own, and an entry can read the Host state it needs directly.
**Add primary and “More…” slots immediately.** Session actions are already behind the row's ellipsis, and no current action set needs another disclosure level. A second hierarchy would add labeling and keyboard policy before a demonstrated density problem exists.
**A dedicated slot appended below the shipped rows.** Rejected: it makes the shipped rows a privileged group a plugin can only follow, and it needs a second rendering path in the primitive for what is one ordered list.
**Entries that compute their own view-order writes.** A pin entry subscribing to the whole Session list and Workspace snapshot to assemble `pinSessionOrder`'s inputs re-renders every visible row on every list change and puts ordering detail into a menu row. Rejected: the injected callback owns the write and reads the snapshots once, at completion.
**Declared shared stores for the rename request and the notice.** The request and the notice are one plugin's transient facts, so they travel as apply-closure observables through the entries' own inject faces.
## Consequences
Plugins can add Session actions without editing `ui-workspace`, while core actions keep a stable position and external conflicts use the slot registry's existing id and priority rules. Every contribution uses the shared `MenuAction`. All plugin actions remain in the secondary row menu until observed scale justifies a new hierarchy.
Plugins add, reorder, or shadow Session row actions in the menu and in the hover strip without editing `ui-workspace`, and the shipped actions follow the same rules and the same registration path. `WorkspaceBrowser` no longer threads action callbacks, renders a toast, or hosts the rename dialog; `Menu` grew `children` and made `items`/`onSelect` optional; `shell.overlay` gained two `ui-workspace` entries. The archived notice applies the "show archived" filter directly instead of opening the view-options menu.
@@ -1,4 +1,4 @@
# Agent Note: Session 行菜单 action slot
# Agent Note: Session 行 action 即 slot 列表
Status: implemented
@@ -6,30 +6,30 @@ Status: implemented
## 问题
Session 行菜单原本是由 `ui-workspace` 持有的封闭 action 列表。第三方客户端插件可以添加独立的侧边栏控件,却无法在不修改 owner 包或复制菜单交互的情况下,把 action 放到 Rename、Fork 与 Archive 旁边。
Session 行的 "..." 菜单和行尾悬停按钮原本是 `ui-workspace` 持有的封闭列表:browser 按行状态拼菜单 `items`、自己渲染置顶和归档按钮、把每个动作的回调一路传下去,连这些动作需要的 toast 和重命名对话框也由它持有。客户端插件可以自己添加侧边栏控件,却无法在不修改 owner 包或复制菜单交互的情况下把 action 放到内置项旁边。
## 决策
`ui-workspace` 在其 `sidebar.workspaces` 注册项下声明 root-scoped 有序列表 slot `sidebar.workspaces.session.menu.action`。每个贡献项接收目标 `sessionId` 与行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id);贡献插件将自身服务与 mutation 保留在自己的注册闭包中。
`ui-workspace` 在其 `sidebar.workspaces` 注册项下声明两个 root-scoped `list` slot——菜单行用 `sidebar.workspaces.session.menu.item`,悬停按钮用 `sidebar.workspaces.session.row.action`——并在 `apply` 里以客户端插件的同一方式注册自己的 action:`pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100)。列表就是菜单和按钮条:条目按 `order` 升序渲染,插件 action 落在其 order 所指的位置,以另一个 `priority` 复用内置 id 则按注册表的普通 cell 规则遮蔽。没有单独的"扩展分组",也没有分隔线。
共享 `MenuAction` primitive 在 `Menu` 内渲染所有贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。动态客户端 bundle 直接通过 loader 的 `require` 从宿主隐式 baseline 解析 `ui-primitives`;它们不声明运行时依赖,也不携带第二套组件协议。
条目只接收行身份 `{ sessionId, displayTitle }`,其余一切自己负责。它用标准 hook 读自己关心的 Host 状态(置顶与归档集合来自 `useWorkspaces`),并据此决定是否显示:Host 规定两个集合互斥,所以 pin 在归档行上不渲染;archive 从不参考 pin。整套行为放在注册项自己的 `inject` face 里,组件只调一个回调:`pinSession` 委托给 `uiWorkspace.pinSession`——先做 Host 置顶,成功后用 `pinSessionOrder` 把会话推到其记账保存顺序的最前,成员关系在完成时刻从对象层快照读取(`pin-order.ts`)——和这个服务原本就持有的 `archiveSession` 并列;归档 action 的回调在此之上加上提示。服务经 apply 自己创建、并作为 handle 交给 browser 注册项的那个 viewing store 实例写入视图顺序,与 `ui-layout` 处理 layout store 的方式相同。置顶与归档集合以 Set 形式经 face 的 `hooks` 到达条目,每次 Workspace 快照变化只重建一次,行读自己那一位只需一次查找。
### 排序与渐进披露
action 发起的浮层必须活得比行菜单久,所以它们是本包注册在 `shell.overlay` 的条目:重命名对话框和行 action 提示。action 经本插件 apply 闭包里的观察源到达自己的浮层:action 一侧注入为回调(`requestSessionRename`、`notify`),浮层一侧注入为 `hooks` 源(`useRenameRequest`、`useToast`)。browser 在标题双击时发出同一个重命名请求,在点击归档行时发出同一种提示;归档提示的第二个动作经同一个 store 实例把归档筛选切到"显示",因为 browser 的视图选项菜单已不在链路上。
Rename、Fork 与 Archive 作为固定的 owner-defined 分组保持在顶部。贡献项在下方形成带语义分隔的分组,并遵循 list slot 排序:先按较小的 `order`,再按 live ledger 顺序。`order` 相同的打包注册保持注册顺序;动态注册使用 facade 分配的递减 shadowing priority,因此较新的注册在前。除此之外,priority 只在一个复用 id 的 cell 内选择活动注册,不会让不同 id 跨越 order。空分组在视觉与无障碍 API 中均隐藏。现有省略号菜单仍是唯一的渐进披露层;嵌套「More…」分组不属于此约定。
## 验证
Primitive 测试覆盖选择、关闭、焦点恢复、子菜单重置、语义分隔线与键盘顺序。行测试覆盖 owner props 与内置 action 优先于插件 action 的位置。组装后的 Slot 运行时测试验证不同 priority 下仍以 order 为主。真实 Loader/Web 场景安装动态包,在 Chromium 中打开已播种 Session 的菜单,对组装结果取快照,选择 action,并验证关闭、owner 数据与 fiber 生命周期清理。
菜单条目渲染 `MenuItemButton`——`ui-primitives` 为"行是组件"的菜单提供的行组件,只是一行普通 markup 与样式。它能加入菜单的键盘走位与焦点归还,是因为 `Menu` 从 DOM 上统一决定这两件事(方向键走位查询行元素;选中后的焦点归还在列表的 click 冒泡上执行一次,数据行与组件行一视同仁)。两类行的关闭都是 owner 的状态:数据行通过 owner 的 `onSelect`,组件行通过 slot 级 `useMenuOpenState` hook——声明带 `inject: { hooks: { menuOpenState } }`,`SessionNodeItem` 把自己的 `[open, setOpen]` 作为该次渲染的 `hookContext` 传入,factory 把这一对原样交回。这正是 `sidebar.right.pane.tab` 用于 `useTabInfo` 的通道。
## 考虑过的替代方案
**通过 slot owner props 传递菜单 descriptor。** 这会使渲染 slot 变成第二套数据注册表,通过回调暴露展示策略,并阻止普通 slot 组件持有自身注入服务。
**在 `Menu` 与行组件之间放一个 React context。** 否决:业务组件不接触任何 React context([client 规则](../../../../packages/client/AGENTS.md));Menu 与行是经 slot 系统建立的父子关系,控制权就该走 slot 的通道。
**暴露原始菜单 markup。** 这会让插件偏离菜单的无障碍、焦点与视觉行为。要求使用共享 `MenuAction`,可让打包与动态加载的贡献项遵守同一套交互协议。
**由 owner 提供行能力。** 把 `pinned`/`archived` 和 `pin`/`archive`/`rename`/`fork` 回调经 owner props 或 slot 级 hook 交给条目,会让 browser 继续拥有每个动作,内置 action 沦为薄封装。否决:这些不是菜单的能力,每个 action 的行为属于它自己,需要的 Host 状态条目可以直接读。
**立即添加主要 slot 与「More…」slot。** Session action 已位于行省略号之后,而且当前 action 集合不需要另一层渐进披露。在出现已证实的密度问题前,第二层级只会提前增加标签与键盘策略。
**在内置行下方追加一个专用 slot。** 否决:它把内置行变成插件只能跟在后面的特权分组,还要在 primitive 里为本来只是一个有序列表的东西开第二条渲染路径。
**让条目自己算置顶顺序写入。** pin 条目为了拼 `pinSessionOrder` 的输入订阅整个 Session 列表和 Workspace 快照,列表一变所有可见行都重渲染,排序细节还进了菜单行。否决:写入归注入的回调,在完成时刻读一次快照。
**用声明式共享 store 传重命名请求与提示。** 请求与提示是本插件自己的瞬时事实,所以经条目自己的 inject face 以 apply 闭包观察源传递。
## 后果
插件无需编辑 `ui-workspace` 即可添加 Session action,同时 core action 保持稳定位置,外部冲突沿用 slot 注册表已有的 id 与 priority 规则。所有贡献项都使用共享 `MenuAction`。所有插件 action 都保留在次级行菜单内,直到观察到的规模证明需要新层级。
插件无需修改 `ui-workspace` 即可在菜单和悬停条里添加、重排或遮蔽 Session 行 action,内置 action 遵循相同规则、走相同注册路径。`WorkspaceBrowser` 不再传递 action 回调、渲染 toast 或承载重命名对话框;`Menu` 新增 `children`,`items`/`onSelect` 变为可选;`shell.overlay` 多了两个 `ui-workspace` 条目。归档提示直接应用"显示已归档"筛选,不再打开视图选项菜单。
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/subsystems/slots.md
slots.md: 0143fd713c856d17cb3d2e77188155c46983e106
slots.zh.md: 18a52f954a7b065504de990e34fc42f536868e4d
slots.md: 1e820fd880163d565a72733372fa4f2cc70a62b5
slots.zh.md: c5bec8e752b9d9e1922f608449ca3249d0477062
+2 -1
View File
@@ -117,7 +117,8 @@ root
│ ├─ sidebar.footer.action
│ ├─ sidebar.workspaces
│ │ ├─ sidebar.workspaces.directoryFlow
│ │ └─ sidebar.workspaces.session.menu.action
│ │ ├─ sidebar.workspaces.session.menu.item
│ │ └─ sidebar.workspaces.session.row.action
│ └─ sidebar.settings
│ ├─ settings.trigger
│ ├─ settings.header
+2 -1
View File
@@ -117,7 +117,8 @@ root
│ ├─ sidebar.footer.action
│ ├─ sidebar.workspaces
│ │ ├─ sidebar.workspaces.directoryFlow
│ │ └─ sidebar.workspaces.session.menu.action
│ │ ├─ sidebar.workspaces.session.menu.item
│ │ └─ sidebar.workspaces.session.row.action
│ └─ sidebar.settings
│ ├─ settings.trigger
│ ├─ settings.header
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md
README.md: 5f45c6ffdc530a0ea7a64a7161c35f992c88ed02
README.zh.md: 052c1c583c62e4dd06c0366eeadc5b41de86d9ec
README.md: 51ad53a79a676f013b61213764479a1247de522c
README.zh.md: c41d19af1855c8ab1582fa92b956ef283d3466cf
+1 -1
View File
@@ -40,7 +40,7 @@ Check this table before writing a control in a feature package. A plugin cannot
| `Switch` | Two-state toggle, 36×20. `label` is required, so the control cannot ship unnamed. |
| `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. |
| `Input` | Single-line text entry for search boxes and inline forms. |
| `Menu`, `MenuAction` | Dropdown of owner-defined items, separators, and group labels, with nested submenus plus optional child actions rendered through `MenuAction`. Injected actions share the same styling, dismissal, focus restoration, submenu reset, and keyboard order. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. |
| `Menu`, `MenuItemButton` | Dropdown of `items` data rows, separators, and group labels, with nested submenus; `children` adds component rows, each a `MenuItemButton` (`separatorBefore` starts a new group), in the same list. Every row shares the styling, the keyboard walk, and the focus return; closing stays the owner's state change for both kinds. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. |
| `Pill` | Selectable capsule button for view switchers and filters; takes `active` and `onClick`. |
| `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. |
| `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. `aria-hidden`, so the render site owns the name. |
+1 -1
View File
@@ -40,7 +40,7 @@ kind: "package-library"
| `Switch` | 36×20 的双态开关。`label` 必填,控件不可能在没有名称的情况下发布。 |
| `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。 |
| `Input` | 单行文本输入,用于搜索框与行内表单。 |
| `Menu`, `MenuAction` | 由 owner 定义条目、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单,也可通过 `MenuAction` 渲染可选子 action。注入的 action 共享相同样式、关闭行为、焦点恢复、子菜单重置和键盘顺序。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 |
| `Menu`, `MenuItemButton` | 由 `items` 数据行、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单;`children` 在同一列表中加入组件行,每行一个 `MenuItemButton`(`separatorBefore` 开启新分组)。所有行共享样式、键盘走位与焦点归还;两类行的关闭都是 owner 状态的改变。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 |
| `Pill` | 可选中的胶囊按钮,用于视图切换与筛选器;接受 `active` 与 `onClick`。 |
| `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 |
| `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading。它是 `aria-hidden` 的,名称由渲染点提供。 |
@@ -75,17 +75,6 @@
min-height: 0;
}
/* Extension actions are the secondary group after owner-defined rows. */
.extensionActions:not(:has(button[role='menuitem'])) {
display: none;
}
.extensionSeparator {
margin-top: 4px;
margin-bottom: 4px;
border-top: 0.5px solid var(--dsw-alias-border-l2);
}
.scrollable .viewport {
overflow-y: auto;
}
@@ -260,6 +249,13 @@
background: var(--dsw-alias-border-l2);
}
/* Two group starts in a row (a data separator followed by a row that also
* starts a group, or two such rows) draw one line, not two. */
.separator + .separator,
.separator + .itemWrap > .separator:first-child {
display: none;
}
/* Nested card to the right of the parent row.
* Bottom-aligned with the parent menu card (grows upward): itemWrap sits in
* .list's 3px pad, so bottom: -3px matches the list's outer bottom edge.
+51 -62
View File
@@ -1,4 +1,4 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { CSSProperties, ReactNode } from 'react'
import { createPortal } from 'react-dom'
import clsx from 'clsx'
@@ -36,52 +36,53 @@ export interface MenuLabel {
/** One primary-menu entry: a row, a separator, or a heading label. */
export type MenuEntry = MenuItem | MenuSeparator | MenuLabel
interface MenuActionContextValue {
clearSubmenu: () => void
select: (action: () => void) => void
}
const MenuActionContext = createContext<MenuActionContextValue | null>(null)
/** Props for an action contributed as a child of {@link Menu}. */
export interface MenuActionProps {
/** Visible action label. */
/** Props for one component-rendered menu row. */
export interface MenuItemButtonProps {
/** Visible row label. */
children: ReactNode
/** Leading icon. */
/** Leading icon (figma .Menu_cell gap 8). */
icon?: ReactNode
/** Whether the action cannot be selected. */
/** Whether the row cannot be activated. */
disabled?: boolean
/** Use the destructive action colors. */
/** Destructive row: error-colored text/icon and danger hover fill. */
danger?: boolean
/** Run the action, then close the containing menu and restore focus. */
/**
* Start a new group: a hairline above this row, the same one a
* `{ type: 'separator' }` data entry draws. It comes and goes with the row,
* so a row that renders nothing leaves no stray line, and two adjacent
* group starts collapse into one line.
*/
separatorBefore?: boolean
/** Row activation (click, Enter, or Tab on the focused row). */
onSelect: () => void
}
/**
* Render one action supplied through a menu extension point.
*
* The action must be a descendant of {@link Menu}. It shares the menu's
* keyboard navigation, selection dismissal, focus restoration, and styling.
* @param props - action presentation and behavior.
* @param props.children - visible action label.
* Render one `role="menuitem"` row for a {@link Menu} whose rows are
* components rather than `items` data: the same markup and styling as a data
* row, so it joins the list's keyboard walk and post-selection focus return
* without any shared state. Closing the menu stays the owner's decision, as
* it is for data rows.
* @param props.children - visible row label.
* @param props.icon - optional leading icon.
* @param props.disabled - whether the action cannot be selected.
* @param props.danger - whether to use destructive action colors.
* @param props.onSelect - action to run before the menu closes.
* @param props.disabled - whether the row cannot be activated.
* @param props.danger - whether to use the destructive row colors.
* @param props.separatorBefore - whether this row starts a new group (hairline above it).
* @param props.onSelect - row activation callback.
* @returns one menu-item row.
*/
export function MenuAction({ children, icon, disabled = false, danger = false, onSelect }: MenuActionProps) {
const menu = useContext(MenuActionContext)
if (menu === null) throw new Error('MenuAction must be rendered inside Menu')
export function MenuItemButton({
children, icon, disabled = false, danger = false, separatorBefore = false, onSelect,
}: MenuItemButtonProps) {
return (
<div className={css.itemWrap} onMouseEnter={menu.clearSubmenu}>
<div className={css.itemWrap}>
{separatorBefore && <div className={css.separator} role="separator" />}
<button
type="button"
role="menuitem"
className={clsx(css.item, danger && css.danger)}
disabled={disabled}
onFocus={menu.clearSubmenu}
onClick={() => { menu.select(onSelect) }}
onClick={onSelect}
>
{icon !== undefined && <span className={css.itemIcon}>{icon}</span>}
<span className={css.itemLabel}>{children}</span>
@@ -111,10 +112,10 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }
* @param props.autoFocus - focus the first item on open; the arrow keys walk the list either way.
* @param props.open - whether the list is showing (owner-controlled).
* @param props.anchor - the trigger element (rendered in place).
* @param props.items - selectable rows and optional separators.
* @param props.items - selectable data rows and optional separators (default none).
* @param props.selectedId - row shown as selected.
* @param props.selectedIds - rows shown as selected when a menu contains independent option groups.
* @param props.onSelect - row click callback (not called for disabled rows or submenu parents that only open children).
* @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).
@@ -138,8 +139,9 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }
* scroll/resize; return null to skip placement for that frame.
* @param props.footer - rows pinned below the scrolling items area, separated
* by a hairline; they stay visible while the items above scroll.
* @param props.children - extension actions appended after `items` in a
* separated group. Render each action with {@link MenuAction}.
* @param props.children - component rows rendered after `items` in the same
* list, each a {@link MenuItemButton}; they share the keyboard walk and the
* post-selection focus return.
* @param props.selection - how a selected row is marked: a trailing check
* (`'check'`, default — figma .Menu_cell) or the hover fill held on the row
* with no check (`'fill'`, for icon-labelled rows where a trailing glyph
@@ -150,16 +152,16 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }
* document.body outside the owner's DOM subtree.
* @returns anchor wrapper with the conditional list.
*/
export function Menu({ open, anchor, items, children, selectedId, selectedIds, onSelect, onClose, align = 'start', side = 'bottom', portal = false, closeOnPointerLeave = false, dense = false, compact = false, autoFocus = false, selection = 'check', getAnchorRect, footer, className, listClassName }: {
export function Menu({ open, anchor, items = [], children, selectedId, selectedIds, onSelect, onClose, align = 'start', side = 'bottom', portal = false, closeOnPointerLeave = false, dense = false, compact = false, autoFocus = false, selection = 'check', getAnchorRect, footer, className, listClassName }: {
open: boolean
autoFocus?: boolean
anchor: ReactNode
items: readonly MenuEntry[]
items?: readonly MenuEntry[]
children?: ReactNode
footer?: readonly MenuEntry[]
selectedId?: string | undefined
selectedIds?: readonly string[] | undefined
onSelect: (id: string) => void
onSelect?: (id: string) => void
onClose: () => void
align?: 'start' | 'end'
side?: 'bottom' | 'top' | 'right'
@@ -400,15 +402,6 @@ export function Menu({ open, anchor, items, children, selectedId, selectedIds, o
// scroll clip would crop it, so only submenu-free menus get the height cap.
const scrollable = !items.some(entry => !isSeparator(entry) && !isLabel(entry) && entry.submenu !== undefined && entry.submenu.length > 0)
const selectExtensionAction = (action: () => void): void => {
try {
action()
} finally {
onClose()
refocusAfterSelection()
}
}
const renderEntry = (entry: MenuEntry) => {
if (isSeparator(entry)) {
return <div key={entry.id} className={css.separator} role="separator" />
@@ -439,8 +432,7 @@ export function Menu({ open, anchor, items, children, selectedId, selectedIds, o
setOpenSubmenuId(entry.id)
return
}
onSelect(entry.id)
refocusAfterSelection()
onSelect?.(entry.id)
}}
>
{entry.icon !== undefined && <span className={css.itemIcon}>{entry.icon}</span>}
@@ -457,7 +449,7 @@ export function Menu({ open, anchor, items, children, selectedId, selectedIds, o
role="menuitem"
className={css.item}
disabled={sub.disabled}
onClick={() => { onSelect(sub.id); refocusAfterSelection() }}
onClick={() => { onSelect?.(sub.id) }}
>
{sub.icon !== undefined && <span className={css.itemIcon}>{sub.icon}</span>}
<span className={css.itemLabel}>{sub.label}</span>
@@ -481,22 +473,19 @@ export function Menu({ open, anchor, items, children, selectedId, selectedIds, o
role="menu"
// React portals bubble synthetic events through the REACT tree: without
// this stop, an item click re-fires the anchor row's own onClick
// (open/toggle) after onSelect.
onClick={(e) => { e.stopPropagation() }}
// (open/toggle) after onSelect. The same bubble is where every row's
// activation lands — data rows and component rows alike — so the
// post-selection focus return is decided once here, after the row's
// own handler ran; a submenu parent only opened its card.
onClick={(e) => {
e.stopPropagation()
const row = e.target instanceof Element ? e.target.closest('button[role="menuitem"]') : null
if (row !== null && row.getAttribute('aria-haspopup') !== 'menu') refocusAfterSelection()
}}
>
<div className={css.viewport} role="presentation">
{items.map(renderEntry)}
{children !== undefined && (
<MenuActionContext.Provider value={{
clearSubmenu: () => { setOpenSubmenuId(null) },
select: selectExtensionAction,
}}>
<div className={css.extensionActions} role="presentation">
<div className={css.extensionSeparator} role="separator" />
{children}
</div>
</MenuActionContext.Provider>
)}
{children}
</div>
{footer !== undefined && footer.length > 0 && (
<div className={css.footer} role="presentation">
+2 -2
View File
@@ -14,8 +14,8 @@ export type { TagTone } from './Tag.tsx'
export { Switch } from './Switch.tsx'
export { Checkbox } from './Checkbox.tsx'
export { Input } from './Input.tsx'
export { Menu, MenuAction } from './Menu.tsx'
export type { MenuActionProps, MenuEntry, MenuItem, MenuSeparator, MenuLabel } from './Menu.tsx'
export { Menu, MenuItemButton } from './Menu.tsx'
export type { MenuItemButtonProps, MenuEntry, MenuItem, MenuSeparator, MenuLabel } from './Menu.tsx'
export { useAnchoredMaxHeight } from './useAnchoredMaxHeight.ts'
export { useAnchoredPosition } from './useAnchoredPosition.ts'
export type { AnchoredPositionOptions } from './useAnchoredPosition.ts'
@@ -2,7 +2,7 @@
import { useState } from 'react'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Button, ConnectionIndicator, Input, Menu, MenuAction, Modal, Pill } from '@deepseek-ai/dsh-client-ui-primitives'
import { Button, ConnectionIndicator, Input, Menu, MenuItemButton, Modal, Pill } from '@deepseek-ai/dsh-client-ui-primitives'
import { POINTER_GRACE_MS } from '../src/pointer-grace.ts'
afterEach(cleanup)
@@ -77,7 +77,7 @@ describe('Menu', () => {
expect(onSelect).toHaveBeenCalledWith('a')
})
it('appends extension actions to keyboard order and restores trigger focus after selection', async () => {
it('walks component rows with the data rows and returns focus to the trigger after one is activated', async () => {
const onAction = vi.fn()
function Harness() {
const [open, setOpen] = useState(true)
@@ -85,24 +85,27 @@ describe('Menu', () => {
<Menu
open={open}
anchor={<button type="button">trigger</button>}
items={[{ id: 'a', label: 'Alpha', submenu: [{ id: 'a1', label: 'Alpha one' }] }]}
items={[{ id: 'a', label: 'Alpha' }]}
onSelect={() => {}}
onClose={() => { setOpen(false) }}
>
<MenuAction onSelect={onAction}>Publish</MenuAction>
<MenuItemButton separatorBefore onSelect={() => { onAction(); setOpen(false) }}>Publish</MenuItemButton>
</Menu>
)
}
render(<Harness />)
const trigger = screen.getByRole('button', { name: 'trigger' })
fireEvent.mouseEnter(screen.getByRole('menuitem', { name: 'Alpha' }))
expect(screen.getByRole('menuitem', { name: 'Alpha one' })).toBeDefined()
expect(screen.getByRole('separator')).toBeDefined()
expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual(['Alpha', 'Publish'])
// The component row starts a group: one hairline, between the data row and it.
const publishWrap = screen.getByRole('menuitem', { name: 'Publish' }).parentElement
expect(screen.getByRole('separator').nextElementSibling).toBe(screen.getByRole('menuitem', { name: 'Publish' }))
expect(publishWrap?.contains(screen.getByRole('separator'))).toBe(true)
const publish = screen.getByRole('menuitem', { name: 'Publish' })
trigger.focus()
fireEvent.keyDown(trigger, { key: 'End' })
expect(document.activeElement).toBe(publish)
expect(screen.queryByRole('menuitem', { name: 'Alpha one' })).toBeNull()
fireEvent.keyDown(publish, { key: 'ArrowUp' })
expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Alpha' }))
fireEvent.click(publish)
expect(onAction).toHaveBeenCalledOnce()
expect(screen.queryByRole('menu')).toBeNull()
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md
README.md: 98bc6c7843c6d76c236f6bce83bf70a823d3394e
README.zh.md: 678568ad19e9b20ab9ad989a6d5505af7bc295f3
README.md: 65b0bd300b9e13bea18fc0c49b0594e38b649728
README.zh.md: 170a1a3e2bd71b400aa9e2c0e318f5e9100b3526
+25 -23
View File
@@ -1,5 +1,5 @@
---
description: "Shared Workspace browser and picker plugin for the dsh web client: grouped or flat session rows, management actions, extensible Session menus, and directory picking."
description: "Shared Workspace browser and picker plugin for the dsh web client: grouped or flat session rows, management actions, the slot-composed Session row actions, and directory picking."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
This package lets users browse grouped or flat Session lists, choose a Workspace for a new Session, and manage Workspaces and Sessions through add, rename, reorder, search, fork, archive, extensible row-menu actions, and Workspace deletion. Pending interactions appear as warning dots, active scheduled tasks as alarm markers, and subagent-origin Sessions remain hidden. Canonically distinct folder paths remain separate Workspaces. Adding a Workspace requires a composed directory picker; without one, the add action is unavailable.
This package lets users browse grouped or flat Session lists, choose a Workspace for a new Session, and manage Workspaces and Sessions through add, rename, reorder, search, fork, archive, and Workspace deletion; the Session row menu and its hover buttons are slot lists that client plugins extend. Pending interactions appear as warning dots, active scheduled tasks as alarm markers, and subagent-origin Sessions remain hidden. Canonically distinct folder paths remain separate Workspaces. Adding a Workspace requires a composed directory picker; without one, the add action is unavailable.
## Table of Contents
@@ -47,9 +47,9 @@ Collapsed search is one header action beside the view and add actions: activatin
### Managing sessions
The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action forks at the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Client plugins can append Session-specific actions to this menu through the ordered `sidebar.workspaces.session.menu.action` slot.
The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action forks at the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, and Archive are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it.
Archive commits without a confirmation dialog and retains the Session's account position. View options control visibility: the default hides archived Sessions, Show archived includes them, and Archived only hides ordinary Sessions. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a toast with undo and filter-menu actions. Unarchive removes the archive mark without restoring a pin or changing the saved position.
Archive commits without a confirmation dialog and retains the Session's account position. View options control visibility: the default hides archived Sessions, Show archived includes them, and Archived only hides ordinary Sessions. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a notice with an undo action and a "show archived" action that switches the filter directly. Unarchive removes the archive mark without restoring a pin or changing the saved position.
A Session title wider than its row is clipped with an ellipsis at rest. Hovering the row scrolls the title to its far edge — the incremented title of a fork, for example — and reveals it without the ellipsis; leaving the row returns the title to its start.
@@ -81,15 +81,15 @@ The package is one composition: both target slots are declared by other plugins,
Each registration declares a **directory-flow child hole** (`single` kind: `conversation.hero.workspace.directoryFlow` / `sidebar.workspaces.directoryFlow`) that the composed picker package's client half fills with its picking interaction — the `-native` backend's renderless OS-chooser driver, an in-app browsing dialog under a `-browse` composition. The flat **Add workspace...** action renders only while the surface's hole is occupied; an empty hole means the composition has no picking affordance. This package owns the trigger and the adoption: the occupant reports one picked path per open through the hole's owner conversation (`open`/`busy`/`onPicked`/`onCancel`/`onError`), and the owner adopts it through the object layer, selecting the committed Workspace only after its list projection has refreshed.
### Session menu actions
### Session row actions
An external client plugin contributes to `sidebar.workspaces.session.menu.action`. Built-in actions stay first in their fixed order; contributed actions form a secondary group after a semantic separator. The group is absent from presentation and accessibility APIs when it has no rendered menu-item button.
The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), and `archive` (menu 400, button 100) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action.
Each contribution receives the target `sessionId` and row `displayTitle` (persisted title, project basename, then Session id). Render the contribution with the shared `MenuAction` primitive; it owns the menu's styling, keyboard behavior, dismissal, and focus restoration. Use a fresh, package-namespaced `id`. Lower `order` values render first. Equal-order packaged registrations keep registration sequence; equal-order dynamic registrations use the facade's decreasing shadowing priority, so the newer entry comes first. `priority` otherwise selects the active registration when two entries deliberately reuse one `id`; it does not move a distinct id across `order` groups.
An entry receives only the row identity (`sessionId`, `displayTitle`) and owns everything else. It reads the Host state it cares about through its own injected hooks (the pin and archive sets, as Sets derived once per Workspace snapshot), decides its own visibility (pin renders nothing on an archived row, because the Host keeps the two sets exclusive), carries its whole behavior in its registration's `inject` face (a pin also fronts the Session in its saved orders; an archive raises the notice), and raises its own surfaces: the rename dialog and the row-action notice are this package's `shell.overlay` entries, fed by the requests the actions inject. A menu entry renders one `MenuItemButton` (with `separatorBefore` when it starts a new group; the hairline comes and goes with the row) and dismisses the menu through the slot-level `useMenuOpenState` hook, the menu's own open state bound from the row's render occurrence; a hover button entry renders one icon button. The browser passes no action callbacks to its rows; its remaining verbs are the search results' restore button and the title double-click, which raises the same rename request.
#### Packaged client plugin
Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot key. Keep the Component at module scope, project business operations through the registration's `inject` face, and own visible copy in the contributing package's locale namespace.
Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot keys. Keep the Component at module scope and own visible copy in the contributing package's locale namespace.
```tsx
import type { Context } from '@deepseek-ai/cordis'
@@ -97,7 +97,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types'
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-workspace/client'
import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives'
import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'
import type {
InjectFace, LocaleDictOf, PropsLocale, PropsRuntime,
} from '@deepseek-ai/dsh-client-ui-slots'
@@ -114,20 +114,21 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
const en: LocaleDictOf<typeof NS> = { export: 'Export {title}' }
const zh: LocaleDictOf<typeof NS> = { export: '导出 {title}' }
interface ExportActionInjected {
interface ExportRowInjected {
exportSession: (sessionId: SessionId) => void
}
type ExportActionProps =
PropsRuntime<'sidebar.workspaces.session.menu.action'>
type ExportRowProps =
PropsRuntime<'sidebar.workspaces.session.menu.item'>
& PropsLocale<typeof NS>
& InjectFace<ExportActionInjected>
& InjectFace<ExportRowInjected>
function ExportAction({ sessionId, displayTitle, exportSession, t }: ExportActionProps) {
function ExportRow({ sessionId, displayTitle, useMenuOpenState, exportSession, t }: ExportRowProps) {
const [, setMenuOpen] = useMenuOpenState()
return (
<MenuAction onSelect={() => { exportSession(sessionId) }}>
<MenuItemButton separatorBefore onSelect={() => { setMenuOpen(false); exportSession(sessionId) }}>
{t('export', { title: displayTitle })}
</MenuAction>
</MenuItemButton>
)
}
@@ -136,21 +137,22 @@ export const inject = ['slots', 'locale']
export function apply(ctx: Context): void {
ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'acme-session-actions: dictionaries')
ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register({
name: 'sidebar.workspaces.session.menu.action',
// Order 500 places the row after the shipped Archive (400); `separatorBefore` opens the plugin group.
ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register({
name: 'sidebar.workspaces.session.menu.item',
id: 'acme.export-session',
order: 100,
order: 500,
locale: NS,
inject: (): ExportActionInjected => ({ exportSession }),
}, ExportAction))
inject: (): ExportRowInjected => ({ exportSession }),
}, ExportRow))
}
```
`ctx.slots.inject()` is required even if the owner is normally present: it waits for the declaration, removes the contribution when that declaration collapses, and registers it again after restoration. The registration's `inject` factory may close over the plugin's declared Cordis services; the Component receives only the projected data and callbacks.
`ctx.slots.inject()` is required even if the owner is normally present: it waits for the declaration, removes the contribution when that declaration collapses, and registers it again after restoration. The registration's `inject` factory may close over the plugin's declared Cordis services; the Component receives only the projected data and callbacks. A hover button registers into `sidebar.workspaces.session.row.action` the same way and renders one icon button.
#### Dynamic client package
A dynamically loaded browser half follows the same component contract. `@deepseek-ai/dsh-client-ui-primitives` is an implicit baseline external: resolve its shared `MenuAction` export directly through the loader's `require`, and render it with `React.createElement`. Do not list the primitive as a runtime dependency or bundle another copy; declare a development dependency only when source compilation needs its types. `MenuAction` must share the host menu context. The real Loader/Web fixture and generated Client Slot catalog contain runnable examples.
A dynamically loaded browser half follows the same component contract. `@deepseek-ai/dsh-client-ui-primitives` is an implicit baseline external: resolve `MenuItemButton` through the loader's `require` and render it with `React.createElement`. Do not list the primitive as a runtime dependency or bundle another copy; declare a development dependency only when source compilation needs its types. The real Loader/Web fixture and the generated Client Slot catalog contain runnable examples.
### View state
+25 -23
View File
@@ -1,5 +1,5 @@
---
description: "dsh Web 客户端的共享 Workspace 浏览器与选择器插件:分组或扁平的会话行、管理操作、可扩展 Session 菜单与目录选择。"
description: "dsh Web 客户端的共享 Workspace 浏览器与选择器插件:分组或扁平的会话行、管理操作、由 slot 组合的 Session 行 action 与目录选择。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
本包让用户浏览分组或扁平的 Session 列表、为新 Session 选择 Workspace,并通过添加、重命名、重排序、搜索、fork、归档、可扩展行菜单操作和删除 Workspace 来管理 Workspace 与 Session。待处理交互显示为警告点,活动定时任务显示为闹钟标识,subagent 来源的 Session 则保持隐藏。规范化后仍有差异的文件夹路径会保留为独立 Workspace。添加 Workspace 需要组合目录选择器;没有目录选择器时,添加操作不可用。
本包让用户浏览分组或扁平的 Session 列表、为新 Session 选择 Workspace,并通过添加、重命名、重排序、搜索、fork、归档和删除 Workspace 来管理 Workspace 与 Session;Session 行菜单及其悬停按钮是可由客户端插件扩展的 slot 列表。待处理交互显示为警告点,活动定时任务显示为闹钟标识,subagent 来源的 Session 则保持隐藏。规范化后仍有差异的文件夹路径会保留为独立 Workspace。添加 Workspace 需要组合目录选择器;没有目录选择器时,添加操作不可用。
## 目录
@@ -47,9 +47,9 @@ kind: "package-reference"
### 管理会话
Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 在源会话最后一个已完成轮次处 fork,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。客户端插件可通过有序 `sidebar.workspaces.session.menu.action` slot 向此菜单追加 Session 专属 action。
Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 在源会话最后一个已完成轮次处 fork,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。
Archive 不经确认对话框直接提交,并保留 Session 的记账位置。视图选项控制显隐:默认隐藏已归档 Session,显示已归档会将其纳入列表,仅显示已归档则隐藏普通 Session。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后,toast 提供撤销与打开筛选菜单的操作。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。
Archive 不经确认对话框直接提交,并保留 Session 的记账位置。视图选项控制显隐:默认隐藏已归档 Session,显示已归档会将其纳入列表,仅显示已归档则隐藏普通 Session。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后的提示提供"撤销"和"筛选已归档会话"两个动作,后者直接把筛选切到显示已归档。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。
标题宽于所在行时,静止状态以省略号裁切。把指针停在行上,标题会滚动到远端——例如 fork 递增后的标题——并在揭示时不显示省略号;指针离开后标题回到开头。
@@ -81,15 +81,15 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示**
每个注册各自声明一个**目录流子 slot**(`single` kind:`conversation.hero.workspace.directoryFlow`/`sidebar.workspaces.directoryFlow`),由组合的选择器包 client half 填入其选取交互——`-native` 后端的无渲染 OS 选择器驱动,`-browse` 组合下则是应用内浏览对话框。平铺显示的**添加工作区…** 操作仅在当前界面的 slot 被占用时渲染;slot 为空意味着该组合没有目录选择能力。本包持有触发与接纳:占用方通过 slot 的属主交互约定(`open`/`busy`/`onPicked`/`onCancel`/`onError`)每次打开上报一个所选路径,owner 通过对象层接纳它,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace。
### Session 菜单 action
### Session 行 action
外部客户端插件向 `sidebar.workspaces.session.menu.action` 贡献 action。内置 action 以固定顺序保持在前;贡献 action 位于语义分隔线后的次级分组中。没有渲染菜单按钮时,该分组不会出现在视觉与无障碍 API 中。
Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。
每个贡献项接收目标 `sessionId` 与行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id)。贡献项必须使用共享的 `MenuAction` primitive 渲染;菜单样式、键盘行为、关闭与焦点恢复均由它统一负责。请使用带包命名空间的新 `id`。较小的 `order` 先渲染;`order` 相同的打包注册保持注册顺序,动态注册则使用 facade 分配的递减 shadowing priority,因此较新的注册在前。除此之外,`priority` 只在两个注册有意复用同一 `id` 时选择活动项,不会让不同 id 跨越 `order` 分组。
条目只接收行身份(`sessionId`、`displayTitle`),其余一切自己负责:用自己注入的 hook 读自己关心的 Host 状态(置顶与归档集合,以每次 Workspace 快照只派生一次的 Set 形式),自己决定是否显示(Host 规定归档与置顶互斥,所以 pin 在归档行上不渲染),整套行为放在注册项自己的 `inject` face 里(置顶成功后顺带把会话推到保存顺序最前,归档成功后发提示),浮层也自己带——重命名对话框和行 action 的提示是本包注册在 `shell.overlay` 的条目,由 action 注入的请求驱动。菜单条目渲染一个 `MenuItemButton`(开启新分组的行加 `separatorBefore`,分隔线随行一起出现和消失),并通过 slot 级 `useMenuOpenState` hook(菜单自身的打开状态,从该行的渲染出现处绑定)关闭菜单;悬停按钮条目渲染一个图标按钮。browser 不再向行传任何 action 回调,它剩下的动作只有搜索结果里的恢复按钮和标题双击,后者发出的是同一个重命名请求。
#### 打包客户端插件
按照 Client 依赖规则,将 `ui-workspace`、`ui-slots`、`ui-renderer`、`client-locale` 与 `ui-primitives` 声明为浏览器/类型开发依赖。纯类型的 `ui-workspace/client` import 会加载本包的 `SlotMap` 声明;缺少该 import 时,独立编译的插件不会知道这个 slot key。Component 保持模块级稳定身份;业务操作通过注册项的 `inject` face 投影;用户可见文案由贡献包自己的 locale namespace 持有。
按照 Client 依赖规则,将 `ui-workspace`、`ui-slots`、`ui-renderer`、`client-locale` 与 `ui-primitives` 声明为浏览器/类型开发依赖。纯类型的 `ui-workspace/client` import 会加载本包的 `SlotMap` 声明;缺少该 import 时,独立编译的插件不会知道这些 slot key。Component 保持模块级稳定身份;用户可见文案由贡献包自己的 locale namespace 持有。
```tsx
import type { Context } from '@deepseek-ai/cordis'
@@ -97,7 +97,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types'
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-workspace/client'
import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives'
import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'
import type {
InjectFace, LocaleDictOf, PropsLocale, PropsRuntime,
} from '@deepseek-ai/dsh-client-ui-slots'
@@ -114,20 +114,21 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
const en: LocaleDictOf<typeof NS> = { export: 'Export {title}' }
const zh: LocaleDictOf<typeof NS> = { export: '导出 {title}' }
interface ExportActionInjected {
interface ExportRowInjected {
exportSession: (sessionId: SessionId) => void
}
type ExportActionProps =
PropsRuntime<'sidebar.workspaces.session.menu.action'>
type ExportRowProps =
PropsRuntime<'sidebar.workspaces.session.menu.item'>
& PropsLocale<typeof NS>
& InjectFace<ExportActionInjected>
& InjectFace<ExportRowInjected>
function ExportAction({ sessionId, displayTitle, exportSession, t }: ExportActionProps) {
function ExportRow({ sessionId, displayTitle, useMenuOpenState, exportSession, t }: ExportRowProps) {
const [, setMenuOpen] = useMenuOpenState()
return (
<MenuAction onSelect={() => { exportSession(sessionId) }}>
<MenuItemButton separatorBefore onSelect={() => { setMenuOpen(false); exportSession(sessionId) }}>
{t('export', { title: displayTitle })}
</MenuAction>
</MenuItemButton>
)
}
@@ -136,21 +137,22 @@ export const inject = ['slots', 'locale']
export function apply(ctx: Context): void {
ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'acme-session-actions: dictionaries')
ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register({
name: 'sidebar.workspaces.session.menu.action',
// Order 500 places the row after the shipped Archive (400); `separatorBefore` opens the plugin group.
ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register({
name: 'sidebar.workspaces.session.menu.item',
id: 'acme.export-session',
order: 100,
order: 500,
locale: NS,
inject: (): ExportActionInjected => ({ exportSession }),
}, ExportAction))
inject: (): ExportRowInjected => ({ exportSession }),
}, ExportRow))
}
```
即使 owner 通常已经存在,也必须使用 `ctx.slots.inject()`:它等待声明,在声明折叠时移除贡献项,并在声明恢复后重新注册。注册项的 `inject` factory 可以闭包使用插件已声明的 Cordis service;Component 只接收投影后的数据和 callback。
即使 owner 通常已经存在,也必须使用 `ctx.slots.inject()`:它等待声明,在声明折叠时移除贡献项,并在声明恢复后重新注册。注册项的 `inject` factory 可以闭包使用插件已声明的 Cordis service;Component 只接收投影后的数据和 callback。悬停按钮以同样方式注册到 `sidebar.workspaces.session.row.action`,渲染一个图标按钮。
#### 动态客户端包
动态加载的 browser half 采用同一套组件协议。`@deepseek-ai/dsh-client-ui-primitives` 是隐式 baseline external:直接通过 loader 的 `require` 解析共享的 `MenuAction` export,再用 `React.createElement` 渲染。不要把 primitive 列为运行时依赖或打包另一份副本;仅在源码编译需要其类型时声明开发依赖。`MenuAction` 必须与宿主菜单共享 context。真实 Loader/Web fixture 与生成的 Client Slot catalog 都包含可运行示例。
动态加载的 browser half 采用同一套组件协议。`@deepseek-ai/dsh-client-ui-primitives` 是隐式 baseline external:通过 loader 的 `require` 解析 `MenuItemButton`,再用 `React.createElement` 渲染。不要把 primitive 列为运行时依赖或打包另一份副本;仅在源码编译需要其类型时声明开发依赖。真实 Loader/Web fixture 与生成的 Client Slot catalog 都包含可运行示例。
### 视图状态
@@ -20,14 +20,26 @@
* leaves the surface with no add affordance at all.
* Two holes exist because the two menu surfaces are independent slot entries
* and a hole has exactly one declaring entry — they carry the same owner
* contract and the same occupant. WorkspaceBrowser also declares the ordered
* Session-menu action list that client plugins can extend.
* contract and the same occupant.
*
* WorkspaceBrowser also declares the two **Session row action lists**: every
* row of a Session's "..." menu is an entry of
* `sidebar.workspaces.session.menu.item`, and every hover button at the row's
* end is an entry of `sidebar.workspaces.session.row.action`. The shipped
* actions — pin, rename, fork, archive — are ordinary entries this package
* registers from `apply`, each carrying its own behavior in its own inject
* face and reading its own Host state through the standard hooks, so a client
* plugin's action lands beside them by `order` and needs nothing from the
* browser beyond the row identity.
*/
import type { HostObservable, PropsHooks, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
import type {
HostObservable, InjectFace, PropsHooks, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore, SlotHookFactory,
} from '@deepseek-ai/dsh-client-ui-slots'
// Type-only: pull the owner SlotMap merges into programs that resolve the
// runtime shares below.
import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type { SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client'
import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client'
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
@@ -52,14 +64,35 @@ export interface DirectoryFlowOwnerProps {
onError: (message: string) => void
}
/** Point-in-time Session row information supplied to each menu action. */
export interface SessionMenuActionOwnerProps {
/** Session targeted by the open row menu. */
/** Owner share of one Session row action occurrence: the row the action belongs to. */
export interface SessionRowOwnerProps {
/** Session the row shows. */
sessionId: SessionId
/** Row display title: persisted title, project basename, or Session id. */
displayTitle: string
}
/** The row menu's open state as its owner holds it: the `useState` pair. */
export type MenuOpenState = readonly [open: boolean, setOpen: (open: boolean) => void]
/**
* Hook every row-menu entry receives. Rows only render while the menu is
* open, so an entry reads it for the setter: `setOpen(false)` dismisses the
* menu the entry sits in — the same state the owner's `onClose` sets.
*/
export type UseMenuOpenState = () => MenuOpenState
/**
* Bind the row's render occurrence into the entries' `useMenuOpenState` hook:
* the owner supplies its open-state pair as the occurrence's `hookContext`,
* and the hook hands that pair back.
* @param _standard - framework standard props (unused).
* @param state - the menu's open-state pair from the render occurrence.
* @returns the hook the entry calls.
*/
export const menuOpenStateFactory: SlotHookFactory<'sidebar.workspaces.session.menu.item', UseMenuOpenState> =
(_standard, state) => () => state
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
/** Directory-flow hole under the conversation empty-state picker (declared by the WorkspacePicker entry). */
@@ -67,34 +100,51 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
/** Directory-flow hole under the sidebar browsing region (declared by the WorkspaceBrowser entry). */
'sidebar.workspaces.directoryFlow': { kind: 'single'; scope: 'root'; owner: DirectoryFlowOwnerProps }
/**
* Ordered third-party actions below the built-in Session row-menu actions.
* Registrations use a fresh id and sort by lower order. Equal-order packaged
* registrations keep registration sequence; equal-order dynamic registrations
* use the facade's decreasing shadowing priority, so the newer entry comes
* first. Priority selects the active registration for one reused id; it does
* not override order across distinct ids. Contributions render `MenuAction`
* so the shared primitive owns styling, keyboard behavior, dismissal, and
* focus restoration. An empty list has no visible or accessible secondary group.
* The rows of one Session's "..." menu, in ascending `order`. ui-workspace
* registers the shipped rows here — `pin` (100), `rename` (200), `fork`
* (300), `archive` (400) — so a plugin row is placed by its own `order`
* among them. Use a package-namespaced `id`; reusing a shipped id at
* another `priority` shadows that row. Each entry renders one
* `MenuItemButton` (`separatorBefore` when it starts a new group), decides
* its own visibility from its own state, and dismisses the menu through the
* injected `useMenuOpenState` hook after acting. Labels come from the
* contributing package's locale namespace.
* @example
* const React = require('react')
* const { MenuAction } = require('@deepseek-ai/dsh-client-ui-primitives')
* const { MenuItemButton } = require('@deepseek-ai/dsh-client-ui-primitives')
*
* return {
* inject: ['slots'],
* apply(ctx) {
* const copyLabel = 'Copy Session ID' // Localize in the contributing package.
* ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register(
* { name: 'sidebar.workspaces.session.menu.action', id: 'copy-session-id', order: 100 },
* ({ sessionId }) => React.createElement(
* MenuAction,
* { onSelect: () => { void navigator.clipboard.writeText(sessionId) } },
* copyLabel,
* ),
* ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register(
* { name: 'sidebar.workspaces.session.menu.item', id: 'copy-session-id', order: 500 },
* ({ sessionId, useMenuOpenState }) => {
* const [, setMenuOpen] = useMenuOpenState()
* return React.createElement(
* MenuItemButton,
* { onSelect: () => { setMenuOpen(false); void navigator.clipboard.writeText(sessionId) } },
* copyLabel,
* )
* },
* ))
* },
* }
*/
'sidebar.workspaces.session.menu.action': { kind: 'list'; scope: 'root'; owner: SessionMenuActionOwnerProps }
'sidebar.workspaces.session.menu.item': {
kind: 'list'
scope: 'root'
owner: SessionRowOwnerProps
hookContext: MenuOpenState
inject: { hooks: { menuOpenState: SlotHookFactory<'sidebar.workspaces.session.menu.item', UseMenuOpenState> } }
}
/**
* The hover buttons at the end of one Session row, in ascending `order`,
* after the "..." menu trigger. ui-workspace registers `archive` (100) and
* `pin` (200) here. An entry renders one icon button (or nothing, when its
* action does not apply to the row) and owns the action it performs.
*/
'sidebar.workspaces.session.row.action': { kind: 'list'; scope: 'root'; owner: SessionRowOwnerProps }
}
}
@@ -153,10 +203,10 @@ export type WorkspaceBrowserInjected = {
) => Promise<{ items: readonly SessionSearchResultItem[]; hasMore: boolean }>
/** Maximum number of merged rows rendered for one search. */
searchResultLimit: number
/** Rename a Session (explicit user title; resolves on host acceptance). */
renameSession: (sessionId: SessionId, title: string) => Promise<void>
/** Fork a Session at its last completed turn and open the child. */
forkSession: (sessionId: SessionId) => void
/** Open the Session rename dialog (a row title double-click); the rename action entry raises the same request. */
requestSessionRename: (sessionId: SessionId, currentTitle: string) => void
/** Tell the user an archived row cannot be opened (a click on it). */
notifyArchivedNotOpenable: () => void
/** Rename a Host Workspace (rejects on name conflict; resolves on durability). */
renameWorkspace: (workspaceId: WorkspaceId, title: string) => Promise<void>
/** Delete only a Host Workspace registration; directory and Session logs remain. */
@@ -166,29 +216,143 @@ export type WorkspaceBrowserInjected = {
* Omitted anchor appends to the end.
*/
insertWorkspaceBefore: (workspaceId: WorkspaceId, beforeWorkspaceId?: WorkspaceId) => Promise<void>
/**
* Archive a Session into the registry-global set: hidden from grouping
* surfaces, log and accounting slot retained. Archiving the current
* session clears the selection into the New Session view state.
*/
archiveSession: (sessionId: SessionId) => Promise<void>
/** Remove a Session from the registry-global archived set. */
/** Remove a Session from the registry-global archived set (the search results' restore button). */
unarchiveSession: (sessionId: SessionId) => Promise<void>
/** Add a Session to the registry-global pinned set (newest pin first). */
pinSession: (sessionId: SessionId) => Promise<void>
/** Remove a Session from the registry-global pinned set. */
unpinSession: (sessionId: SessionId) => Promise<void>
/** Adopt a picked host directory as a real Workspace before targeting a Session. */
createWorkspace: (input: { path: string }) => Promise<WorkspaceView>
}
/** The browser's declared viewing store handle, shared with the row actions that write view state. */
export type WorkspaceViewStoreHandle = ReturnType<typeof createWorkspaceViewStore>
/** Props of one shipped row-menu entry: owner share + locale seat + the entry's own injected share. */
export type SessionMenuItemProps<Injected extends object = object> =
PropsRuntime<'sidebar.workspaces.session.menu.item'>
& PropsLocale<'workspace'>
& InjectFace<Injected>
/** Props of one shipped row hover button: owner share + locale seat + the entry's own injected share. */
export type SessionRowActionProps<Injected extends object = object> =
PropsRuntime<'sidebar.workspaces.session.row.action'>
& PropsLocale<'workspace'>
& InjectFace<Injected>
/** One transient notice a row action raises; the overlay toast entry renders it. */
export type RowToast =
| { kind: 'archived'; sessionId: SessionId }
| { kind: 'pinFailed' }
| { kind: 'unpinFailed' }
| { kind: 'archivedNotOpenable' }
/** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */
export type RowToastState = RowToast & { seq: number }
/**
* Pin action share (menu row and hover button). The callbacks carry the whole
* behavior: the Host call, fronting the Session in its saved orders after a
* pin, and the failure notice. The hooks are the registry-global sets as
* Sets, so a row reads its own membership with one lookup.
*/
export interface PinSessionInjected {
hooks: {
/** Pinned Session ids. */
pinned: HostObservable<ReadonlySet<SessionId>>
/** Archived Session ids (pin does not apply to an archived row). */
archived: HostObservable<ReadonlySet<SessionId>>
}
/** Pin a Session; on success it leads its accounts' saved orders, on failure the notice says so. */
pinSession: (sessionId: SessionId) => void
/** Unpin a Session; saved positions stay as they are. */
unpinSession: (sessionId: SessionId) => void
}
/**
* Archive action share (menu row and hover button). The callbacks carry the
* whole behavior: the Host call, the notice a success raises, and the
* diagnostics for a rejection.
*/
export interface ArchiveSessionInjected {
hooks: {
/** Archived Session ids. */
archived: HostObservable<ReadonlySet<SessionId>>
}
/**
* Archive a Session into the registry-global set: the row keeps its
* account position and shows per the archived filter; archiving the
* current session clears the selection into the New Session view state.
*/
archiveSession: (sessionId: SessionId) => void
/** Remove a Session from the registry-global archived set. */
unarchiveSession: (sessionId: SessionId) => void
}
/** Fork action share. */
export interface ForkSessionInjected {
/** Fork a Session at its last completed turn; the child arrives through the Host list. */
forkSession: (sessionId: SessionId) => void
}
/** Rename action share: the row only raises the request; the dialog entry answers it. */
export interface RenameSessionInjected {
/** Ask for the rename dialog, seeded with the row's current title. */
requestSessionRename: (sessionId: SessionId, currentTitle: string) => void
}
/** A Session rename the rename action asked for; the dialog entry opens on it. */
export interface SessionRenameRequest {
/** Session to rename. */
sessionId: SessionId
/** Title the dialog seeds its draft from. */
currentTitle: string
}
/** Rename dialog share: the pending request, its settlement, and the rename hop the dialog confirms with. */
export interface SessionRenameDialogInjected {
hooks: {
/** The rename asked for, until the dialog consumes or cancels it. */
renameRequest: HostObservable<SessionRenameRequest | null>
}
/** Consume or cancel the pending request. */
settleSessionRename: () => void
/** Rename a Session (explicit user title; resolves on host acceptance). */
renameSession: (sessionId: SessionId, title: string) => Promise<void>
}
/** Row toast share: the notice on display, its dismissal, and the two actions the archived notice offers. */
export interface RowToastInjected {
hooks: {
/** The notice on display, or none. */
toast: HostObservable<RowToastState | null>
}
/** Take the notice down. */
dismissToast: () => void
/** Undo an archive from its notice. */
undoArchive: (sessionId: SessionId) => void
/** Switch the archived filter to "show" so the archived row is back in view. */
showArchived: () => void
}
/** Props of the rename dialog entry in `shell.overlay`. */
export type SessionRenameDialogProps =
PropsRuntime<'shell.overlay'>
& PropsLocale<'workspace'>
& Omit<SessionRenameDialogInjected, 'hooks'>
& PropsHooks<SessionRenameDialogInjected['hooks']>
/** Props of the row toast entry in `shell.overlay`. */
export type RowToastProps =
PropsRuntime<'shell.overlay'>
& PropsLocale<'workspace'>
& Omit<RowToastInjected, 'hooks'>
& PropsHooks<RowToastInjected['hooks']>
/** Full browser props: shell owner share + viewing store + injected actions + the locale seat. */
export type WorkspaceBrowserProps =
PropsRuntime<'sidebar.workspaces'>
& PropsRenderSlots<
'sidebar.workspaces.directoryFlow' | 'sidebar.workspaces.session.menu.action'
'sidebar.workspaces.directoryFlow' | 'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action'
>
& PropsStore<ReturnType<typeof createWorkspaceViewStore>>
& PropsStore<WorkspaceViewStoreHandle>
& Omit<WorkspaceBrowserInjected, 'hooks'>
& PropsHooks<WorkspaceBrowserInjected['hooks']>
& PropsLocale<'workspace'>
+131 -24
View File
@@ -5,15 +5,20 @@
* (`conversation.hero.workspace` — both hero forms). Both read real Host
* Workspaces through the global useWorkspaces hook, and each declares its
* own `single` directory-flow child hole for the composed picker package's
* client half. WorkspaceBrowser additionally declares the ordered Session
* menu-action list (see the contract module doc). Export discipline:
* client half. WorkspaceBrowser additionally declares the two Session row
* action lists, and this apply registers the shipped actions — pin, rename,
* fork, archive — into them the way any client plugin would, each with its
* own behavior, plus the rename dialog and the row-action notice into
* `shell.overlay` (see the contract module doc). Export discipline:
* packages/client/AGENTS.md.
*/
import type { Context } from '@deepseek-ai/cordis'
import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client'
import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'
import type { IWorkspaces, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { HostObservable, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
// Type-only: pulls the Controller service merges.
import type {} from '@deepseek-ai/dsh-api-session-controller/client'
import type {} from '@deepseek-ai/dsh-api-workspace-controller/client'
@@ -24,17 +29,28 @@ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
// Type-only: pulls the Session root standard-hook merge.
import type {} from '@deepseek-ai/dsh-client-ui-session/client'
import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from './contract/slots.ts'
import {
type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected,
type RenameSessionInjected, type RowToast, type RowToastInjected, type RowToastState, type SessionRenameDialogInjected,
type SessionRenameRequest, type WorkspaceBrowserInjected, type WorkspacePickerInjected,
} from './contract/slots.ts'
import { UiWorkspaceService } from './navigation.ts'
import { createWorkspaceViewStore } from './stores.ts'
import { WorkspaceBrowser } from './rows/WorkspaceBrowser.tsx'
import { ArchiveSessionMenuItem, ArchiveSessionRowButton } from './session-actions/ArchiveSession.tsx'
import { derive } from './session-actions/derived.ts'
import { ForkSessionMenuItem } from './session-actions/ForkSession.tsx'
import { PinSessionMenuItem, PinSessionRowButton } from './session-actions/PinSession.tsx'
import { RenameSessionMenuItem, SessionRenameDialog } from './session-actions/RenameSession.tsx'
import { RowActionToast } from './session-actions/RowActionToast.tsx'
import { WorkspacePicker } from './WorkspacePicker.tsx'
import { en, zh, type WorkspaceKey } from './locales.ts'
export type { UiWorkspace } from './navigation.ts'
export type {
DirectoryFlowOwnerProps, DirectoryFlowSlotName, DirectoryPickingHooks, DirectoryPickingInjected,
SessionMenuActionOwnerProps, WorkspaceBrowserInjected, WorkspaceBrowserProps,
MenuOpenState, RowToast, SessionRenameRequest, SessionRowOwnerProps, UseMenuOpenState, WorkspaceBrowserInjected,
WorkspaceBrowserProps,
WorkspacePickerInjected, WorkspacePickerProps,
} from './contract/slots.ts'
export type { WorkspaceKey } from './locales.ts'
@@ -81,8 +97,14 @@ export const inject = [
export function apply(ctx: Context): void {
const sessions = ctx.get('sessions') as ISessions
const workspaces = ctx.get('workspaces') as IWorkspaces
// One viewing-store instance, created here as ui-layout does for its layout
// store: the browser declares the handle, and the UiWorkspace service writes
// view order through the same instance the renderer hands the browser.
const viewHandle = createWorkspaceViewStore()
const viewInstance = viewHandle.create()
const viewStore: typeof viewHandle = { ...viewHandle, create: () => viewInstance }
const uiWorkspace = new UiWorkspaceService(
ctx, ctx.remote.directoryPicker, workspaces, sessions)
ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions)
ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } })
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries')
@@ -107,6 +129,76 @@ export function apply(ctx: Context): void {
const openSession: WorkspaceBrowserInjected['open'] = (sessionId) => {
uiWorkspace.openSession(sessionId)
}
// Registry-global sets as Sets, rebuilt only when the Workspace snapshot changes.
const pinnedSet = derive(workspaces.list, snapshot => new Set<SessionId>(snapshot.pinnedSessionIds))
const archivedSet = derive(workspaces.list, snapshot => new Set<SessionId>(snapshot.archivedSessionIds))
// Plugin-private facts the row actions and their overlay surfaces share:
// the pending rename request and the notice on display. Each business
// writes through its own injected callback and the surface reads through
// its bound hook.
const renameRequest = createSnapshotStore<SessionRenameRequest | null>(null)
const rowToast = createSnapshotStore<RowToastState | null>(null)
let toastSeq = 0
const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) }
const requestSessionRename = (sessionId: SessionId, currentTitle: string): void => {
renameRequest.set({ sessionId, currentTitle })
}
const unarchiveSession = (sessionId: SessionId): void => {
uiWorkspace.unarchiveSession(sessionId).catch((reason: unknown) => {
console.warn('session unarchive rejected:', reason)
})
}
const renameSession: SessionRenameDialogInjected['renameSession'] = async (sessionId, title) => {
const result = await sessions.using(
sessionId,
{ source: 'workspaceOperation' },
reference => reference.binding.session.rename(title),
)
if (!result.ok) throw new Error(result.error.message)
}
const pinInjected = (): PinSessionInjected => ({
hooks: { pinned: pinnedSet, archived: archivedSet },
// Pin failures surface as a notice: nothing else on the surface moves, so
// a silent failure would read as a dead action.
pinSession: (sessionId) => {
uiWorkspace.pinSession(sessionId).catch(() => { notify({ kind: 'pinFailed' }) })
},
unpinSession: (sessionId) => {
uiWorkspace.unpinSession(sessionId).catch(() => { notify({ kind: 'unpinFailed' }) })
},
})
const archiveInjected = (): ArchiveSessionInjected => ({
hooks: { archived: archivedSet },
// Archive preserves the log and the account position, so it needs no
// confirmation; the notice offers undo and the archived filter.
archiveSession: (sessionId) => {
uiWorkspace.archiveSession(sessionId).then(() => {
notify({ kind: 'archived', sessionId })
}).catch((reason: unknown) => {
console.warn('session archive rejected:', reason)
})
},
unarchiveSession,
})
const forkInjected = (): ForkSessionInjected => ({
forkSession: (sessionId) => {
uiWorkspace.forkSession(sessionId).catch(() => {
// Fork or child-title failure leaves the list as it was.
})
},
})
const renameInjected = (): RenameSessionInjected => ({ requestSessionRename })
const renameDialogInjected = (): SessionRenameDialogInjected => ({
hooks: { renameRequest },
settleSessionRename: () => { renameRequest.set(null) },
renameSession,
})
const rowToastInjected = (): RowToastInjected => ({
hooks: { toast: rowToast },
dismissToast: () => { rowToast.set(null) },
undoArchive: unarchiveSession,
showArchived: () => { viewInstance.actions.setArchivedFilter('show') },
})
const browserInjected = (): WorkspaceBrowserInjected => ({
// Explicit group actions keep their target; unscoped New Session inherits
// the current Session Workspace before the recent-Workspace fallback.
@@ -114,29 +206,14 @@ export function apply(ctx: Context): void {
open: openSession,
searchSessions,
searchResultLimit: sessions.searchResultLimit,
renameSession: async (sessionId, title) => {
const result = await sessions.using(
sessionId,
{ source: 'workspaceOperation' },
reference => reference.binding.session.rename(title),
)
if (!result.ok) throw new Error(result.error.message)
},
forkSession: (sessionId) => {
uiWorkspace.forkSession(sessionId)
.catch(() => {
// Fork or child-rename failure keeps the current selection.
})
},
requestSessionRename,
notifyArchivedNotOpenable: () => { notify({ kind: 'archivedNotOpenable' }) },
renameWorkspace: async (workspaceId, title) => { await workspaces.rename(workspaceId, title) },
deleteWorkspace: async (workspaceId) => { await workspaces.delete(workspaceId) },
insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {
await workspaces.insertBefore(workspaceId, beforeWorkspaceId)
},
archiveSession: async (sessionId) => { await uiWorkspace.archiveSession(sessionId) },
unarchiveSession: async (sessionId) => { await uiWorkspace.unarchiveSession(sessionId) },
pinSession: async (sessionId) => { await workspaces.pinSession(sessionId) },
unpinSession: async (sessionId) => { await workspaces.unpinSession(sessionId) },
createWorkspace: input => workspaces.create(input),
hooks: { directoryFlow: browserFlowSource, hostInfo },
})
@@ -151,14 +228,44 @@ export function apply(ctx: Context): void {
name: 'sidebar.workspaces',
children: {
'sidebar.workspaces.directoryFlow': { kind: 'single', scope: 'root' },
'sidebar.workspaces.session.menu.action': { kind: 'list', scope: 'root' },
// Every row entry reads the menu's open state through a hook bound
// from the row's render occurrence (the owner passes the state pair
// as hookContext).
'sidebar.workspaces.session.menu.item': {
kind: 'list', scope: 'root', inject: { hooks: { menuOpenState: menuOpenStateFactory } },
},
'sidebar.workspaces.session.row.action': { kind: 'list', scope: 'root' },
},
store: createWorkspaceViewStore(),
store: viewStore,
inject: browserInjected,
locale: NS,
},
WorkspaceBrowser,
))
// The shipped row actions take the same route as a plugin's: `slots.inject`
// waits for the browser registration above to declare each list, and the
// entries leave with it. Orders step by 100 so a plugin entry can land
// between them.
ctx.slots.inject('sidebar.workspaces.session.menu.item', function* () {
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'pin', order: 100, locale: NS, inject: pinInjected }, PinSessionMenuItem)
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'rename', order: 200, locale: NS, inject: renameInjected }, RenameSessionMenuItem)
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'fork', order: 300, locale: NS, inject: forkInjected }, ForkSessionMenuItem)
yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'archive', order: 400, locale: NS, inject: archiveInjected }, ArchiveSessionMenuItem)
})
ctx.slots.inject('sidebar.workspaces.session.row.action', function* () {
yield ctx.slots.register({ name: 'sidebar.workspaces.session.row.action', id: 'archive', order: 100, locale: NS, inject: archiveInjected }, ArchiveSessionRowButton)
yield ctx.slots.register({ name: 'sidebar.workspaces.session.row.action', id: 'pin', order: 200, locale: NS, inject: pinInjected }, PinSessionRowButton)
})
// The surfaces the actions raise live in the frame-wide layer: they must
// outlive the row menu the action sat in.
ctx.slots.inject('shell.overlay', function* () {
yield ctx.slots.register({
name: 'shell.overlay', id: 'workspace.session-rename', locale: NS, inject: renameDialogInjected,
}, SessionRenameDialog)
yield ctx.slots.register({
name: 'shell.overlay', id: 'workspace.row-toast', locale: NS, inject: rowToastInjected,
}, RowActionToast)
})
ctx.slots.inject('conversation.hero.workspace', () => ctx.slots.register(
{
name: 'conversation.hero.workspace',
@@ -16,6 +16,8 @@ import type {
} from '@deepseek-ai/dsh-api-workspace-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import { pinOrderAccounts, pinOrderSource } from './pin-order.ts'
import type { WorkspaceViewStoreActions } from './stores.ts'
interface MainSelection {
readonly sessionId?: SessionId
@@ -63,6 +65,19 @@ export interface UiWorkspace {
* @param sessionId - Session to unarchive.
*/
unarchiveSession(sessionId: SessionId): Promise<void>
/**
* Pin a Session on the Host, then lead it in its accounts' saved orders
* (its Workspace group or Ungrouped, and the flat list). The order write
* reads the memberships current at completion, so reorders that landed
* while the Host call was pending keep their positions.
* @param sessionId - Session to pin.
*/
pinSession(sessionId: SessionId): Promise<void>
/**
* Unpin a Session on the Host; saved positions stay as they are.
* @param sessionId - Session to unpin.
*/
unpinSession(sessionId: SessionId): Promise<void>
/**
* Open the Host-native directory picker.
* @returns the selected directory, or null when cancelled.
@@ -115,12 +130,14 @@ class UiWorkspaceService extends Service implements UiWorkspace {
* @param directoryPicker - the directory-picking Remote namespace.
* @param workspaces - pure Workspace Controller.
* @param sessions - pure Session Controller.
* @param view - the browser's viewing-store write set (one instance shared with its registration).
*/
constructor(
ctx: Context,
private readonly directoryPicker: ClientRemote['directoryPicker'],
private readonly workspaces: IWorkspaces,
private readonly sessions: ISessions,
private readonly view: Pick<WorkspaceViewStoreActions, 'pinSessionOrder'>,
) {
super(ctx, 'uiWorkspace')
ctx.effect(() => {
@@ -217,6 +234,20 @@ class UiWorkspaceService extends Service implements UiWorkspace {
await this.workspaces.unarchiveSession(sessionId)
}
async pinSession(sessionId: SessionId): Promise<void> {
await this.workspaces.pinSession(sessionId)
const { items, pinnedSessionIds, archivedSessionIds } = this.workspaces.list.getSnapshot()
this.view.pinSessionOrder(
sessionId,
pinOrderAccounts(items, sessionId),
pinOrderSource(items, this.sessions.list.getSnapshot(), { pinnedSessionIds, archivedSessionIds }),
)
}
async unpinSession(sessionId: SessionId): Promise<void> {
await this.workspaces.unpinSession(sessionId)
}
async pickDirectory(): Promise<string | null> {
const result = await this.directoryPicker.pick()
if (!result.ok) throw new Error(`directory picker failed: ${result.error.message}`)
@@ -0,0 +1,51 @@
/**
* The complete account memberships a Pin order write reconciles against,
* derived from the same Host snapshots the browser orders by, so the
* UiWorkspace service can complete the write without the browser in the loop.
*/
import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { FLAT_SESSION_ORDER_KEY } from './stores.ts'
import { owningGroupKey, sessionMemberIds, type SessionRowState, UNGROUPED_KEY } from './tree.ts'
/** What `pinSessionOrder` reconciles a pinned Session's accounts against. */
export interface PinOrderSource {
members: Readonly<Record<string, readonly SessionId[]>>
summaries: SessionListState['byId']
rowState: Pick<SessionRowState, 'pinnedSessionIds' | 'archivedSessionIds'>
}
/**
* Every account's complete membership: each Workspace, Ungrouped, and the flat list.
* @param workspaces - current Host Workspaces.
* @param list - current Session list snapshot.
* @param rowState - registry-global pin and archive sets.
* @returns the order source for one pin write.
*/
export function pinOrderSource(
workspaces: readonly WorkspaceView[],
list: SessionListState,
rowState: PinOrderSource['rowState'],
): PinOrderSource {
const accounted = new Set(workspaces.flatMap(workspace => workspace.sessionIds))
return {
members: Object.fromEntries([
...workspaces.map(workspace => [workspace.workspaceId, workspace.sessionIds] as const),
[UNGROUPED_KEY, list.ids.filter(id => list.byId[id] !== undefined && !accounted.has(id))],
[FLAT_SESSION_ORDER_KEY, sessionMemberIds(list)],
]),
summaries: list.byId,
rowState,
}
}
/**
* The accounts a pinned Session leads: its group (or Ungrouped) and the flat list.
* @param workspaces - current Host Workspaces.
* @param sessionId - the Session being pinned.
* @returns the account keys `pinSessionOrder` fronts.
*/
export function pinOrderAccounts(workspaces: readonly WorkspaceView[], sessionId: SessionId): readonly string[] {
return [owningGroupKey(workspaces, sessionId), FLAT_SESSION_ORDER_KEY]
}
@@ -2,23 +2,26 @@
* Workspace browser tree row components (figma Cell set 14:3080): pure presentational —
* all data and callbacks arrive via props. Hover swaps (folder->chevron,
* time->ellipsis, action buttons) are CSS-only, and a session row's clipped
* title is scrolled programmatically while the row is hovered. Row ... menus are
* visual-only except workspace Rename/Delete and the Session built-ins plus
* ordered plugin actions; the session and workspace hover cards are suppressed
* while a menu is open.
* title is scrolled programmatically while the row is hovered. Workspace row
* menus are visual-only except Rename/Delete. A Session row's "..." menu and
* its hover buttons are the `sidebar.workspaces.session.menu.item` and
* `sidebar.workspaces.session.row.action` lists, rendered through the
* browser's `renderSlot` with the menu's open state as the occurrence's hook
* context; this package's own actions are entries like any plugin's. The
* session and workspace hover cards are suppressed while a menu is open.
*/
import { useEffect, useRef, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import clsx from 'clsx'
import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
import {
HoverCard, IconAlarmClockOutlineRegular, IconArchiveOutlineRegular, IconBranchOutlineRegular,
IconEditOutlineRegular, IconEllipsisOutlineRegular, IconFolderCloseRegular, IconFolderOpenRegular,
IconNewChatOutlineRegular, IconPinFillRegular, IconPinOutlineRegular, IconTrashOutlineRegular,
HoverCard, IconAlarmClockOutlineRegular, IconArchiveOutlineRegular, IconEditOutlineRegular,
IconEllipsisOutlineRegular, IconFolderCloseRegular, IconFolderOpenRegular,
IconNewChatOutlineRegular, IconPinFillRegular, IconTrashOutlineRegular,
IconTriangleRightFillRegular, IconUnarchiveOutlineRegular, Menu, relativeTime, StateDot, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { StateDotState } from '@deepseek-ai/dsh-client-ui-primitives'
import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path'
import type { WorkspaceBrowserProps } from '../contract/slots.ts'
import type { MenuOpenState, WorkspaceBrowserProps } from '../contract/slots.ts'
import type { GroupNode, SearchResultNode, SessionNode } from '../tree.ts'
import css from './Rows.module.css'
@@ -461,10 +464,8 @@ export function SearchResultItem({ result, currentId, onOpen, onUnarchive, t }:
* @param props.currentId - selected session id (row highlight).
* @param props.now - epoch ms for relative-time formatting.
* @param props.onOpen - open a session by id.
* @param props.onRename - open the session rename dialog (id + current title).
* @param props.onFork - fork a session at its last completed turn.
* @param props.onArchive - archive a session by id.
* @param props.renderSlot - render ordered plugin actions after the built-in actions.
* @param props.onRenameRequest - open the rename dialog from a title double-click (id + current title).
* @param props.renderSlot - render the row's `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action` lists.
* @param props.onReveal - scroll this row into view after search navigation, then acknowledge it.
* @param props.drag - optional row-drag target wiring; blank rows cannot start a drag.
* @param props.flat - omit the empty status slot in the hierarchy-free flat list.
@@ -472,22 +473,14 @@ export function SearchResultItem({ result, currentId, onOpen, onUnarchive, t }:
* @returns the session row.
*/
export function SessionNodeItem({
node, currentId, now, onOpen, onRename, onFork, onArchive, onUnarchive, onPin, renderSlot, onReveal, drag, flat = false, t,
node, currentId, now, onOpen, onRenameRequest, renderSlot, onReveal, drag, flat = false, t,
}: {
node: SessionNode
currentId: string | undefined
now: number
onOpen: (id: SessionNode['id']) => void
/** Open the browser-owned session rename dialog (row menu action). */
onRename: (id: SessionNode['id'], currentTitle: string) => void
/** Fork a session at its last completed turn (row menu action). */
onFork: (id: SessionNode['id']) => void
/** Archive this session (row menu action; commits without a dialog). */
onArchive: (id: SessionNode['id']) => void
/** Unarchive this session (row menu action on archived rows). */
onUnarchive: (id: SessionNode['id']) => void
/** Pin or unpin this session (row menu action; `pin` false unpins). */
onPin: (id: SessionNode['id'], pin: boolean) => void
/** Open the rename dialog from a title double-click (id + current title). */
onRenameRequest: (id: SessionNode['id'], currentTitle: string) => void
/** Scroll this row into view after search navigation, then acknowledge it. */
onReveal?: (() => void) | undefined
/** Present on reorderable-list rows so every row can remain a drop target. */
@@ -495,7 +488,7 @@ export function SessionNodeItem({
/** The row is rendered without a parent Workspace header. */
flat?: boolean | undefined
t: RowTranslate
} & PropsRenderSlots<'sidebar.workspaces.session.menu.action'>) {
} & PropsRenderSlots<'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action'>) {
const row = node
const title = displayTitle(node, t)
const selected = node.id === currentId
@@ -507,6 +500,8 @@ export function SessionNodeItem({
// their drop targets to fellow pinned rows.
const draggable = drag !== undefined && !row.blank && !row.archived
const [menuOpen, setMenuOpen] = useState(false)
// The menu's open state, bound into the row entries' `useMenuOpenState` hook.
const menuOpenState = useMemo((): MenuOpenState => [menuOpen, setMenuOpen], [menuOpen])
const rowRef = useRef<HTMLDivElement>(null)
const titleRef = useRef<HTMLSpanElement>(null)
useEffect(() => {
@@ -514,25 +509,6 @@ export function SessionNodeItem({
rowRef.current?.scrollIntoView({ block: 'nearest' })
onReveal()
}, [onReveal])
// Archive hides the row through the registry-global archive set and never
// touches the session log, so it is not styled as destructive and needs no
// confirmation dialog. Archived rows swap pin/archive for unarchive.
const sessionMenuItems = row.archived
? [
{ id: 'rename', label: t('rename'), icon: <IconEditOutlineRegular /> },
{ id: 'fork', label: t('menu.fork'), icon: <IconBranchOutlineRegular /> },
{ id: 'unarchive', label: t('menu.unarchiveSession'), icon: <IconUnarchiveOutlineRegular size={14} /> },
]
: [
{
id: row.pinned ? 'unpin' : 'pin',
label: t(row.pinned ? 'menu.unpinSession' : 'menu.pinSession'),
icon: row.pinned ? <IconPinFillRegular /> : <IconPinOutlineRegular />,
},
{ id: 'rename', label: t('rename'), icon: <IconEditOutlineRegular /> },
{ id: 'fork', label: t('menu.fork'), icon: <IconBranchOutlineRegular /> },
{ id: 'archive', label: t('menu.archiveSession'), icon: <IconArchiveOutlineRegular size={14} /> },
]
// Figma session cell: pad 8, status slot 16, then a 4px title gap.
const ownRow = (
<div
@@ -590,7 +566,7 @@ export function SessionNodeItem({
className={css.title}
onDoubleClick={row.blank
? undefined
: (e) => { e.stopPropagation(); onRename(node.id, row.title) }}
: (e) => { e.stopPropagation(); onRenameRequest(node.id, row.title) }}
>
{title}
</span>
@@ -615,16 +591,6 @@ export function SessionNodeItem({
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={sessionMenuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'rename') onRename(node.id, row.title)
if (id === 'fork') onFork(node.id)
if (id === 'archive') onArchive(node.id)
if (id === 'unarchive') onUnarchive(node.id)
if (id === 'pin') onPin(node.id, true)
if (id === 'unpin') onPin(node.id, false)
}}
portal
closeOnPointerLeave
anchor={(
@@ -638,38 +604,13 @@ export function SessionNodeItem({
</button>
)}
>
{renderSlot('sidebar.workspaces.session.menu.action', {
sessionId: node.id,
displayTitle: row.title,
})}
{renderSlot(
'sidebar.workspaces.session.menu.item',
{ sessionId: node.id, displayTitle: row.title },
{ hookContext: menuOpenState },
)}
</Menu>
<Tooltip label={row.archived ? t('actions.unarchive') : t('actions.archive')} side="bottom" align="end" delayMs={500}>
<button
type="button"
className={css.iconButton}
aria-label={row.archived ? t('menu.unarchiveSession') : t('menu.archiveSession')}
onClick={(e) => {
e.stopPropagation()
if (row.archived) onUnarchive(node.id)
else onArchive(node.id)
}}
>
{row.archived ? <IconUnarchiveOutlineRegular size={14} /> : <IconArchiveOutlineRegular size={14} />}
</button>
</Tooltip>
{/* Rightmost so it lands where the rest-state pin marker sits. */}
{!row.archived && (
<Tooltip label={row.pinned ? t('actions.unpin') : t('actions.pin')} side="bottom" align="end" delayMs={500}>
<button
type="button"
className={css.iconButton}
aria-label={row.pinned ? t('menu.unpinSession') : t('menu.pinSession')}
onClick={(e) => { e.stopPropagation(); onPin(node.id, !row.pinned) }}
>
{row.pinned ? <IconPinFillRegular size={14} /> : <IconPinOutlineRegular size={14} />}
</button>
</Tooltip>
)}
{renderSlot('sidebar.workspaces.session.row.action', { sessionId: node.id, displayTitle: row.title })}
</span>
)}
</div>
@@ -7,8 +7,12 @@
* rail entry path, each requesting expansion through the owner share. Adding
* is the header button's one action, so it raises the directory flow with no
* menu in between; the flow and its error dialog live in WorkspacePicker
* (same package — direct composition, no slot between them). Session row
* menus render the browser-owned action list after their built-in actions.
* (same package — direct composition, no slot between them). A Session row's
* "..." menu and hover buttons are the `sidebar.workspaces.session.menu.item`
* and `sidebar.workspaces.session.row.action` lists rendered through this
* entry's `renderSlot`; the actions in them, this package's own included,
* are slot entries with their own behavior, so this component threads no
* action callbacks and hosts no action surface.
*/
import { type CSSProperties, type ReactNode, useEffect, useMemo, useRef, useState } from 'react'
import clsx from 'clsx'
@@ -16,8 +20,8 @@ import {
Button, IconArchiveCheckOutlineRegular, IconArchiveOutlineRegular,
IconChevronsUpDownOutlineRegular, IconClockOutlineRegular, IconCloseFillRegular,
IconFlatListOutlineRegular, IconFolderCloseRegular, IconProjectAddOutlineRegular,
IconSearchOutlineRegular, IconSlidersTwoOutlineRegular, IconWarningOutlineRegular,
IconWorkspaceTreeOutlineRegular, Menu, Modal, Toast, Tooltip,
IconSearchOutlineRegular, IconSlidersTwoOutlineRegular,
IconWorkspaceTreeOutlineRegular, Menu, Modal, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type {
SessionListState, SessionSearchResultItem,
@@ -103,27 +107,16 @@ function useNativeDragAcceptance(active: boolean): void {
}
/** Grouping, ordering, and archived-filter menu; own open state so it resets with the wide chrome. */
function ViewOptionsMenu({ groupBy, orderBy, archivedFilter, onGroupPick, onOrderPick, onArchivedFilterPick, openSeq, t }: {
function ViewOptionsMenu({ groupBy, orderBy, archivedFilter, onGroupPick, onOrderPick, onArchivedFilterPick, t }: {
groupBy: SessionGroupBy
orderBy: SessionOrderBy
archivedFilter: ArchivedFilter
onGroupPick: (mode: SessionGroupBy) => void
onOrderPick: (mode: SessionOrderBy) => void
onArchivedFilterPick: (filter: ArchivedFilter) => void
/** Each bump above zero opens the menu (the archive toast's filter action). */
openSeq?: number
t: WorkspaceBrowserProps['t']
}) {
const [open, setOpen] = useState(false)
// Seeded with the mount-time value: a chrome remount (e.g. window resize
// through the rail breakpoint) must not replay an old toast-action bump.
const seenOpenSeq = useRef(openSeq ?? 0)
useEffect(() => {
if (openSeq !== undefined && openSeq > seenOpenSeq.current) {
seenOpenSeq.current = openSeq
setOpen(true)
}
}, [openSeq])
return (
<Menu
open={open}
@@ -179,9 +172,6 @@ function ViewOptionsMenu({ groupBy, orderBy, archivedFilter, onGroupPick, onOrde
)
}
/** Hold for the actionable post-archive toast: two buttons need a longer read-and-react window than a plain notice. */
const ARCHIVE_TOAST_HOLD_MS = 6000
/** In-flight root-row drag: source identity plus the current insert marker. */
interface DragState {
/** Workspace id, or {@link UNGROUPED_KEY} for the browser-local loose-session account. */
@@ -231,9 +221,9 @@ function workspaceGroupHalf(e: { clientY: number; currentTarget: HTMLElement }):
type SessionTreeProps = Pick<
WorkspaceBrowserProps,
'useSessionStatus' | 'startSession' | 'open' | 'forkSession'
'useSessionStatus' | 'startSession' | 'open'
| 'insertWorkspaceBefore' | 't' | 'usePanelInfo'
> & PropsRenderSlots<'sidebar.workspaces.session.menu.action'> & {
> & PropsRenderSlots<'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action'> & {
/** Always-mounted Session list snapshot. */
list: SessionListState
/** Host account home for POSIX hover-path abbreviation. */
@@ -260,14 +250,8 @@ type SessionTreeProps = Pick<
onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void
/** Open the browser-owned delete-confirmation dialog for a real Workspace group. */
onDeleteRequest: (workspaceId: WorkspaceId, currentTitle: string) => void
/** Open the browser-owned session rename dialog. */
onSessionRename: (sessionId: SessionNode['id'], currentTitle: string) => void
/** Archive a Session; the selected filter determines its visibility. */
onSessionArchive: (sessionId: SessionNode['id']) => void
/** Unarchive a session (row menu action on archived rows). */
onSessionUnarchive: (sessionId: SessionNode['id']) => void
/** Pin or unpin a session (row menu action; `pin` false unpins). */
onSessionPin: (sessionId: SessionNode['id'], pin: boolean) => void
/** Open the rename dialog from a row title double-click. */
onSessionRenameRequest: (sessionId: SessionNode['id'], currentTitle: string) => void
/** One Session chosen from search that must be exposed and scrolled into view. */
revealSessionId?: SessionId | undefined
/** Acknowledge that the chosen Session row has been revealed. */
@@ -276,10 +260,10 @@ type SessionTreeProps = Pick<
/** The scrolling session tree; unmounting drops the sessions subscription and expand-all state. */
function SessionTree({
list, useSessionStatus, startSession, open, forkSession, workspaces, ungroupedSessionIds,
list, useSessionStatus, startSession, open, workspaces, ungroupedSessionIds,
rowState,
workspaceReady, animationResetKey, usePanelInfo,
onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onSessionUnarchive, onSessionPin,
onRenameRequest, onDeleteRequest, onSessionRenameRequest,
renderSlot,
insertWorkspaceBefore,
nestWorkspaces, groupExpansion, setGroupExpanded,
@@ -560,11 +544,7 @@ function SessionTree({
currentId={current}
now={now}
onOpen={open}
onRename={onSessionRename}
onFork={forkSession}
onArchive={onSessionArchive}
onUnarchive={onSessionUnarchive}
onPin={onSessionPin}
onRenameRequest={onSessionRenameRequest}
renderSlot={renderSlot}
onReveal={node.id === revealSessionId && group.key === revealGroup
? () => { onSessionRevealed(node.id) }
@@ -614,8 +594,7 @@ function SessionTree({
/** The flat "In one list" body: every session is one draggable top-level row. */
function FlatList({
list, sessionIds, rowState, useSessionStatus, open, forkSession, onSessionRename, onSessionArchive,
onSessionUnarchive, onSessionPin,
list, sessionIds, rowState, useSessionStatus, open, onSessionRenameRequest,
renderSlot,
usePanelInfo, setSessionOrder, workspaceReady, animationResetKey,
revealSessionId, onSessionRevealed, t,
@@ -623,11 +602,7 @@ function FlatList({
SessionTreeProps,
| 'useSessionStatus'
| 'open'
| 'forkSession'
| 'onSessionRename'
| 'onSessionArchive'
| 'onSessionUnarchive'
| 'onSessionPin'
| 'onSessionRenameRequest'
| 'renderSlot'
| 'usePanelInfo'
| 'setSessionOrder'
@@ -684,11 +659,7 @@ function FlatList({
currentId={currentId}
now={now}
onOpen={open}
onRename={onSessionRename}
onFork={forkSession}
onArchive={onSessionArchive}
onUnarchive={onSessionUnarchive}
onPin={onSessionPin}
onRenameRequest={onSessionRenameRequest}
renderSlot={renderSlot}
onReveal={node.id === revealSessionId
? () => { onSessionRevealed(node.id) }
@@ -841,15 +812,12 @@ export function WorkspaceBrowser({
actions,
startSession,
open,
renameSession,
forkSession,
requestSessionRename,
notifyArchivedNotOpenable,
renameWorkspace,
deleteWorkspace,
insertWorkspaceBefore,
archiveSession,
unarchiveSession,
pinSession,
unpinSession,
createWorkspace,
searchSessions,
searchResultLimit,
@@ -876,23 +844,11 @@ export function WorkspaceBrowser({
const archivedFilter = useStore(s => s.archivedFilter ?? 'default')
const groupExpansion = useStore(s => s.groupExpansion)
const sessionOrderByAccount = useStore(s => s.sessionOrderByAccount)
// Each bump opens the view-options menu (the archive toast's filter action).
const [viewOptionsOpenSeq, setViewOptionsOpenSeq] = useState(0)
// One transient banner at a time; the seq keys remounts so a repeat message restarts its hold.
const [toast, setToast] = useState<{
text: string
seq: number
tone: 'warning' | 'success'
actions?: readonly { label: string; onClick: () => void }[]
} | null>(null)
const showToast = (text: string): void => {
setToast(current => ({ text, seq: (current?.seq ?? 0) + 1, tone: 'warning' }))
}
// Archived sessions are not openable: the row stays visible under the
// filter but a click explains instead of navigating.
const guardedOpen = (sessionId: SessionId): void => {
if (archivedSessionIds.includes(sessionId)) {
showToast(t('toast.archivedNotOpenable'))
notifyArchivedNotOpenable()
return
}
open(sessionId)
@@ -952,9 +908,6 @@ export function WorkspaceBrowser({
[UNGROUPED_KEY, orderedUngroupedSessionIds] as const,
[FLAT_SESSION_ORDER_KEY, orderedFlatSessionIds] as const,
]), [orderedFlatSessionIds, orderedUngroupedSessionIds, orderedWorkspaces])
const pinOrderSource = { workspaces, ungroupedMemberIds, flatMemberIds, summaries: list.byId, rowState: orderState }
const latestPinOrder = useRef(pinOrderSource)
latestPinOrder.current = pinOrderSource
useEffect(() => {
if (workspacePhase !== 'ready') return
actions.retainAccountKeys([
@@ -1024,7 +977,7 @@ export function WorkspaceBrowser({
const openSearchResult = (sessionId: SessionId): void => {
if (archivedSessionIds.includes(sessionId)) {
showToast(t('toast.archivedNotOpenable'))
notifyArchivedNotOpenable()
return
}
setRevealSessionId(sessionId)
@@ -1139,88 +1092,13 @@ export function WorkspaceBrowser({
})
}
// Session rename dialog (same browser-owned pattern as workspace rename;
// sessions have no client-side name-conflict rule — the host normalizes).
// Unlike workspace rename, an unchanged title is NOT blocked: confirming
// the current automatic title is the gesture that pins it.
const [sessionRenameTarget, setSessionRenameTarget] = useState<{ sessionId: SessionNode['id']; currentTitle: string } | null>(null)
const [sessionRenameDraft, setSessionRenameDraft] = useState('')
const [sessionRenaming, setSessionRenaming] = useState(false)
const [sessionRenameError, setSessionRenameError] = useState<string | null>(null)
const sessionRenameTrimmed = sessionRenameDraft.trim()
const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === '' || sessionRenameTarget === null
const closeSessionRename = () => {
if (sessionRenaming) return
setSessionRenameTarget(null)
setSessionRenameError(null)
}
const confirmSessionRename = () => {
if (sessionRenameBlocked) return
setSessionRenaming(true)
setSessionRenameError(null)
renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => {
setSessionRenaming(false)
setSessionRenameTarget(null)
}).catch((reason: unknown) => {
setSessionRenaming(false)
setSessionRenameError(reason instanceof Error ? reason.message : String(reason))
})
}
const onSessionRename = (sessionId: SessionNode['id'], currentTitle: string) => {
setSessionRenameTarget({ sessionId, currentTitle })
setSessionRenameDraft(currentTitle)
setSessionRenameError(null)
}
// Archive preserves the log and account position, so it needs no confirmation.
// The selected filter determines visibility after the archive-set echo.
const onSessionArchive = (sessionId: SessionNode['id']) => {
archiveSession(sessionId).then(() => {
setToast(current => ({
text: t('toast.archived'),
seq: (current?.seq ?? 0) + 1,
tone: 'success',
actions: [
{ label: t('toast.archivedUndo'), onClick: () => { setToast(null); onSessionUnarchive(sessionId) } },
{
prefix: t('toast.archivedOr'),
label: t('toast.archivedFilter'),
onClick: () => { setToast(null); setViewOptionsOpenSeq(seq => seq + 1) },
},
],
}))
}).catch((reason: unknown) => {
console.warn('session archive rejected:', reason)
})
}
// The search results' restore button; the row actions own the rest of the
// Session verbs as slot entries.
const onSessionUnarchive = (sessionId: SessionNode['id']) => {
unarchiveSession(sessionId).catch((reason: unknown) => {
console.warn('session unarchive rejected:', reason)
})
}
// Pin failures surface as a toast: unlike archive, nothing else on the
// surface moves, so a silent failure would read as a dead menu action.
const onSessionPin = (sessionId: SessionNode['id'], pin: boolean) => {
(pin ? pinSession(sessionId) : unpinSession(sessionId)).then(() => {
if (!pin) return
const source = latestPinOrder.current
actions.pinSessionOrder(
sessionId,
[owningGroupKey(source.workspaces, sessionId), FLAT_SESSION_ORDER_KEY],
{
members: Object.fromEntries([
...source.workspaces.map(workspace => [workspace.workspaceId, workspace.sessionIds] as const),
[UNGROUPED_KEY, source.ungroupedMemberIds],
[FLAT_SESSION_ORDER_KEY, source.flatMemberIds],
]),
summaries: source.summaries,
rowState: source.rowState,
},
)
}).catch(() => {
showToast(t(pin ? 'toast.pinFailed' : 'toast.unpinFailed'))
})
}
// Delete dialog is separate from the row so a successful removal can
// unmount that row without tearing down the in-flight confirmation state.
@@ -1331,7 +1209,6 @@ export function WorkspaceBrowser({
onGroupPick={actions.setGroupBy}
onOrderPick={(mode) => { actions.setOrderBy(mode, activeSessionOrders) }}
onArchivedFilterPick={actions.setArchivedFilter}
openSeq={viewOptionsOpenSeq}
t={t}
/>
)}
@@ -1421,9 +1298,8 @@ export function WorkspaceBrowser({
workspaceReady={workspaceReady}
animationResetKey={`${groupBy}/${orderBy}/${archivedFilter}`}
useSessionStatus={useSessionStatus}
open={guardedOpen} forkSession={forkSession}
onSessionRename={onSessionRename} onSessionArchive={onSessionArchive}
onSessionUnarchive={onSessionUnarchive} onSessionPin={onSessionPin}
open={guardedOpen}
onSessionRenameRequest={requestSessionRename}
renderSlot={renderSlot}
setSessionOrder={saveSessionOrder}
revealSessionId={revealSessionId}
@@ -1436,12 +1312,8 @@ export function WorkspaceBrowser({
usePanelInfo={usePanelInfo}
list={list}
useSessionStatus={useSessionStatus}
onSessionRename={onSessionRename}
onSessionArchive={onSessionArchive}
onSessionUnarchive={onSessionUnarchive}
onSessionPin={onSessionPin}
onSessionRenameRequest={requestSessionRename}
renderSlot={renderSlot}
forkSession={forkSession}
workspaces={orderedWorkspaces}
ungroupedSessionIds={orderedUngroupedSessionIds}
workspaceReady={workspaceReady}
@@ -1506,37 +1378,6 @@ export function WorkspaceBrowser({
{renameError !== null && <div className={css.renameError} role="alert">{renameError}</div>}
</Modal>
<Modal
open={sessionRenameTarget !== null}
onClose={closeSessionRename}
closeLabel={t('close')}
title={t('rename.session.title')}
footer={(
<>
<Button variant="outline" disabled={sessionRenaming} onClick={closeSessionRename}>{t('cancel')}</Button>
<Button variant="primary" disabled={sessionRenameBlocked} onClick={confirmSessionRename}>{t('rename')}</Button>
</>
)}
>
<input
className={css.renameInput}
value={sessionRenameDraft}
aria-label={t('field.sessionName')}
autoFocus
disabled={sessionRenaming}
onFocus={(e) => { e.target.select() }}
onChange={(e) => { setSessionRenameDraft(e.target.value); setSessionRenameError(null) }}
onCompositionStart={() => { composingRef.current = true }}
onCompositionEnd={() => { composingRef.current = false }}
onKeyDown={(e) => {
if (e.key === 'Enter' && !composingRef.current) {
e.preventDefault()
confirmSessionRename()
}
}}
/>
{sessionRenameError !== null && <div className={css.renameError} role="alert">{sessionRenameError}</div>}
</Modal>
<Modal
open={deleteTarget !== null}
onClose={closeDelete}
@@ -1562,17 +1403,6 @@ export function WorkspaceBrowser({
{deleting && <div className={css.deleteStatus} role="status">{t('delete.pending')}</div>}
{deleteError !== null && <div className={css.renameError} role="alert">{deleteError}</div>}
</Modal>
{toast !== null && (
<Toast
key={`toast-${String(toast.seq)}`}
text={toast.text}
{...toast.tone === 'success'
? { tone: 'success' as const }
: { icon: <IconWarningOutlineRegular /> }}
{...toast.actions === undefined ? {} : { actions: toast.actions, holdMs: ARCHIVE_TOAST_HOLD_MS }}
onDone={() => { setToast(null) }}
/>
)}
</div>
)
}
@@ -0,0 +1,61 @@
/**
* The archive action: a `sidebar.workspaces.session.menu.item` row and a
* `sidebar.workspaces.session.row.action` button over one injected behavior.
* The same entries restore an archived row; the notice a successful archive
* raises and the diagnostics for Host rejections live in the injected
* callbacks, not here.
*/
import {
IconArchiveOutlineRegular, IconUnarchiveOutlineRegular, MenuItemButton, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { ArchiveSessionInjected, SessionMenuItemProps, SessionRowActionProps } from '../contract/slots.ts'
import css from '../rows/Rows.module.css'
/**
* Menu row (order 400): archive, or restore an archived row.
* @param props - owner share, the archive share, and the menu open state.
* @returns the row.
*/
export function ArchiveSessionMenuItem({
sessionId, useArchived, useMenuOpenState, archiveSession, unarchiveSession, t,
}: SessionMenuItemProps<ArchiveSessionInjected>) {
const [, setMenuOpen] = useMenuOpenState()
const archived = useArchived(set => set.has(sessionId))
return (
<MenuItemButton
icon={archived ? <IconUnarchiveOutlineRegular size={14} /> : <IconArchiveOutlineRegular size={14} />}
onSelect={() => {
setMenuOpen(false)
;(archived ? unarchiveSession : archiveSession)(sessionId)
}}
>
{t(archived ? 'menu.unarchiveSession' : 'menu.archiveSession')}
</MenuItemButton>
)
}
/**
* Hover button (order 100): archive, or restore an archived row.
* @param props - owner share and the archive share.
* @returns the button.
*/
export function ArchiveSessionRowButton({
sessionId, useArchived, archiveSession, unarchiveSession, t,
}: SessionRowActionProps<ArchiveSessionInjected>) {
const archived = useArchived(set => set.has(sessionId))
return (
<Tooltip label={t(archived ? 'actions.unarchive' : 'actions.archive')} side="bottom" align="end" delayMs={500}>
<button
type="button"
className={css.iconButton}
aria-label={t(archived ? 'menu.unarchiveSession' : 'menu.archiveSession')}
onClick={(e) => {
e.stopPropagation()
;(archived ? unarchiveSession : archiveSession)(sessionId)
}}
>
{archived ? <IconUnarchiveOutlineRegular size={14} /> : <IconArchiveOutlineRegular size={14} />}
</button>
</Tooltip>
)
}
@@ -0,0 +1,24 @@
/** The fork action: one `sidebar.workspaces.session.menu.item` row. */
import { IconBranchOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ForkSessionInjected, SessionMenuItemProps } from '../contract/slots.ts'
/**
* Menu row (order 300): fork at the Session's last completed turn; the child
* arrives through the Host list beside its source.
* @param props - owner share, menu open state, and the fork share.
* @returns the row.
*/
export function ForkSessionMenuItem({ sessionId, useMenuOpenState, forkSession, t }: SessionMenuItemProps<ForkSessionInjected>) {
const [, setMenuOpen] = useMenuOpenState()
return (
<MenuItemButton
icon={<IconBranchOutlineRegular />}
onSelect={() => {
setMenuOpen(false)
forkSession(sessionId)
}}
>
{t('menu.fork')}
</MenuItemButton>
)
}
@@ -0,0 +1,72 @@
/**
* The pin action: a `sidebar.workspaces.session.menu.item` row and a
* `sidebar.workspaces.session.row.action` button over one injected behavior.
* Pin and archive are mutually exclusive on the Host, so the action reads both
* sets and does not offer itself on an archived row; what a pin does beyond
* the Host call (fronting the Session in its saved orders, the failure
* notice) lives in the injected callbacks, not here.
*/
import {
IconPinFillRegular, IconPinOutlineRegular, MenuItemButton, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { PinSessionInjected, SessionMenuItemProps, SessionRowActionProps } from '../contract/slots.ts'
import css from '../rows/Rows.module.css'
type PinState = Pick<SessionMenuItemProps<PinSessionInjected>, 'sessionId' | 'usePinned' | 'useArchived'>
/** The row's pin and archive membership, one Set lookup each. */
function usePinState({ sessionId, usePinned, useArchived }: PinState) {
return {
pinned: usePinned(pinned => pinned.has(sessionId)),
archived: useArchived(archived => archived.has(sessionId)),
}
}
/**
* Menu row (order 100): pin or unpin by the row's current state; absent on archived rows.
* @param props - owner share, the pin share, and the menu open state.
* @returns the row, or null for an archived Session.
*/
export function PinSessionMenuItem(props: SessionMenuItemProps<PinSessionInjected>) {
const { sessionId, useMenuOpenState, pinSession, unpinSession, t } = props
const [, setMenuOpen] = useMenuOpenState()
const { pinned, archived } = usePinState(props)
if (archived) return null
return (
<MenuItemButton
icon={pinned ? <IconPinFillRegular /> : <IconPinOutlineRegular />}
onSelect={() => {
setMenuOpen(false)
;(pinned ? unpinSession : pinSession)(sessionId)
}}
>
{t(pinned ? 'menu.unpinSession' : 'menu.pinSession')}
</MenuItemButton>
)
}
/**
* Hover button (order 200, rightmost: it lands where the rest-state pin marker sits); absent on archived rows.
* @param props - owner share and the pin share.
* @returns the button, or null for an archived Session.
*/
export function PinSessionRowButton(props: SessionRowActionProps<PinSessionInjected>) {
const { sessionId, pinSession, unpinSession, t } = props
const { pinned, archived } = usePinState(props)
if (archived) return null
return (
<Tooltip label={t(pinned ? 'actions.unpin' : 'actions.pin')} side="bottom" align="end" delayMs={500}>
<button
type="button"
className={css.iconButton}
aria-label={t(pinned ? 'menu.unpinSession' : 'menu.pinSession')}
onClick={(e) => {
e.stopPropagation()
;(pinned ? unpinSession : pinSession)(sessionId)
}}
>
{pinned ? <IconPinFillRegular size={14} /> : <IconPinOutlineRegular size={14} />}
</button>
</Tooltip>
)
}
@@ -0,0 +1,122 @@
/**
* The rename action: a `sidebar.workspaces.session.menu.item` row that raises
* the rename request, and the `shell.overlay` dialog entry that answers it.
* The dialog lives outside the row menu because the row unmounts with the
* menu; the browser raises the same request from a title double-click.
*/
import { useRef, useState } from 'react'
import { Button, IconEditOutlineRegular, MenuItemButton, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
import type {
RenameSessionInjected, SessionMenuItemProps, SessionRenameDialogInjected, SessionRenameDialogProps, SessionRenameRequest,
} from '../contract/slots.ts'
import css from '../rows/WorkspaceBrowser.module.css'
/**
* Menu row (order 200): ask for the rename dialog, seeded with the row's current title.
* @param props - owner share, menu open state, and the rename share.
* @returns the row.
*/
export function RenameSessionMenuItem({
sessionId, displayTitle, useMenuOpenState, requestSessionRename, t,
}: SessionMenuItemProps<RenameSessionInjected>) {
const [, setMenuOpen] = useMenuOpenState()
return (
<MenuItemButton
icon={<IconEditOutlineRegular />}
onSelect={() => {
setMenuOpen(false)
requestSessionRename(sessionId, displayTitle)
}}
>
{t('rename')}
</MenuItemButton>
)
}
/**
* The `shell.overlay` entry: nothing while no rename is requested, otherwise
* one dialog per request (keyed by the Session, so a new request starts a
* fresh draft). Sessions have no client-side name-conflict rule (the host
* normalizes), and unlike Workspace rename an unchanged title is NOT
* blocked: confirming the current automatic title is the gesture that pins it.
* @param props - the request hook, its settlement, the rename hop, and the locale seat.
* @returns the open dialog, or null.
*/
export function SessionRenameDialog({ useRenameRequest, settleSessionRename, renameSession, t }: SessionRenameDialogProps) {
const request = useRenameRequest(pending => pending)
if (request === null) return null
return (
<RenameForm
key={request.sessionId}
request={request}
renameSession={renameSession}
onSettle={settleSessionRename}
t={t}
/>
)
}
/** One request's dialog: the draft seeds from the request on mount; in-flight and error state die with it. */
function RenameForm({ request, renameSession, onSettle, t }: {
request: SessionRenameRequest
renameSession: SessionRenameDialogInjected['renameSession']
onSettle: () => void
t: SessionRenameDialogProps['t']
}) {
const [draft, setDraft] = useState(request.currentTitle)
const [renaming, setRenaming] = useState(false)
const [error, setError] = useState<string | null>(null)
// IME composition: Enter that commits a composition must not submit.
const composingRef = useRef(false)
const trimmed = draft.trim()
const blocked = renaming || trimmed === ''
const close = () => {
if (renaming) return
onSettle()
}
const confirm = () => {
if (blocked) return
setRenaming(true)
setError(null)
renameSession(request.sessionId, trimmed).then(() => {
setRenaming(false)
onSettle()
}).catch((reason: unknown) => {
setRenaming(false)
setError(reason instanceof Error ? reason.message : String(reason))
})
}
return (
<Modal
open
onClose={close}
closeLabel={t('close')}
title={t('rename.session.title')}
footer={(
<>
<Button variant="outline" disabled={renaming} onClick={close}>{t('cancel')}</Button>
<Button variant="primary" disabled={blocked} onClick={confirm}>{t('rename')}</Button>
</>
)}
>
<input
className={css.renameInput}
value={draft}
aria-label={t('field.sessionName')}
autoFocus
disabled={renaming}
onFocus={(e) => { e.target.select() }}
onChange={(e) => { setDraft(e.target.value); setError(null) }}
onCompositionStart={() => { composingRef.current = true }}
onCompositionEnd={() => { composingRef.current = false }}
onKeyDown={(e) => {
if (e.key === 'Enter' && !composingRef.current) {
e.preventDefault()
confirm()
}
}}
/>
{error !== null && <div className={css.renameError} role="alert">{error}</div>}
</Modal>
)
}
@@ -0,0 +1,47 @@
/**
* The `shell.overlay` entry that shows the row actions' notices: the archived
* notice with its undo and "show archived" actions, pin failures, and the
* browser's "archived rows cannot be opened" notice. One notice at a time;
* a parent rerender does not extend its hold.
*/
import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import type { RowToastProps } from '../contract/slots.ts'
/** Hold for the actionable archived notice: two buttons need a longer read-and-react window than a plain notice. */
const ARCHIVED_TOAST_HOLD_MS = 6000
/**
* @param props - the notice hook, its dismissal, the two archived-notice actions, and the locale seat.
* @returns the notice on display, or null.
*/
export function RowActionToast({ useToast, dismissToast, undoArchive, showArchived, t }: RowToastProps) {
const toast = useToast(current => current)
if (toast === null) return null
if (toast.kind === 'archived') {
const { sessionId } = toast
return (
<Toast
key={`toast-${String(toast.seq)}`}
text={t('toast.archived')}
tone="success"
holdMs={ARCHIVED_TOAST_HOLD_MS}
actions={[
{ label: t('toast.archivedUndo'), onClick: () => { dismissToast(); undoArchive(sessionId) } },
{ prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), onClick: () => { dismissToast(); showArchived() } },
]}
onDone={dismissToast}
/>
)
}
const text = toast.kind === 'pinFailed'
? t('toast.pinFailed')
: toast.kind === 'unpinFailed' ? t('toast.unpinFailed') : t('toast.archivedNotOpenable')
return (
<Toast
key={`toast-${String(toast.seq)}`}
text={text}
icon={<IconWarningOutlineRegular />}
onDone={dismissToast}
/>
)
}
@@ -0,0 +1,26 @@
/** Derived observable sources for the row actions' injected hooks. */
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
/**
* Project one observable into another, recomputing only when the source
* snapshot changes identity, so consumers that select from the projection
* (a Set lookup per row) never rebuild it per read.
* @param source - the observable to project.
* @param project - pure projection of one source snapshot.
* @returns the projected observable, subscribing through the source.
*/
export function derive<S, T>(source: HostObservable<S>, project: (snapshot: S) => T): HostObservable<T> {
let seen: S | undefined
let value: T | undefined
return {
getSnapshot: () => {
const snapshot = source.getSnapshot()
if (value === undefined || snapshot !== seen) {
seen = snapshot
value = project(snapshot)
}
return value
},
subscribe: listener => source.subscribe(listener),
}
}
@@ -128,3 +128,6 @@ export function createWorkspaceViewStore(): EngineStoreHandle<WorkspaceViewState
},
})
}
/** The bound write set of one viewing-store instance (what the UiWorkspace service drives). */
export type WorkspaceViewStoreActions = ReturnType<ReturnType<typeof createWorkspaceViewStore>['create']>['actions']
@@ -1,14 +1,52 @@
import { Context } from '@deepseek-ai/cordis'
import { describe, expect, it, vi } from 'vitest'
import type {
SessionListState, SessionReference, SessionSummary,
} from '@deepseek-ai/dsh-api-session-controller/client'
import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client'
import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client'
import {
type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected,
type RenameSessionInjected, type RowToastInjected, type SessionRenameDialogInjected, type WorkspaceViewStoreHandle,
} from '../src/client/contract/slots.ts'
import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx'
import { ArchiveSessionMenuItem, ArchiveSessionRowButton } from '../src/client/session-actions/ArchiveSession.tsx'
import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.tsx'
import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx'
import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx'
import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx'
import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx'
import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts'
import { UNGROUPED_KEY } from '../src/client/tree.ts'
import { apply as hostApply } from '../src/index.ts'
import type { SessionReference } from '@deepseek-ai/dsh-api-session-controller/client'
const sid = (id: string) => id as SessionId
const summary = (id: string, updatedAt: number): SessionSummary => ({
id: sid(id), displayTitle: id, running: false, blank: false, updatedAt, retainedBy: {},
})
const sessionState = (items: readonly SessionSummary[]): SessionListState => ({
ids: items.map(item => item.id),
byId: Object.fromEntries(items.map(item => [item.id, item])),
phase: 'ready',
projectionsBySession: {}, jobsBySession: {},
})
const workspace = (id: string, sessionIds: readonly string[]): WorkspaceView => ({
workspaceId: id as WorkspaceId, path: `/projects/${id}`, title: id,
sessionIds: sessionIds.map(sid), createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
})
const workspaceState = (
items: readonly WorkspaceView[],
archivedSessionIds: readonly SessionId[] = [],
pinnedSessionIds: readonly SessionId[] = [],
): WorkspaceSnapshot => ({
items, archivedSessionIds, pinnedSessionIds, state: 'idle', phase: 'ready', error: null,
})
async function bench() {
const ctx = new Context()
@@ -44,29 +82,29 @@ async function bench() {
operation: (reference: SessionReference) => unknown,
) => await operation(retain(target)))
const fork = vi.fn(async () => 'forked' as never)
const pinSession = vi.fn(async () => undefined)
const unpinSession = vi.fn(async () => undefined)
// The Host snapshots the injected hooks derive from and a pin's order write
// reads at completion; a test replaces them whole, so an unchanged snapshot
// keeps its identity between reads.
let workspaceSnapshot = workspaceState([])
let sessionSnapshot = sessionState([])
const subscribe = () => () => {}
const workspacesSubscribe = vi.fn(subscribe)
ctx.provide('workspaces', {
list: {
getSnapshot: () => ({
items: [], archivedSessionIds: [], pinnedSessionIds: [], state: 'idle', phase: 'ready', error: null,
}),
subscribe,
},
list: { getSnapshot: () => workspaceSnapshot, subscribe: workspacesSubscribe },
create,
rename,
delete: vi.fn(async () => undefined),
insertBefore: vi.fn(async () => undefined),
archiveSession: vi.fn(async () => undefined),
unarchiveSession: vi.fn(async () => undefined),
pinSession,
unpinSession,
insertSessionBefore: vi.fn(async () => ({})),
} as never)
ctx.provide('sessions', {
list: {
getSnapshot: () => ({
ids: [], byId: {}, phase: 'ready',
projectionsBySession: {}, jobsBySession: {},
}),
subscribe,
},
list: { getSnapshot: () => sessionSnapshot, subscribe },
create: vi.fn(async () => 'created' as never),
retain,
using,
@@ -89,18 +127,50 @@ async function bench() {
ctx.provide('locale', locale)
return {
ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename,
retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory,
retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession,
workspacesSubscribe,
setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot },
setSessions: (snapshot: SessionListState): void => { sessionSnapshot = snapshot },
}
}
type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace'
type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace' | 'shell.overlay'
/** Declare any subset of the holes with a single root registration ('root' is a single slot). */
const MENU_ITEM = 'sidebar.workspaces.session.menu.item'
const ROW_ACTION = 'sidebar.workspaces.session.row.action'
type RowListName = typeof MENU_ITEM | typeof ROW_ACTION | 'shell.overlay'
/** Declare any subset of the holes with a single root registration ('root' is a single slot); the overlay is a list. */
function declare(slots: SlotRegistry, ...names: HoleName[]): () => void {
const children = Object.fromEntries(names.map(name => [name, { kind: 'single', scope: 'root' }]))
const children = Object.fromEntries(names.map(name => [
name, { kind: name === 'shell.overlay' ? 'list' : 'single', scope: 'root' },
]))
return slots.register({ name: 'root', children } as never, () => null)
}
/** The one entry registered under `id` in a list. */
function entry(slots: SlotRegistry, key: RowListName, id: string): StoredEntry {
const found = slots.entries(key).find(candidate => candidate.options.id === id)
if (found === undefined) throw new Error(`no ${key} entry ${id}`)
return found
}
/** An entry's injected face; the shipped factories ignore the positional store actions. */
function faceOf(registration: StoredEntry): object {
if (registration.inject === undefined) throw new Error(`entry ${String(registration.options.id)} declares no inject face`)
return registration.inject()
}
/** The viewing-store instance the browser's declared handle hands the renderer. */
function viewInstance(slots: SlotRegistry) {
const browser = slots.entries('sidebar.workspaces')[0]!
if (browser.store === undefined) throw new Error('the browser entry declares no viewing store')
return (browser.store as WorkspaceViewStoreHandle).create()
}
/** Let the injected callbacks' Host-call chains settle: one macrotask drains every pending microtask. */
const settled = (): Promise<void> => new Promise((resolve) => { setTimeout(resolve, 0) })
describe('ui-workspace apply', () => {
it('keeps the host Loader entry inert', () => {
expect(hostApply).not.toThrow()
@@ -124,10 +194,268 @@ describe('ui-workspace apply', () => {
const after = await bench()
await after.ctx.plugin({ inject: [...inject], apply }).await()
declare(after.slots, 'conversation.hero.workspace', 'conversation.empty.workspace')
declare(after.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay')
await Promise.resolve()
expect(after.slots.entries('conversation.hero.workspace')[0]!.component).toBe(WorkspacePicker)
// expect(after.slots.entries('conversation.empty.workspace')[0]!.component).toBe(WorkspacePicker)
// The row actions follow the browser's own declaration, whenever it lands.
expect(after.slots.entries(MENU_ITEM)).toHaveLength(4)
expect(after.slots.entries(ROW_ACTION)).toHaveLength(2)
expect(after.slots.entries('shell.overlay')).toHaveLength(2)
})
it('declares the two Session row lists and registers the shipped actions and overlay surfaces into them', async () => {
const b = await bench()
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
await b.ctx.plugin({ inject: [...inject], apply }).await()
// The menu list binds the row's open state into every entry's hook; the
// hover-button list carries no common face.
expect(b.slots.spec(MENU_ITEM)).toEqual({
kind: 'list', scope: 'root', inject: { hooks: { menuOpenState: menuOpenStateFactory } },
})
expect(b.slots.spec(ROW_ACTION)).toEqual({ kind: 'list', scope: 'root' })
const rows = (key: RowListName) => b.slots.entries(key)
.map(registration => [registration.options.id, registration.options.order, registration.component, registration.locale])
expect(rows(MENU_ITEM)).toEqual([
['pin', 100, PinSessionMenuItem, 'workspace'],
['rename', 200, RenameSessionMenuItem, 'workspace'],
['fork', 300, ForkSessionMenuItem, 'workspace'],
['archive', 400, ArchiveSessionMenuItem, 'workspace'],
])
expect(rows(ROW_ACTION)).toEqual([
['archive', 100, ArchiveSessionRowButton, 'workspace'],
['pin', 200, PinSessionRowButton, 'workspace'],
])
expect(rows('shell.overlay')).toEqual([
['workspace.session-rename', undefined, SessionRenameDialog, 'workspace'],
['workspace.row-toast', undefined, RowActionToast, 'workspace'],
])
// Only the browser declares the viewing store; its handle hands out the
// one instance the injected callbacks write view state through. The
// row actions and overlay surfaces declare none.
const browser = b.slots.entries('sidebar.workspaces')[0]!
expect(browser.store).toBeDefined()
expect(viewInstance(b.slots)).toBe(viewInstance(b.slots))
for (const registration of [...b.slots.entries(MENU_ITEM), ...b.slots.entries(ROW_ACTION), ...b.slots.entries('shell.overlay')]) {
expect(registration.store).toBeUndefined()
}
// Each share raises its own notices inside its callbacks.
for (const id of ['pin', 'archive']) {
expect(faceOf(entry(b.slots, MENU_ITEM, id))).not.toHaveProperty('notify')
expect(faceOf(entry(b.slots, ROW_ACTION, id))).not.toHaveProperty('notify')
}
})
it('derives the pinned and archived Sets from the Workspace snapshot, rebuilt only when it changes', async () => {
const b = await bench()
b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [sid('two')], [sid('one')]))
declare(b.slots, 'sidebar.workspaces')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const pin = faceOf(entry(b.slots, MENU_ITEM, 'pin')) as PinSessionInjected
const pinButton = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected
const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected
const pinned = pin.hooks.pinned.getSnapshot()
const archived = pin.hooks.archived.getSnapshot()
expect(pinned).toEqual(new Set(['one']))
expect(archived).toEqual(new Set(['two']))
// One source per set, shared by every entry and held while the snapshot stands.
expect(pin.hooks.pinned.getSnapshot()).toBe(pinned)
expect(pinButton.hooks.pinned.getSnapshot()).toBe(pinned)
expect(archive.hooks.archived.getSnapshot()).toBe(archived)
// Subscriptions ride the Workspace Controller's list source.
const listener = vi.fn()
const unsubscribe = pin.hooks.pinned.subscribe(listener)
expect(b.workspacesSubscribe).toHaveBeenCalledWith(listener)
unsubscribe()
b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [], [sid('one'), sid('two')]))
expect(pin.hooks.pinned.getSnapshot()).toEqual(new Set(['one', 'two']))
expect(pin.hooks.pinned.getSnapshot()).not.toBe(pinned)
expect(archive.hooks.archived.getSnapshot()).toEqual(new Set())
})
it('pins through the navigation service, which fronts the Session in its group and the flat list of the browser view', async () => {
const b = await bench()
b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two', 'three'])]))
b.setSessions(sessionState([summary('one', 3), summary('two', 2), summary('three', 1)]))
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const view = viewInstance(b.slots)
const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
expect(view.getSnapshot().sessionOrderByAccount).toEqual({})
const pin = faceOf(entry(b.slots, MENU_ITEM, 'pin')) as PinSessionInjected
pin.pinSession(sid('three'))
expect(b.pinSession).toHaveBeenCalledWith('three')
await vi.waitFor(() => {
expect(view.getSnapshot().sessionOrderByAccount).toEqual({
alpha: ['three', 'one', 'two'],
[UNGROUPED_KEY]: [],
[FLAT_SESSION_ORDER_KEY]: ['three', 'one', 'two'],
})
})
// The saved positions lead without leaving Last updated, and a successful pin raises no notice.
expect(view.getSnapshot().orderBy).toBe('updated')
expect(toast.hooks.toast.getSnapshot()).toBeNull()
// The hover button's face is the same behavior.
const pinButton = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected
pinButton.pinSession(sid('one'))
expect(b.pinSession).toHaveBeenLastCalledWith('one')
await vi.waitFor(() => {
expect(view.getSnapshot().sessionOrderByAccount.alpha).toEqual(['one', 'three', 'two'])
})
// Unpin leaves the saved orders as they are.
const before = view.getSnapshot().sessionOrderByAccount
pin.unpinSession(sid('one'))
expect(b.unpinSession).toHaveBeenCalledWith('one')
await settled()
expect(view.getSnapshot().sessionOrderByAccount).toBe(before)
expect(toast.hooks.toast.getSnapshot()).toBeNull()
})
it('raises the pin and unpin failure notices and writes no order', async () => {
const b = await bench()
b.setWorkspaces(workspaceState([workspace('alpha', ['one'])]))
b.setSessions(sessionState([summary('one', 1)]))
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const view = viewInstance(b.slots)
const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
const pin = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected
b.pinSession.mockRejectedValueOnce(new Error('pin wire down'))
pin.pinSession(sid('one'))
await vi.waitFor(() => { expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'pinFailed', seq: 1 }) })
b.unpinSession.mockRejectedValueOnce(new Error('unpin wire down'))
pin.unpinSession(sid('one'))
await vi.waitFor(() => { expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'unpinFailed', seq: 2 }) })
expect(view.getSnapshot().sessionOrderByAccount).toEqual({})
})
it('archives through the navigation service and raises the archived notice; Host rejections are console diagnostics', async () => {
const b = await bench()
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const archiveSession = vi.spyOn(b.ctx.uiWorkspace, 'archiveSession').mockResolvedValue(undefined)
const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined)
const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected
archive.archiveSession(sid('one'))
expect(archiveSession).toHaveBeenCalledWith('one')
await vi.waitFor(() => {
expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archived', sessionId: 'one', seq: 1 })
})
// The menu row's face is the same behavior; a restore raises no notice.
const archiveRow = faceOf(entry(b.slots, MENU_ITEM, 'archive')) as ArchiveSessionInjected
archiveRow.unarchiveSession(sid('one'))
expect(unarchiveSession).toHaveBeenCalledWith('one')
await settled()
expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archived', sessionId: 'one', seq: 1 })
const archiveRejection = new Error('archive exploded')
const unarchiveRejection = new Error('unarchive exploded')
archiveSession.mockRejectedValueOnce(archiveRejection)
unarchiveSession.mockRejectedValueOnce(unarchiveRejection)
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
archive.archiveSession(sid('two'))
await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session archive rejected:', archiveRejection) })
archive.unarchiveSession(sid('two'))
await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session unarchive rejected:', unarchiveRejection) })
} finally {
warn.mockRestore()
}
// A rejected archive raises no notice.
expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archived', sessionId: 'one', seq: 1 })
})
it('the notice share takes the notice down, undoes an archive, and shows the archived rows', async () => {
const b = await bench()
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined)
const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected
const view = viewInstance(b.slots)
// The browser raises the not-openable notice into the same entry, and the source notifies.
expect(toast.hooks.toast.getSnapshot()).toBeNull()
const noticed = vi.fn()
const unsubscribe = toast.hooks.toast.subscribe(noticed)
browser.notifyArchivedNotOpenable()
expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archivedNotOpenable', seq: 1 })
expect(noticed).toHaveBeenCalledOnce()
toast.dismissToast()
expect(toast.hooks.toast.getSnapshot()).toBeNull()
unsubscribe()
expect(view.getSnapshot().archivedFilter).toBe('default')
toast.showArchived()
expect(view.getSnapshot().archivedFilter).toBe('show')
toast.undoArchive(sid('one'))
expect(unarchiveSession).toHaveBeenCalledWith('one')
// A rejected undo is a console diagnostic.
const rejection = new Error('unarchive exploded')
unarchiveSession.mockRejectedValueOnce(rejection)
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
toast.undoArchive(sid('two'))
await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session unarchive rejected:', rejection) })
} finally {
warn.mockRestore()
}
})
it('routes fork and rename through their shares, the rename dialog, and the browser face', async () => {
const b = await bench()
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined)
// Fork goes through the navigation service, which leaves the child unselected.
const forkSession = vi.spyOn(b.ctx.uiWorkspace, 'forkSession')
const fork = faceOf(entry(b.slots, MENU_ITEM, 'fork')) as ForkSessionInjected
b.retain.mockClear()
fork.forkSession('session' as never)
await forkSession.mock.results[0]!.value
expect(b.fork).toHaveBeenCalledWith({ sessionId: 'session', increaseTitle: true })
expect(b.retain).not.toHaveBeenCalled()
// The rename row raises the request the dialog entry reads; settling clears it.
const rename = faceOf(entry(b.slots, MENU_ITEM, 'rename')) as RenameSessionInjected
const dialog = faceOf(entry(b.slots, 'shell.overlay', 'workspace.session-rename')) as SessionRenameDialogInjected
expect(dialog.hooks.renameRequest.getSnapshot()).toBeNull()
const requested = vi.fn()
const unsubscribeRequest = dialog.hooks.renameRequest.subscribe(requested)
rename.requestSessionRename('session' as never, 'Old title')
expect(dialog.hooks.renameRequest.getSnapshot()).toEqual({ sessionId: 'session', currentTitle: 'Old title' })
expect(requested).toHaveBeenCalled()
unsubscribeRequest()
dialog.settleSessionRename()
expect(dialog.hooks.renameRequest.getSnapshot()).toBeNull()
// The dialog's rename hop reaches the Session face and rethrows a business error.
await dialog.renameSession('session' as never, 'renamed session')
expect(b.using).toHaveBeenCalledWith('session', { source: 'workspaceOperation' }, expect.any(Function))
expect(b.renameSession).toHaveBeenCalledWith('renamed session')
b.renameSession.mockResolvedValueOnce({
ok: false, error: new RemoteError('gateway/internal', 'title write failed', {}),
} as never)
await expect(dialog.renameSession('session' as never, 'again')).rejects.toThrow('title write failed')
// The browser raises the same rename request from a title double-click,
// restores from its search results, and carries none of the row verbs itself.
const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected
browser.requestSessionRename('session' as never, 'Row title')
expect(dialog.hooks.renameRequest.getSnapshot()).toEqual({ sessionId: 'session', currentTitle: 'Row title' })
for (const verb of ['forkSession', 'archiveSession', 'pinSession', 'unpinSession', 'renameSession', 'undoArchive', 'showArchived']) {
expect(browser).not.toHaveProperty(verb)
}
await browser.unarchiveSession('session' as never)
expect(unarchiveSession).toHaveBeenCalledWith('session')
})
it('routes browser actions and picker creation to the services', async () => {
@@ -136,7 +464,7 @@ describe('ui-workspace apply', () => {
await b.ctx.plugin({ inject: [...inject], apply }).await()
const startSession = vi.spyOn(b.ctx.uiWorkspace, 'startSession').mockImplementation(() => undefined)
const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)()
const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected
// Both arms delegate to the shared Session navigation action.
browser.startSession('ws' as never)
expect(startSession).toHaveBeenCalledWith('ws')
@@ -151,23 +479,12 @@ describe('ui-workspace apply', () => {
})
expect(b.search).toHaveBeenCalledWith('match', signal)
expect(browser.searchResultLimit).toBe(20)
await browser.renameSession('session' as never, 'renamed session')
expect(b.using).toHaveBeenCalledWith(
'session', { source: 'workspaceOperation' }, expect.any(Function),
)
expect(b.renameSession).toHaveBeenCalledWith('renamed session')
b.retain.mockClear()
const forkSession = vi.spyOn(b.ctx.uiWorkspace, 'forkSession')
browser.forkSession('session' as never)
await forkSession.mock.results[0]!.value
expect(b.retain).not.toHaveBeenCalled()
expect(b.fork).toHaveBeenCalledWith({ sessionId: 'session', increaseTitle: true })
await browser.renameWorkspace('ws' as never, 'renamed')
expect(b.rename).toHaveBeenCalledWith('ws', 'renamed')
await browser.createWorkspace({ path: '/tmp/browser-project' })
expect(b.create).toHaveBeenCalledWith({ path: '/tmp/browser-project' })
const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)()
const picker = faceOf(b.slots.entries('conversation.hero.workspace')[0]!) as WorkspacePickerInjected
await picker.createWorkspace({ path: '/tmp/project' })
expect(b.create).toHaveBeenCalledWith({ path: '/tmp/project' })
})
@@ -179,10 +496,9 @@ describe('ui-workspace apply', () => {
// Registration declared the child holes (declaration = render authorization).
expect(b.slots.spec('sidebar.workspaces.directoryFlow')).toMatchObject({ kind: 'single' })
expect(b.slots.spec('conversation.hero.workspace.directoryFlow')).toMatchObject({ kind: 'single' })
expect(b.slots.spec('sidebar.workspaces.session.menu.action')).toEqual({ kind: 'list', scope: 'root' })
const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)()
const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)()
const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected
const picker = faceOf(b.slots.entries('conversation.hero.workspace')[0]!) as WorkspacePickerInjected
expect(browser.hooks.directoryFlow.getSnapshot()).toBe(false)
expect(browser.hooks.hostInfo.getSnapshot()).toMatchObject({ home: undefined })
expect(picker.hooks.directoryFlow.getSnapshot()).toBe(false)
@@ -207,19 +523,27 @@ describe('ui-workspace apply', () => {
}) as never)
declare(b.slots, 'sidebar.workspaces')
await b.ctx.plugin({ inject: [...inject], apply }).await()
const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)()
const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected
await expect(browser.searchSessions('needle', new AbortController().signal))
.rejects.toThrow('index unavailable')
})
it('unregisters every entry on teardown', async () => {
const b = await bench()
declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace')
declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay')
const fiber = b.ctx.plugin({ inject: [...inject], apply })
await fiber.await()
expect(b.slots.entries(MENU_ITEM)).toHaveLength(4)
expect(b.slots.entries(ROW_ACTION)).toHaveLength(2)
expect(b.slots.entries('shell.overlay')).toHaveLength(2)
await fiber.dispose()
expect(b.slots.entries('sidebar.workspaces')).toHaveLength(0)
expect(b.slots.entries('conversation.hero.workspace')).toHaveLength(0)
// expect(b.slots.entries('conversation.empty.workspace')).toHaveLength(0)
// The row lists collapse with the browser declaration; the overlay list
// (declared by the shell) keeps no ui-workspace entry behind.
expect(b.slots.spec(MENU_ITEM)).toBeUndefined()
expect(b.slots.entries(MENU_ITEM)).toHaveLength(0)
expect(b.slots.entries(ROW_ACTION)).toHaveLength(0)
expect(b.slots.entries('shell.overlay')).toHaveLength(0)
})
})
@@ -1,28 +1,27 @@
// @vitest-environment jsdom
/**
* The session-rename assembly chain on SlotTestRuntime (real apply, real
* WorkspaceBrowser occupying the sidebar hole): row menu → rename dialog →
* the injected renameSession hop (sessions.binding → ISession.rename) → on
* the accepted unary response the dialog closes and the row re-labels from
* the list state — no push-frame wait. Coverage split: the assembled-app
* snapshot (apps/web/tests/session-actions.snapshot.ts) pins the full-app
* transcript; the
* verb's wire behavior stays with the Session Controller client package
* (session.spec.ts#rename), the dialog's own arms with rows.spec /
* workspace-browser.spec.
* WorkspaceBrowser occupying the sidebar hole, the shipped row actions and
* the overlay surfaces registered by the same apply): row menu → rename
* request → the `shell.overlay` dialog → the injected renameSession hop
* (sessions.binding → ISession.rename) → on the accepted unary response the
* dialog closes and the row re-labels from the list state — no push-frame
* wait. Coverage split: the assembled-app snapshot
* (apps/web/tests/session-actions.snapshot.ts) pins the full-app transcript;
* the verb's wire behavior stays with the Session Controller client package
* (session.spec.ts#rename), the entries' own arms with
* session-actions.client.spec, the row's list rendering with rows.client.spec.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, waitFor, within } from '@testing-library/react'
import type { ISession } from '@deepseek-ai/dsh-api-session-controller/client'
import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client'
import { SessionSeq, type SessionId } from '@deepseek-ai/dsh-session/types'
import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
import type { PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import { RemoteError, SlotTestRuntime, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives'
import {
apply, inject, type SessionMenuActionOwnerProps,
} from '@deepseek-ai/dsh-client-ui-workspace/client'
import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client'
// The service reads its initial locale from the browser; these specs assert
// the shipped Chinese copy, so they state the browser they assume.
@@ -48,10 +47,36 @@ async function createRuntime(): Promise<SlotTestRuntime> {
return runtime
}
/** Test-owned sidebar shell role: declares and renders the browsing region. */
type FrameProps = PropsRenderSlots<'sidebar.workspaces'>
/** Test-owned shell role: declares and renders the browsing region and the frame-wide overlay list. */
type FrameProps = PropsRenderSlots<'sidebar.workspaces' | 'shell.overlay'>
function SidebarFrame({ renderSlot }: FrameProps) {
return <>{renderSlot('sidebar.workspaces', { wide: true, expandSidebar: () => {} })}</>
return (
<>
{renderSlot('sidebar.workspaces', { wide: true, expandSidebar: () => {} })}
{renderSlot('shell.overlay', {})}
</>
)
}
/** Declare the sidebar hole and the overlay list the rename dialog and the row notices mount in. */
async function declareFrame(runtime: SlotTestRuntime): Promise<void> {
await runtime.root.declare(
{
'sidebar.workspaces': { kind: 'single', scope: 'root' },
'shell.overlay': { kind: 'list', scope: 'root' },
} as never,
SidebarFrame as never,
)
}
/** One Workspace holding the fixture Session. */
async function seedWorkspace(runtime: SlotTestRuntime): Promise<void> {
await runtime.workspaces.update((draft) => {
draft.items = [{
workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha',
sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
}] as never
})
}
describe('session rename through the assembled browser', () => {
@@ -64,46 +89,51 @@ describe('session rename through the assembled browser', () => {
session: { rename: vi.fn() },
})
await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready
await runtime.workspaces.update((draft) => {
draft.items = [{
workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha',
sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
}] as never
})
await runtime.root.declare(
{ 'sidebar.workspaces': { kind: 'single', scope: 'root' } } as never,
SidebarFrame as never,
)
await seedWorkspace(runtime)
await declareFrame(runtime)
await runtime.mount({ inject: [...inject], apply })
const registerAction = (id: string, order: number, priority: number, label: string) => {
runtime.slots.register(
{ name: 'sidebar.workspaces.session.menu.action', id, order, priority },
({ sessionId, displayTitle }: SessionMenuActionOwnerProps) => (
<MenuAction onSelect={() => { selected(id, sessionId, displayTitle) }}>{label}</MenuAction>
),
{ name: 'sidebar.workspaces.session.menu.item', id, order, priority },
({ sessionId, displayTitle, useMenuOpenState }: PropsRuntime<'sidebar.workspaces.session.menu.item'>) => {
const [, setMenuOpen] = useMenuOpenState()
return (
<MenuItemButton separatorBefore={order === 500} onSelect={() => {
setMenuOpen(false)
selected(id, sessionId, displayTitle)
}}>
{label}
</MenuItemButton>
)
},
)
}
// List display order stays primary even when the later registration has
// the lower shadowing priority assigned to dynamic browser packages.
registerAction('earlier', 10, -1, 'Earlier action')
registerAction('later', 20, -2, 'Later action')
// `order` places plugin rows after the shipped rows (100/200/300/400)
// even when the later registration has the lower shadowing priority
// assigned to dynamic browser packages; the first plugin row opens the
// plugin group with a hairline.
registerAction('export', 500, -1, 'Export action')
registerAction('last', 600, -2, 'Last action')
const view = runtime.renderRoot()
const row = (await view.findByText('Session title')).closest('[role="treeitem"]')!
const trigger = within(row as HTMLElement).getByLabelText('会话“Session title”的操作')
fireEvent.click(trigger)
expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([
'置顶会话', '重命名', '分叉会话', '归档会话', 'Earlier action', 'Later action',
'置顶会话', '重命名', '分叉会话', '归档会话', 'Export action', 'Last action',
])
const later = view.getByRole('menuitem', { name: 'Later action' })
const earlier = view.getByRole('menuitem', { name: 'Earlier action' })
expect(view.getAllByRole('separator')).toHaveLength(1)
const last = view.getByRole('menuitem', { name: 'Last action' })
const exportRow = view.getByRole('menuitem', { name: 'Export action' })
trigger.focus()
fireEvent.keyDown(trigger, { key: 'End' })
expect(document.activeElement).toBe(later)
fireEvent.keyDown(later, { key: 'ArrowUp' })
expect(document.activeElement).toBe(earlier)
fireEvent.click(earlier)
expect(selected).toHaveBeenCalledWith('earlier', SID, 'Session title')
expect(document.activeElement).toBe(last)
fireEvent.keyDown(last, { key: 'ArrowUp' })
expect(document.activeElement).toBe(exportRow)
fireEvent.click(exportRow)
expect(selected).toHaveBeenCalledWith('export', SID, 'Session title')
// The plugin row dismissed the menu through the bound open-state hook;
// the list returns focus to the trigger.
expect(view.queryByRole('menu')).toBeNull()
await act(async () => { await Promise.resolve() })
expect(document.activeElement).toBe(trigger)
@@ -121,16 +151,8 @@ describe('session rename through the assembled browser', () => {
session: { rename },
})
await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready
await runtime.workspaces.update((draft) => {
draft.items = [{
workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha',
sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
}] as never
})
await runtime.root.declare(
{ 'sidebar.workspaces': { kind: 'single', scope: 'root' } } as never,
SidebarFrame as never,
)
await seedWorkspace(runtime)
await declareFrame(runtime)
await runtime.mount({ inject: [...inject], apply })
const view = runtime.renderRoot()
@@ -138,6 +160,8 @@ describe('session rename through the assembled browser', () => {
const row = (await view.findByText('旧标题')).closest('[role="treeitem"]')!
fireEvent.click(within(row as HTMLElement).getByLabelText('会话“旧标题”的操作'))
fireEvent.click(view.getByRole('menuitem', { name: '重命名', hidden: true }))
// The rename row dismissed the menu; the dialog lives in the overlay list.
expect(view.queryByRole('menu')).toBeNull()
// The dialog seeds from the current title; submit a padded value.
const input = await view.findByLabelText('会话名称') as HTMLInputElement
@@ -169,16 +193,8 @@ describe('session rename through the assembled browser', () => {
session: { rename },
})
await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready
await runtime.workspaces.update((draft) => {
draft.items = [{
workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha',
sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
}] as never
})
await runtime.root.declare(
{ 'sidebar.workspaces': { kind: 'single', scope: 'root' } } as never,
SidebarFrame as never,
)
await seedWorkspace(runtime)
await declareFrame(runtime)
await runtime.mount({ inject: [...inject], apply })
const view = runtime.renderRoot()
await runtime.flush()
@@ -6,9 +6,9 @@ import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/clie
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts'
import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives'
import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
import type { SessionMenuActionOwnerProps } from '../src/client/contract/slots.ts'
import type { MenuOpenState, SessionRowOwnerProps } from '../src/client/contract/slots.ts'
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import type { RowDragProps } from '../src/client/rows/Rows.tsx'
import {
@@ -25,13 +25,18 @@ const tEn = makeTranslate(en, commonEn) as never
const sid = (id: string) => id as SessionId
const wid = (id: string) => id as WorkspaceId
const renderNoSessionActions: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] = () => null
/** The two row lists a Session row renders. */
type RowSlotName = 'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action'
type RowRenderSlot = PropsRenderSlots<RowSlotName>['renderSlot']
type SessionNodeItemProps = ComponentProps<typeof SessionNodeItemComponent>
// Direct row specs use the real required Slot share, empty unless the case supplies an occupant.
function SessionNodeItem({ renderSlot = renderNoSessionActions, ...props }: Omit<
ComponentProps<typeof SessionNodeItemComponent>, 'renderSlot'
> & Partial<Pick<ComponentProps<typeof SessionNodeItemComponent>, 'renderSlot'>>) {
return <SessionNodeItemComponent {...props} renderSlot={renderSlot} />
const renderNoRowEntries: RowRenderSlot = () => null
// Direct row specs use the real required Slot share, empty unless the case supplies entries.
function SessionNodeItem({ renderSlot = renderNoRowEntries, onRenameRequest = () => {}, ...props }: Omit<
SessionNodeItemProps, 'renderSlot' | 'onRenameRequest'
> & Partial<Pick<SessionNodeItemProps, 'renderSlot' | 'onRenameRequest'>>) {
return <SessionNodeItemComponent {...props} renderSlot={renderSlot} onRenameRequest={onRenameRequest} />
}
/** Half detection reads the row rect; jsdom rects are all-zero by default. */
@@ -79,13 +84,12 @@ describe('workspace browser rows', () => {
id: sid('flat'), title: 'Flat Session', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
const view = render(<SessionNodeItem node={idle} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} flat t={t} />)
const view = render(<SessionNodeItem node={idle} currentId={undefined} now={0} onOpen={vi.fn()} flat t={t} />)
const title = screen.getByText('Flat Session')
expect(title.previousElementSibling).toBeNull()
view.rerender(<SessionNodeItem node={{ ...idle, running: true }} currentId={undefined} now={0}
onOpen={vi.fn()} onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} flat t={t} />)
onOpen={vi.fn()} flat t={t} />)
expect(screen.getByText('Flat Session').previousElementSibling?.querySelector('[data-state="ongoing"]')).toBeTruthy()
})
@@ -175,8 +179,7 @@ describe('workspace browser rows', () => {
}
const onOpen = vi.fn()
render(
<SessionNodeItem node={node} currentId={node.id} now={0} onOpen={onOpen}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />,
<SessionNodeItem node={node} currentId={node.id} now={0} onOpen={onOpen} t={t} />,
)
const row = screen.getByRole('treeitem')
@@ -194,8 +197,7 @@ describe('workspace browser rows', () => {
pinned: false, archived: false,
}
render(
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />,
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />,
)
const row = screen.getByRole('treeitem')
const title = screen.getByText(node.title)
@@ -236,8 +238,7 @@ describe('workspace browser rows', () => {
pinned: false, archived: false,
}
render(
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />,
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />,
)
const row = screen.getByRole('treeitem')
const title = screen.getByText(node.title)
@@ -258,8 +259,7 @@ describe('workspace browser rows', () => {
runningSubagentCount: 0, completed: false, hasActiveSchedule: true, updatedAt: 0, pinned: false, archived: false,
}
const view = render(
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />,
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen} t={t} />,
)
const assertIndicator = (): HTMLElement => {
@@ -277,8 +277,7 @@ describe('workspace browser rows', () => {
expect(onOpen).toHaveBeenCalledWith(node.id)
view.rerender(
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} flat t={t} />,
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen} flat t={t} />,
)
assertIndicator()
})
@@ -290,8 +289,7 @@ describe('workspace browser rows', () => {
id: sid('s1'), title: 'One', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, ...over,
}}
currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t}
currentId={undefined} now={0} onOpen={vi.fn()} t={t}
/>,
)
const stateDot = (view: ReturnType<typeof renderRow>) =>
@@ -322,8 +320,7 @@ describe('workspace browser rows', () => {
id: sid('owner'), title: 'Delegating', blank: false, running: false,
runningSubagentCount: 2, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
const row = screen.getByRole('treeitem')
expect(row.querySelector('[data-state="ongoing"]')).not.toBeNull()
expect(screen.getByText('2 个子代理运行中')).toBeTruthy()
@@ -344,8 +341,7 @@ describe('workspace browser rows', () => {
id: sid('owner'), title: 'Delegating', blank: false, running: true,
runningSubagentCount: 1, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
const row = screen.getByRole('treeitem')
expect(row.querySelectorAll('[data-state="ongoing"]')).toHaveLength(1)
expect(screen.getByText('进行中')).toBeTruthy()
@@ -365,8 +361,7 @@ describe('workspace browser rows', () => {
id: sid('owner'), title: 'Needs input', blank: false, pendingInteraction: 'question',
running: false, runningSubagentCount: 1, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
const row = screen.getByRole('treeitem')
expect(row.querySelector('[data-state="warning"]')).not.toBeNull()
expect(row.querySelector('[data-state="ongoing"]')).toBeNull()
@@ -512,10 +507,13 @@ describe('workspace browser rows', () => {
id: sid('s-blank'), title: 'ignored', blank: true, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={node.id} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
// The placeholder has no content yet: no row verbs, no "now" stamp.
const rendered = vi.fn()
const renderSlot: RowRenderSlot = (name: RowSlotName) => { rendered(name); return null }
render(<SessionNodeItem node={node} currentId={node.id} now={0} onOpen={vi.fn()} renderSlot={renderSlot} t={t} />)
// The placeholder has no content yet: no row verbs (neither list is
// asked for anything), no "now" stamp.
expect(screen.queryByRole('button', { name: /会话.*的操作/ })).toBeNull()
expect(rendered).not.toHaveBeenCalled()
expect(screen.queryByText('刚刚')).toBeNull()
// The hover card keeps title + status but drops the timestamp line.
const wrapper = screen.getByRole('treeitem').parentElement as HTMLElement
@@ -530,85 +528,104 @@ describe('workspace browser rows', () => {
}
})
it('session row menu opens without opening the session and dispatches rename, fork, and archive', () => {
it('session row menu opens without opening the session and Escape closes it', () => {
const onOpen = vi.fn()
const onRename = vi.fn()
const onFork = vi.fn()
const onArchive = vi.fn()
const node: SessionNode = {
id: sid('s1'), title: 'One', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen}
onRename={onRename} onFork={onFork} onArchive={onArchive} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' }))
expect(onOpen).not.toHaveBeenCalled()
// Archive is not destructive (log and accounting slot remain): no danger styling.
expect(screen.getByRole('menuitem', { name: '归档会话' }).className).not.toMatch(/danger/)
// Rename dispatches with the current display title (dialog prefill).
fireEvent.click(screen.getByRole('menuitem', { name: '重命名' }))
expect(screen.queryByRole('menu')).toBeNull()
expect(onRename).toHaveBeenCalledWith(node.id, 'One')
expect(onOpen).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '分叉会话' }))
expect(onFork).toHaveBeenCalledWith(node.id)
// Archive dispatches without opening the session.
fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '归档会话' }))
expect(onArchive).toHaveBeenCalledWith(node.id)
expect(onRename).toHaveBeenCalledOnce()
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen} t={t} />)
const trigger = screen.getByRole('button', { name: '会话“One”的操作' })
fireEvent.click(trigger)
expect(screen.getByRole('menu')).toBeTruthy()
expect(onOpen).not.toHaveBeenCalled()
// Escape closes without selecting (Menu onClose path).
fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' }))
fireEvent.keyDown(document, { key: 'Escape' })
expect(screen.queryByRole('menu')).toBeNull()
// The trigger toggles: a second click closes the menu it opened.
fireEvent.click(trigger)
fireEvent.click(trigger)
expect(screen.queryByRole('menu')).toBeNull()
expect(onOpen).not.toHaveBeenCalled()
})
it('appends plugin actions after built-ins with the Session owner props', async () => {
it('renders the menu list with the row identity and open state, and returns focus to the trigger after an entry closes it', async () => {
const onOpen = vi.fn()
const onPluginAction = vi.fn()
const onEntry = vi.fn()
const rendered = vi.fn()
const renderSlot: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] = (name, value) => {
// The generic framework signature cannot narrow its owner from a runtime key in a test stub.
const owner = value as unknown as SessionMenuActionOwnerProps
const { sessionId, displayTitle } = owner
rendered(name, value)
// A stub satisfies the generic render signature only with erased parameter
// types; it narrows the owner and the occurrence options itself.
const renderSlot: RowRenderSlot = (name: RowSlotName, owner: object, opts?: object) => {
const { sessionId, displayTitle } = owner as SessionRowOwnerProps
const hookContext = opts !== undefined && 'hookContext' in opts ? opts.hookContext : undefined
rendered(name, owner, hookContext)
if (name !== 'sidebar.workspaces.session.menu.item') return null
// The stub stands in for the renderer, which binds this occurrence's
// hookContext into the entries' useMenuOpenState hook.
const [open, setMenuOpen] = hookContext as MenuOpenState
return (
<MenuAction onSelect={() => {
onPluginAction(sessionId, displayTitle)
<MenuItemButton onSelect={() => {
setMenuOpen(false)
onEntry(sessionId, displayTitle, open)
}}>
Export
</MenuAction>
</MenuItemButton>
)
}
const node: SessionNode = {
id: sid('s1'), title: 'One', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<>
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()}
renderSlot={renderSlot} t={t} />
</>)
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen} renderSlot={renderSlot} t={t} />)
// Both lists receive the row identity; only the menu list carries the open state.
expect(rendered).toHaveBeenCalledWith(
'sidebar.workspaces.session.menu.item', { sessionId: node.id, displayTitle: 'One' }, [false, expect.any(Function)],
)
expect(rendered).toHaveBeenCalledWith(
'sidebar.workspaces.session.row.action', { sessionId: node.id, displayTitle: 'One' }, undefined,
)
expect(screen.queryByRole('menuitem')).toBeNull()
const trigger = screen.getByRole('button', { name: '会话“One”的操作' })
trigger.focus()
fireEvent.click(trigger)
const actions = screen.getAllByRole('menuitem')
expect(actions.map(action => action.textContent)).toEqual(['置顶会话', '重命名', '分叉会话', '归档会话', 'Export'])
expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual(['Export'])
expect(rendered).toHaveBeenCalledWith(
'sidebar.workspaces.session.menu.item', { sessionId: node.id, displayTitle: 'One' }, [true, expect.any(Function)],
)
fireEvent.click(screen.getByRole('menuitem', { name: 'Export' }))
await act(async () => { await Promise.resolve() })
expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.menu.action', expect.any(Object))
const owner = rendered.mock.calls.at(-1)?.[1] as SessionMenuActionOwnerProps | undefined
expect(owner?.sessionId).toBe(node.id)
expect(owner?.displayTitle).toBe('One')
expect(onPluginAction).toHaveBeenCalledWith(node.id, 'One')
expect(onEntry).toHaveBeenCalledWith(node.id, 'One', true)
// The entry dismissed the menu through the state pair; the list returns focus.
expect(screen.queryByRole('menu')).toBeNull()
await act(async () => { await Promise.resolve() })
expect(document.activeElement).toBe(trigger)
expect(onOpen).not.toHaveBeenCalled()
})
it('renders the row action list inside the actions area after the menu trigger', () => {
const onOpen = vi.fn()
const onQuick = vi.fn()
const renderSlot: RowRenderSlot = (name: RowSlotName) => name === 'sidebar.workspaces.session.row.action'
? (
<button type="button" aria-label="Quick action" onClick={(e) => { e.stopPropagation(); onQuick() }} />
)
: null
const node: SessionNode = {
id: sid('s1'), title: 'One', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen} renderSlot={renderSlot} t={t} />)
const trigger = screen.getByRole('button', { name: '会话“One”的操作' })
const quick = screen.getByRole('button', { name: 'Quick action' })
const actionsArea = trigger.closest('[class*="rowActions"]')
expect(actionsArea).not.toBeNull()
expect(actionsArea?.contains(quick)).toBe(true)
expect(trigger.compareDocumentPosition(quick) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
fireEvent.click(quick)
expect(onQuick).toHaveBeenCalledOnce()
expect(onOpen).not.toHaveBeenCalled()
})
it('shows the hover card after the dwell and suppresses it while the row menu is open', () => {
vi.useFakeTimers()
try {
@@ -616,8 +633,7 @@ describe('workspace browser rows', () => {
id: sid('s1'), title: 'Hovered', blank: false, running: true,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={60_000} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
render(<SessionNodeItem node={node} currentId={undefined} now={60_000} onOpen={vi.fn()} t={t} />)
const wrapper = screen.getByRole('treeitem').parentElement as HTMLElement
fireEvent.pointerEnter(wrapper)
act(() => { vi.advanceTimersByTime(800) })
@@ -648,8 +664,7 @@ describe('workspace browser rows', () => {
pendingInteraction, running: true, runningSubagentCount: 0, completed: false,
hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
const view = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
const view = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
const row = screen.getByRole('treeitem')
const title = screen.getByText('Needs input')
expect(row.querySelector('[data-state="warning"]')).toBeTruthy()
@@ -660,7 +675,7 @@ describe('workspace browser rows', () => {
expect(row.textContent).not.toContain('刚刚')
view.rerender(<SessionNodeItem node={{ ...node, running: false }} currentId={undefined} now={0}
onOpen={vi.fn()} onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
onOpen={vi.fn()} t={t} />)
expect(screen.getByRole('treeitem').querySelector('[data-state="warning"]')).toBeTruthy()
fireEvent.pointerEnter(screen.getByRole('treeitem').parentElement as HTMLElement)
@@ -683,8 +698,7 @@ describe('workspace browser rows', () => {
pendingInteraction, running: false, runningSubagentCount: 0, completed: false,
hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={tEn} />)
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={tEn} />)
const row = screen.getByRole('treeitem')
expect(screen.getByText('Needs input').nextElementSibling?.textContent).toBe(compactLabel)
expect(screen.getByText('Needs input').nextElementSibling?.getAttribute('aria-hidden')).toBe('true')
@@ -698,8 +712,7 @@ describe('workspace browser rows', () => {
id: sid('s1'), title: 'Quiet', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
fireEvent.pointerEnter(screen.getByRole('treeitem').parentElement as HTMLElement)
act(() => { vi.advanceTimersByTime(800) })
expect(screen.getByText('空闲').parentElement?.querySelector('[data-state="idle"]')).not.toBeNull()
@@ -716,8 +729,7 @@ describe('workspace browser rows', () => {
id: sid('s1'), title: 'Done', blank: false, running: false,
runningSubagentCount: 0, completed: true, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
fireEvent.pointerEnter(screen.getByRole('treeitem').parentElement as HTMLElement)
act(() => { vi.advanceTimersByTime(800) })
// Row's visually-hidden reminder label plus the hover card's status line.
@@ -734,8 +746,7 @@ describe('workspace browser rows', () => {
id: sid('s1'), title: 'Stored', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: true,
}
const { rerender } = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
const { rerender } = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
fireEvent.pointerEnter(screen.getByRole('treeitem').parentElement as HTMLElement)
act(() => { vi.advanceTimersByTime(800) })
// Row indicator label plus the hover card's archived line; the idle
@@ -744,8 +755,7 @@ describe('workspace browser rows', () => {
expect(screen.queryByText('空闲')).toBeNull()
// Live activity on an archived session still shows beside the line.
rerender(<SessionNodeItem node={{ ...node, running: true }} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
rerender(<SessionNodeItem node={{ ...node, running: true }} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
expect(screen.getAllByText('进行中').length).toBeGreaterThan(0)
expect(screen.getAllByText('已归档')).toHaveLength(1)
} finally {
@@ -760,8 +770,7 @@ describe('workspace browser rows', () => {
}
const inactive = dragProps()
const { rerender } = render(
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} drag={inactive} t={t} />,
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} drag={inactive} t={t} />,
)
const row = screen.getByRole('treeitem')
stubRect(row)
@@ -778,8 +787,7 @@ describe('workspace browser rows', () => {
const active = dragProps({ active: true, marker: 'before' })
rerender(
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} drag={active} t={t} />,
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} drag={active} t={t} />,
)
stubRect(screen.getByRole('treeitem'))
// Top half hovers/drops 'before'; bottom half 'after' (row mid = 117).
@@ -792,128 +800,63 @@ describe('workspace browser rows', () => {
const after = dragProps({ active: true, marker: 'after' })
rerender(
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} drag={after} t={t} />,
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} drag={after} t={t} />,
)
expect(screen.getByRole('treeitem').className).toMatch(/dropAfter/)
})
it('marks a pinned row, keeps it draggable, and unpins through the row menu', () => {
const onPin = vi.fn()
it('marks a pinned row and keeps it draggable', () => {
const node: SessionNode = {
id: sid('s1'), title: 'Pinned', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: true, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={onPin}
const view = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
drag={dragProps()} t={t} />)
const row = screen.getByRole('treeitem')
// Reorderable within the pinned block; the browser gates the targets.
expect(row.getAttribute('draggable')).toBe('true')
expect(screen.getByRole('img', { name: '已置顶' })).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '会话“Pinned”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '取消置顶' }))
expect(onPin).toHaveBeenCalledWith(node.id, false)
})
it('pins an unpinned row through the row menu', () => {
const onPin = vi.fn()
const node: SessionNode = {
id: sid('s1'), title: 'Plain', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={onPin} t={t} />)
view.rerender(<SessionNodeItem node={{ ...node, pinned: false }} currentId={undefined} now={0} onOpen={vi.fn()}
drag={dragProps()} t={t} />)
expect(screen.queryByRole('img', { name: '已置顶' })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '会话“Plain”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
expect(onPin).toHaveBeenCalledWith(node.id, true)
})
it('marks an archived row, blocks dragging it, and swaps its menu to rename/fork/unarchive', () => {
const onUnarchive = vi.fn()
it('marks an archived row and blocks dragging it', () => {
const node: SessionNode = {
id: sid('s1'), title: 'Stored', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: true,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: true, archived: true,
}
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={onUnarchive} onPin={vi.fn()}
drag={dragProps()} t={t} />)
const row = screen.getByRole('treeitem')
expect(row.className).toMatch(/archived/)
expect(row.getAttribute('draggable')).toBe('false')
// No leading marker: the grayed row alone carries the archived look.
// No leading marker: the grayed row alone carries the archived look, and
// the pin marker stays off an archived row.
expect(screen.queryByRole('img', { name: '已归档' })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '会话“Stored”的操作' }))
// Pin and archive are replaced by unarchive; rename and fork remain.
expect(screen.queryByRole('menuitem', { name: '置顶会话' })).toBeNull()
expect(screen.queryByRole('menuitem', { name: '归档会话' })).toBeNull()
expect(screen.getByRole('menuitem', { name: '重命名' })).toBeTruthy()
expect(screen.getByRole('menuitem', { name: '分叉会话' })).toBeTruthy()
fireEvent.click(screen.getByRole('menuitem', { name: '取消归档' }))
expect(onUnarchive).toHaveBeenCalledWith(node.id)
expect(screen.queryByRole('img', { name: '已置顶' })).toBeNull()
expect(row.getAttribute('aria-description')).toBe('已归档对话暂时无法查看,请取消归档后查看')
})
it('double-clicking the title opens rename with the current title, but not on a blank row', () => {
const onRename = vi.fn()
it('double-clicking the title asks for the rename dialog with the current title, but not on a blank row', () => {
const onRenameRequest = vi.fn()
const onOpen = vi.fn()
const node: SessionNode = {
id: sid('s1'), title: 'Named', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
const view = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen}
onRename={onRename} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
onRenameRequest={onRenameRequest} t={t} />)
fireEvent.doubleClick(screen.getByText('Named'))
expect(onRename).toHaveBeenCalledWith(node.id, 'Named')
expect(onRenameRequest).toHaveBeenCalledWith(node.id, 'Named')
expect(onOpen).not.toHaveBeenCalled()
// A blank placeholder has no content to rename: double-click is inert.
view.rerender(<SessionNodeItem node={{ ...node, blank: true }} currentId={undefined} now={0}
onOpen={onOpen} onRename={onRename} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} />)
onOpen={onOpen} onRenameRequest={onRenameRequest} t={t} />)
fireEvent.doubleClick(screen.getByText('新会话'))
expect(onRename).toHaveBeenCalledOnce()
})
it('quick pin button toggles pin state without opening the session', () => {
const onPin = vi.fn()
const onOpen = vi.fn()
const node: SessionNode = {
id: sid('s1'), title: 'Quick', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
const view = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen}
onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={onPin} t={t} />)
fireEvent.click(screen.getByRole('button', { name: '置顶会话' }))
expect(onPin).toHaveBeenCalledWith(node.id, true)
view.rerender(<SessionNodeItem node={{ ...node, pinned: true }} currentId={undefined} now={0}
onOpen={onOpen} onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={onPin} t={t} />)
fireEvent.click(screen.getByRole('button', { name: '取消置顶' }))
expect(onPin).toHaveBeenCalledWith(node.id, false)
expect(onOpen).not.toHaveBeenCalled()
})
it('quick archive button archives a live row and unarchives an archived one, hiding quick pin there', () => {
const onArchive = vi.fn()
const onUnarchive = vi.fn()
const onOpen = vi.fn()
const node: SessionNode = {
id: sid('s1'), title: 'Quick', blank: false, running: false,
runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false,
}
const view = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={onOpen}
onRename={vi.fn()} onFork={vi.fn()} onArchive={onArchive} onUnarchive={onUnarchive} onPin={vi.fn()} t={t} />)
fireEvent.click(screen.getByRole('button', { name: '归档会话' }))
expect(onArchive).toHaveBeenCalledWith(node.id)
view.rerender(<SessionNodeItem node={{ ...node, archived: true }} currentId={undefined} now={0}
onOpen={onOpen} onRename={vi.fn()} onFork={vi.fn()} onArchive={onArchive} onUnarchive={onUnarchive} onPin={vi.fn()} t={t} />)
// An archived row cannot be pinned: no quick pin button.
expect(screen.queryByRole('button', { name: '置顶会话' })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '取消归档' }))
expect(onUnarchive).toHaveBeenCalledWith(node.id)
expect(onArchive).toHaveBeenCalledOnce()
expect(onOpen).not.toHaveBeenCalled()
expect(onRenameRequest).toHaveBeenCalledOnce()
})
it('flags an archived content-search result', () => {
@@ -0,0 +1,443 @@
// @vitest-environment jsdom
/**
* The shipped Session row actions rendered directly with hand-built props:
* the pin, rename, fork, and archive menu rows, the archive and pin hover
* buttons, and the two `shell.overlay` surfaces they raise (rename dialog,
* row notice). Every action reads its own injected hooks and calls its own
* injected callbacks; what those callbacks do is apply.client.spec's
* subject. The browser and the slot machinery stay out; the assembled
* chain lives in rename-assembly.client.spec.
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
import type { WorkspaceId, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { GlobalStandardProps, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
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 type {
MenuOpenState, RowToast, RowToastState, SessionRenameDialogInjected, SessionRenameRequest,
} from '../src/client/contract/slots.ts'
import { ArchiveSessionMenuItem, ArchiveSessionRowButton } from '../src/client/session-actions/ArchiveSession.tsx'
import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.tsx'
import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx'
import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx'
import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx'
import { zh } from '../src/client/locales.ts'
afterEach(cleanup)
// The seat's key domain is workspace ∪ common; the stub mirrors the real
// lookup chain (namespace, then common vocabulary, then the key).
const t: PropsLocale<'workspace'>['t'] = makeTranslate(zh, commonZh)
const sid = (id: string) => id as SessionId
/** Selector hook over one fixed snapshot: how the renderer binds a standard or injected `hooks` source. */
function hook<T>(snapshot: T) {
return function select<S>(selector: (state: T) => S): S { return selector(snapshot) }
}
/** The Set an injected membership hook selects from. */
const idSet = (...ids: string[]): ReadonlySet<SessionId> => new Set(ids.map(sid))
/** The row every action is rendered for: its owner share as the browser passes it. */
const ROW = { sessionId: sid('one'), displayTitle: 'Session title' }
const one: SessionSummary = {
id: ROW.sessionId, displayTitle: ROW.displayTitle, running: false, blank: false, updatedAt: 1, retainedBy: {},
}
const sessions: SessionListState = {
ids: [one.id], byId: { [one.id]: one }, phase: 'ready', projectionsBySession: {}, jobsBySession: {},
}
// The Workspace snapshot lists no pins or archives: an action's membership
// arrives through its injected Set hooks, never through this seat.
const workspaces: WorkspaceSnapshot = {
items: [{
workspaceId: 'alpha' as WorkspaceId, path: '/projects/alpha', title: 'alpha', sessionIds: [one.id],
createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
}],
archivedSessionIds: [], pinnedSessionIds: [], state: 'idle', phase: 'ready', error: null,
}
const noStatus: SessionStatusSnapshot = new Map()
// Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps.
const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined, reload: () => {} })) as GlobalStandardProps['useResource']
const usePanelInfo: GlobalStandardProps['usePanelInfo'] = selector => selector({ activePanelId: null })
/** The global standard seat every root-scope entry receives. */
const standard: GlobalStandardProps = {
useSessions: hook(sessions),
useSessionStatus: hook(noStatus),
useSessionRetainInfo: () => undefined,
usePanelInfo,
useResource,
useWorkspaces: hook(workspaces),
}
type MenuRowProps = PropsRuntime<'sidebar.workspaces.session.menu.item'> & PropsLocale<'workspace'>
type ActionRowProps = PropsRuntime<'sidebar.workspaces.session.row.action'> & PropsLocale<'workspace'>
type OverlayProps = PropsRuntime<'shell.overlay'> & PropsLocale<'workspace'>
/** Owner share, standard seat, locale seat, and the bound open-state hook of one menu row. */
function menuRow(menu: MenuOpenState): MenuRowProps {
return { ...ROW, useMenuOpenState: () => menu, t, ...standard }
}
/** Owner share, standard seat, and locale seat of one hover button. */
const actionRow: ActionRowProps = { ...ROW, t, ...standard }
/** Standard and locale seats of a `shell.overlay` entry (no owner share). */
const overlay: OverlayProps = { t, ...standard }
/** An open menu whose setter records the entries' dismissal. */
function openMenu() {
const setMenuOpen = vi.fn()
const state: MenuOpenState = [true, setMenuOpen]
return { state, setMenuOpen }
}
/** Position of a mock's `nth` call in the global call sequence (a call that never happened sorts last). */
function callOrder(fn: { mock: { invocationCallOrder: readonly number[] } }, nth = 0): number {
return fn.mock.invocationCallOrder[nth] ?? Number.POSITIVE_INFINITY
}
describe('pin action', () => {
/** The pin share over fixed membership: the bound Set hooks and the two callbacks the entries call. */
const pinShare = (pinned: readonly string[] = [], archived: readonly string[] = []) => ({
usePinned: hook(idSet(...pinned)),
useArchived: hook(idSet(...archived)),
pinSession: vi.fn(),
unpinSession: vi.fn(),
})
it('menu row closes the menu, then pins an unpinned Session', () => {
const { state, setMenuOpen } = openMenu()
const pin = pinShare()
render(<PinSessionMenuItem {...menuRow(state)} {...pin} />)
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
expect(pin.pinSession).toHaveBeenCalledWith(sid('one'))
expect(pin.unpinSession).not.toHaveBeenCalled()
expect(setMenuOpen).toHaveBeenCalledWith(false)
expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(pin.pinSession))
})
it('menu row closes the menu, then unpins a pinned Session', () => {
const { state, setMenuOpen } = openMenu()
const pin = pinShare(['one'])
render(<PinSessionMenuItem {...menuRow(state)} {...pin} />)
fireEvent.click(screen.getByRole('menuitem', { name: '取消置顶' }))
expect(pin.unpinSession).toHaveBeenCalledWith(sid('one'))
expect(pin.pinSession).not.toHaveBeenCalled()
expect(setMenuOpen).toHaveBeenCalledWith(false)
expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(pin.unpinSession))
})
it('row button toggles the pin without opening the row', () => {
const onRowClick = vi.fn()
const pin = pinShare()
const view = render(
<div onClick={onRowClick}>
<PinSessionRowButton {...actionRow} {...pin} />
</div>,
)
fireEvent.click(screen.getByRole('button', { name: '置顶会话' }))
expect(pin.pinSession).toHaveBeenCalledWith(sid('one'))
expect(pin.unpinSession).not.toHaveBeenCalled()
view.rerender(
<div onClick={onRowClick}>
<PinSessionRowButton {...actionRow} {...pin} usePinned={hook(idSet('one'))} />
</div>,
)
fireEvent.click(screen.getByRole('button', { name: '取消置顶' }))
expect(pin.unpinSession).toHaveBeenCalledWith(sid('one'))
expect(pin.pinSession).toHaveBeenCalledOnce()
expect(onRowClick).not.toHaveBeenCalled()
})
it('offers nothing on an archived Session', () => {
const { state } = openMenu()
const pin = pinShare(['one'], ['one'])
const menu = render(<PinSessionMenuItem {...menuRow(state)} {...pin} />)
expect(menu.container.childElementCount).toBe(0)
const button = render(<PinSessionRowButton {...actionRow} {...pin} />)
expect(button.container.childElementCount).toBe(0)
expect(screen.queryByRole('button')).toBeNull()
})
})
describe('archive action', () => {
/** The archive share over fixed membership: the bound Set hook and the two callbacks the entries call. */
const archiveShare = (archived: readonly string[] = []) => ({
useArchived: hook(idSet(...archived)),
archiveSession: vi.fn(),
unarchiveSession: vi.fn(),
})
it('menu row closes the menu, then archives', () => {
const { state, setMenuOpen } = openMenu()
const archive = archiveShare()
render(<ArchiveSessionMenuItem {...menuRow(state)} {...archive} />)
const row = screen.getByRole('menuitem', { name: '归档会话' })
// Archive is not destructive (log and accounting slot remain): no danger styling.
expect(row.className).not.toMatch(/danger/)
fireEvent.click(row)
expect(archive.archiveSession).toHaveBeenCalledWith(sid('one'))
expect(archive.unarchiveSession).not.toHaveBeenCalled()
expect(setMenuOpen).toHaveBeenCalledWith(false)
expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(archive.archiveSession))
})
it('menu row closes the menu, then restores an archived Session', () => {
const { state, setMenuOpen } = openMenu()
const archive = archiveShare(['one'])
render(<ArchiveSessionMenuItem {...menuRow(state)} {...archive} />)
fireEvent.click(screen.getByRole('menuitem', { name: '取消归档' }))
expect(archive.unarchiveSession).toHaveBeenCalledWith(sid('one'))
expect(archive.archiveSession).not.toHaveBeenCalled()
expect(setMenuOpen).toHaveBeenCalledWith(false)
expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(archive.unarchiveSession))
})
it('row button archives and restores without opening the row', () => {
const onRowClick = vi.fn()
const archive = archiveShare()
const view = render(
<div onClick={onRowClick}>
<ArchiveSessionRowButton {...actionRow} {...archive} />
</div>,
)
fireEvent.click(screen.getByRole('button', { name: '归档会话' }))
expect(archive.archiveSession).toHaveBeenCalledWith(sid('one'))
view.rerender(
<div onClick={onRowClick}>
<ArchiveSessionRowButton {...actionRow} {...archive} useArchived={hook(idSet('one'))} />
</div>,
)
fireEvent.click(screen.getByRole('button', { name: '取消归档' }))
expect(archive.unarchiveSession).toHaveBeenCalledWith(sid('one'))
expect(archive.archiveSession).toHaveBeenCalledOnce()
expect(onRowClick).not.toHaveBeenCalled()
})
})
describe('fork and rename rows', () => {
it('fork closes the menu, then forks the Session', () => {
const { state, setMenuOpen } = openMenu()
const forkSession = vi.fn()
render(<ForkSessionMenuItem {...menuRow(state)} forkSession={forkSession} />)
fireEvent.click(screen.getByRole('menuitem', { name: '分叉会话' }))
expect(forkSession).toHaveBeenCalledWith(sid('one'))
expect(setMenuOpen).toHaveBeenCalledWith(false)
expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(forkSession))
})
it('rename closes the menu, then asks for the dialog with the row title', () => {
const { state, setMenuOpen } = openMenu()
const requestSessionRename = vi.fn()
render(<RenameSessionMenuItem {...menuRow(state)} requestSessionRename={requestSessionRename} />)
fireEvent.click(screen.getByRole('menuitem', { name: '重命名' }))
expect(requestSessionRename).toHaveBeenCalledWith(sid('one'), 'Session title')
expect(setMenuOpen).toHaveBeenCalledWith(false)
expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(requestSessionRename))
})
})
describe('SessionRenameDialog', () => {
/** The dialog over a test-owned request source; settling clears the request the way apply does. */
function renameDialog(renameSession: SessionRenameDialogInjected['renameSession']) {
const request = createSnapshotStore<SessionRenameRequest | null>(null)
const settleSessionRename = vi.fn(() => { request.set(null) })
render(
<SessionRenameDialog
{...overlay}
useRenameRequest={bindSnapshotSelector(request)}
settleSessionRename={settleSessionRename}
renameSession={renameSession}
/>,
)
const ask = (sessionId: string, currentTitle: string): void => {
act(() => { request.set({ sessionId: sid(sessionId), currentTitle }) })
}
return { settleSessionRename, ask }
}
it('renders nothing until a rename is requested', () => {
renameDialog(vi.fn(async () => {}))
expect(screen.queryByRole('dialog')).toBeNull()
expect(document.body.textContent).toBe('')
})
it('seeds the draft from the request, renames with the trimmed title, and settles on acceptance', async () => {
const pending = Promise.withResolvers<undefined>()
const renameSession = vi.fn(() => pending.promise)
const { settleSessionRename, ask } = renameDialog(renameSession)
ask('one', '旧标题')
expect(screen.getByRole('dialog', { name: '重命名会话' })).toBeTruthy()
const input = screen.getByLabelText<HTMLInputElement>('会话名称')
expect(input.value).toBe('旧标题')
// Confirming the current title is allowed (that gesture pins an automatic
// title); a blank draft is not, by button or by Enter.
expect(screen.getByRole<HTMLButtonElement>('button', { name: '重命名' }).disabled).toBe(false)
fireEvent.change(input, { target: { value: ' ' } })
expect(screen.getByRole<HTMLButtonElement>('button', { name: '重命名' }).disabled).toBe(true)
fireEvent.keyDown(input, { key: 'Enter' })
expect(renameSession).not.toHaveBeenCalled()
fireEvent.change(input, { target: { value: ' 新标题 ' } })
fireEvent.click(screen.getByRole('button', { name: '重命名' }))
expect(renameSession).toHaveBeenCalledWith(sid('one'), '新标题')
// While the Host call is pending the input locks and closing is blocked.
expect(input.disabled).toBe(true)
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.click(screen.getByRole('button', { name: '取消' }))
expect(settleSessionRename).not.toHaveBeenCalled()
await act(async () => { pending.resolve(undefined) })
expect(settleSessionRename).toHaveBeenCalledOnce()
expect(screen.queryByRole('dialog')).toBeNull()
})
it('Enter confirms only outside an IME composition', () => {
const renameSession = vi.fn(async () => {})
const { ask } = renameDialog(renameSession)
ask('one', 'Old')
const input = screen.getByLabelText<HTMLInputElement>('会话名称')
fireEvent.change(input, { target: { value: 'New' } })
// Enter that commits a composition must not submit.
fireEvent.compositionStart(input)
fireEvent.keyDown(input, { key: 'Enter' })
expect(renameSession).not.toHaveBeenCalled()
fireEvent.compositionEnd(input)
fireEvent.keyDown(input, { key: 'a' })
fireEvent.keyDown(input, { key: 'Enter' })
expect(renameSession).toHaveBeenCalledWith(sid('one'), 'New')
})
it('keeps the dialog open with the rejection surfaced, clears it on edit, and reports a non-Error reason as text', async () => {
const renameSession = vi.fn<SessionRenameDialogInjected['renameSession']>()
.mockRejectedValueOnce(new Error('title write failed'))
.mockRejectedValueOnce('denied')
const { settleSessionRename, ask } = renameDialog(renameSession)
ask('one', 'Old')
const input = screen.getByLabelText<HTMLInputElement>('会话名称')
fireEvent.change(input, { target: { value: 'New' } })
fireEvent.click(screen.getByRole('button', { name: '重命名' }))
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('title write failed') })
expect(input.disabled).toBe(false)
expect(settleSessionRename).not.toHaveBeenCalled()
fireEvent.change(input, { target: { value: 'Newer' } })
expect(screen.queryByRole('alert')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '重命名' }))
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('denied') })
expect(screen.getByRole('dialog', { name: '重命名会话' })).toBeTruthy()
})
it('Cancel, Escape, and Close settle without renaming; a request for another Session starts a fresh draft', () => {
const renameSession = vi.fn(async () => {})
const { settleSessionRename, ask } = renameDialog(renameSession)
ask('one', 'Old')
fireEvent.change(screen.getByLabelText('会话名称'), { target: { value: 'Draft' } })
fireEvent.click(screen.getByRole('button', { name: '取消' }))
expect(settleSessionRename).toHaveBeenCalledOnce()
expect(screen.queryByRole('dialog')).toBeNull()
ask('one', 'Old')
fireEvent.keyDown(document, { key: 'Escape' })
expect(settleSessionRename).toHaveBeenCalledTimes(2)
ask('one', 'Old')
fireEvent.click(screen.getByRole('button', { name: '关闭' }))
expect(settleSessionRename).toHaveBeenCalledTimes(3)
expect(renameSession).not.toHaveBeenCalled()
ask('one', 'First')
fireEvent.change(screen.getByLabelText('会话名称'), { target: { value: 'Edited' } })
ask('two', 'Second')
expect(screen.getByLabelText<HTMLInputElement>('会话名称').value).toBe('Second')
})
})
describe('RowActionToast', () => {
/** The notice surface over a test-owned notice source; dismissal clears the notice the way apply does. */
function toastSurface() {
const toast = createSnapshotStore<RowToastState | null>(null)
const dismissToast = vi.fn(() => { toast.set(null) })
const undoArchive = vi.fn()
const showArchived = vi.fn()
render(
<RowActionToast
{...overlay}
useToast={bindSnapshotSelector(toast)}
dismissToast={dismissToast}
undoArchive={undoArchive}
showArchived={showArchived}
/>,
)
let seq = 0
const notify = (notice: RowToast): void => {
act(() => { toast.set({ ...notice, seq: ++seq }) })
}
return { dismissToast, undoArchive, showArchived, notify }
}
it('renders nothing without a notice', () => {
toastSurface()
expect(screen.queryByRole('alert')).toBeNull()
expect(document.body.textContent).toBe('')
})
it('the archived notice takes itself down, then undoes the archive or shows the archived rows', () => {
const { dismissToast, undoArchive, showArchived, notify } = toastSurface()
notify({ kind: 'archived', sessionId: sid('one') })
expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销或筛选已归档会话')
fireEvent.click(screen.getByRole('button', { name: '撤销' }))
expect(dismissToast).toHaveBeenCalledOnce()
expect(undoArchive).toHaveBeenCalledWith(sid('one'))
expect(callOrder(dismissToast)).toBeLessThan(callOrder(undoArchive))
expect(showArchived).not.toHaveBeenCalled()
expect(screen.queryByRole('alert')).toBeNull()
notify({ kind: 'archived', sessionId: sid('two') })
fireEvent.click(screen.getByRole('button', { name: '筛选已归档会话' }))
expect(dismissToast).toHaveBeenCalledTimes(2)
expect(showArchived).toHaveBeenCalledOnce()
expect(callOrder(dismissToast, 1)).toBeLessThan(callOrder(showArchived))
expect(undoArchive).toHaveBeenCalledOnce()
expect(screen.queryByRole('alert')).toBeNull()
})
it.each([
['pinFailed', '置顶失败,请稍后重试'],
['unpinFailed', '取消置顶失败,请稍后重试'],
['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'],
] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => {
vi.useFakeTimers()
try {
const { dismissToast, notify } = toastSurface()
notify({ kind })
const alert = screen.getByRole('alert')
expect(alert.textContent).toBe(text)
expect(alert.querySelector('button')).toBeNull()
act(() => { vi.advanceTimersByTime(4000) })
expect(dismissToast).toHaveBeenCalledOnce()
expect(screen.queryByRole('alert')).toBeNull()
} finally {
vi.useRealTimers()
}
})
it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', () => {
vi.useFakeTimers()
try {
const { dismissToast, notify } = toastSurface()
notify({ kind: 'archived', sessionId: sid('one') })
act(() => { vi.advanceTimersByTime(4000) })
expect(screen.getByRole('alert')).toBeTruthy()
notify({ kind: 'archived', sessionId: sid('two') })
act(() => { vi.advanceTimersByTime(6999) })
expect(dismissToast).not.toHaveBeenCalled()
act(() => { vi.advanceTimersByTime(1) })
expect(dismissToast).toHaveBeenCalledOnce()
expect(screen.queryByRole('alert')).toBeNull()
} finally {
vi.useRealTimers()
}
})
})
@@ -93,6 +93,14 @@ function dragData(): Pick<DataTransfer, 'effectAllowed' | 'dropEffect' | 'setDat
return { effectAllowed: 'uninitialized', dropEffect: 'none', setData: vi.fn() }
}
// The default child stub: an open directory flow shows its marker; the two
// Session row lists stay empty (their entries have their own spec). A stub
// satisfies the generic render signature only with an erased owner type.
const renderDirectoryFlowOnly: WorkspaceBrowserProps['renderSlot'] = (name: string, owner: object) =>
name === 'sidebar.workspaces.directoryFlow' && (owner as DirectoryFlowOwnerProps).open
? <div data-testid="directory-flow" />
: null
function mount(overrides: Partial<WorkspaceBrowserProps> = {}) {
const store = createWorkspaceViewStore().create()
const props: WorkspaceBrowserProps = {
@@ -109,19 +117,16 @@ function mount(overrides: Partial<WorkspaceBrowserProps> = {}) {
open: vi.fn(),
searchSessions: vi.fn(async () => ({ items: [], hasMore: false })),
searchResultLimit: 20,
renameSession: vi.fn(async () => {}),
forkSession: vi.fn(),
requestSessionRename: vi.fn(),
notifyArchivedNotOpenable: vi.fn(),
renameWorkspace: vi.fn(async () => {}),
deleteWorkspace: vi.fn(async () => {}),
archiveSession: vi.fn(async () => {}),
unarchiveSession: vi.fn(async () => {}),
pinSession: vi.fn(async () => {}),
unpinSession: vi.fn(async () => {}),
insertWorkspaceBefore: vi.fn(async () => {}),
createWorkspace: vi.fn(async () => workspace('created', [])),
useDirectoryFlow: bindSnapshotSelector({ getSnapshot: () => true, subscribe: () => () => {} }),
useHostInfo: selector => selector({ home: undefined, isLoopback: true }),
renderSlot: ((_name: string, owner: { open: boolean }) => (owner.open ? <div data-testid="directory-flow" /> : null)) as never,
renderSlot: renderDirectoryFlowOnly,
t,
...overrides,
}
@@ -630,6 +635,47 @@ describe('WorkspaceBrowser', () => {
expect(screen.queryByText('alpha-s')).toBeNull()
})
it('a title double-click asks for the rename dialog with the row title', () => {
const requestSessionRename = vi.fn()
const open = vi.fn()
const b = mount({
useSessions: hook(sessionState([summary('alpha-s', 1, { displayTitle: 'Alpha session' })])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['alpha-s'])])),
requestSessionRename,
open,
})
fireEvent.click(screen.getByText('alpha'))
fireEvent.doubleClick(screen.getByText('Alpha session'))
expect(requestSessionRename).toHaveBeenCalledWith(sid('alpha-s'), 'Alpha session')
expect(open).not.toHaveBeenCalled()
// The flat list threads the same request.
act(() => { b.store.actions.setGroupBy('flat') })
fireEvent.doubleClick(screen.getByText('Alpha session'))
expect(requestSessionRename).toHaveBeenCalledTimes(2)
})
it('renders both Session row lists for every visible row in the grouped tree and the flat list', () => {
const rendered = vi.fn()
const renderSlot: WorkspaceBrowserProps['renderSlot'] = (name: string, owner: object) => {
rendered(name, owner)
return null
}
const b = mount({
useSessions: hook(sessionState([summary('alpha-s', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['alpha-s'])])),
renderSlot,
})
expect(rendered).not.toHaveBeenCalledWith('sidebar.workspaces.session.menu.item', expect.anything())
fireEvent.click(screen.getByText('alpha'))
const owner = { sessionId: sid('alpha-s'), displayTitle: 'alpha-s' }
expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.menu.item', owner)
expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.row.action', owner)
rendered.mockClear()
act(() => { b.store.actions.setGroupBy('flat') })
expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.menu.item', owner)
expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.row.action', owner)
})
it('shows five sessions by default and clears transient show-all when the Workspace collapses', () => {
const items = Array.from({ length: 7 }, (_, index) => summary(`session-${index + 1}`, 7 - index))
const b = mount({
@@ -769,17 +815,13 @@ describe('WorkspaceBrowser', () => {
expect(screen.getAllByRole('treeitem').slice(1)[0]?.textContent).toContain('two')
})
it('archives a session from the row menu and hides archived rows in both modes', async () => {
const archiveSession = vi.fn(async () => {})
it('hides archived rows in both modes once the archive set carries them', () => {
const b = mount({
useSessions: hook(sessionState([summary('kept-s', 2), summary('gone-s', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['kept-s', 'gone-s'])])),
archiveSession,
})
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“gone-s”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '归档会话' }))
expect(archiveSession).toHaveBeenCalledWith(sid('gone-s'))
expect(screen.getByText('gone-s')).toBeTruthy()
// The archive-set echo hides the row in grouped and flat modes.
rerender(b, { useWorkspaces: hook(workspaceState([workspace('alpha', ['kept-s', 'gone-s'])], [sid('gone-s')])) })
@@ -790,144 +832,6 @@ describe('WorkspaceBrowser', () => {
expect(screen.queryByText('gone-s')).toBeNull()
})
it('logs and keeps the tree when the archive call rejects', async () => {
const rejection = new Error('archive exploded')
const archiveSession = vi.fn(async () => { throw rejection })
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
mount({
useSessions: hook(sessionState([summary('alpha-s', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['alpha-s'])])),
archiveSession,
})
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“alpha-s”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '归档会话' }))
await Promise.resolve()
await Promise.resolve()
expect(warn).toHaveBeenCalledWith('session archive rejected:', rejection)
expect(screen.getByText('alpha-s')).toBeTruthy()
} finally {
warn.mockRestore()
}
})
it('fronts a freshly pinned row in the saved manual orders and seeds missing accounts', async () => {
const pinSession = vi.fn(async () => {})
const b = mount({
useSessions: hook(sessionState([summary('one', 3), summary('two', 2), summary('three', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two', 'three'])])),
pinSession,
})
act(() => { b.store.actions.setSessionOrder('alpha', ['one', 'two', 'three'], {}) })
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“three”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
expect(pinSession).toHaveBeenCalledWith(sid('three'))
await waitFor(() => {
expect(b.store.getSnapshot().sessionOrderByAccount.alpha).toEqual(['three', 'one', 'two'])
})
expect(b.store.getSnapshot().sessionOrderByAccount[FLAT_SESSION_ORDER_KEY]).toEqual(['three', 'one', 'two'])
})
it('saves a Pin reorder without leaving Last updated and leaves positions unchanged on unpin', async () => {
localStorage.clear()
const pinSession = vi.fn(async () => {})
const unpinSession = vi.fn(async () => {})
const b = mount({
useSessions: hook(sessionState([summary('one', 2), summary('two', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two'])])),
pinSession, unpinSession,
})
expect(b.store.getSnapshot().orderBy).toBe('updated')
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“two”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
expect(pinSession).toHaveBeenCalledWith(sid('two'))
await act(async () => { await Promise.resolve() })
expect(b.store.getSnapshot().sessionOrderByAccount).toEqual({
alpha: ['two', 'one'],
[UNGROUPED_KEY]: [],
[FLAT_SESSION_ORDER_KEY]: ['two', 'one'],
})
expect(b.store.getSnapshot().orderBy).toBe('updated')
rerender(b, { useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two'])], [], [sid('two')])) })
fireEvent.click(screen.getByRole('button', { name: '视图选项' }))
fireEvent.click(screen.getByRole('menuitem', { name: '手动排序' }))
const before = b.store.getSnapshot().sessionOrderByAccount
expect(before).toEqual({
alpha: ['one', 'two'],
[UNGROUPED_KEY]: [],
[FLAT_SESSION_ORDER_KEY]: ['one', 'two'],
})
fireEvent.click(screen.getByRole('button', { name: '会话“two”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '取消置顶' }))
expect(unpinSession).toHaveBeenCalledWith(sid('two'))
await act(async () => { await Promise.resolve() })
expect(b.store.getSnapshot().sessionOrderByAccount).toEqual(before)
})
it('keeps newer saved orders when a pending Pin completes', async () => {
const pending = Promise.withResolvers<undefined>()
const pinSession = vi.fn(() => pending.promise)
const b = mount({
useSessions: hook(sessionState([summary('one', 3), summary('two', 2), summary('three', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two', 'three'])])),
pinSession,
})
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“three”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
expect(pinSession).toHaveBeenCalledWith(sid('three'))
act(() => {
b.store.actions.setSessionOrder('alpha', ['two', 'one', 'three'], {})
b.store.actions.setSessionOrder(FLAT_SESSION_ORDER_KEY, ['two', 'one', 'three'], {})
})
await act(async () => { pending.resolve(undefined) })
expect(b.store.getSnapshot().sessionOrderByAccount.alpha).toEqual(['three', 'two', 'one'])
expect(b.store.getSnapshot().sessionOrderByAccount[FLAT_SESSION_ORDER_KEY]).toEqual(['three', 'two', 'one'])
})
it('uses current membership when a Workspace disappears during a pending Pin', async () => {
const pending = Promise.withResolvers<undefined>()
const b = mount({
useSessions: hook(sessionState([summary('one', 2), summary('two', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two'])])),
pinSession: vi.fn(() => pending.promise),
})
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“two”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
rerender(b, { useWorkspaces: hook(workspaceState([])) })
await act(async () => { pending.resolve(undefined) })
expect(b.store.getSnapshot().sessionOrderByAccount).not.toHaveProperty('alpha')
expect(b.store.getSnapshot().sessionOrderByAccount[UNGROUPED_KEY]).toEqual(['two', 'one'])
expect(b.store.getSnapshot().sessionOrderByAccount[FLAT_SESSION_ORDER_KEY]).toEqual(['two', 'one'])
})
it('keeps saved Workspace members with temporarily missing summaries when pinning in Last updated', async () => {
localStorage.clear()
const b = mount({
useSessions: hook(sessionState([summary('one', 3), summary('two', 2), summary('three', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two', 'three'])])),
})
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“one”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
await act(async () => { await Promise.resolve() })
expect(b.store.getSnapshot().sessionOrderByAccount.alpha).toEqual(['one', 'two', 'three'])
rerender(b, {
useSessions: hook(sessionState([summary('one', 3), summary('three', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two', 'three'])], [], [sid('one')])),
})
fireEvent.click(screen.getByRole('button', { name: '会话“three”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
await act(async () => { await Promise.resolve() })
expect(b.store.getSnapshot().orderBy).toBe('updated')
expect(b.store.getSnapshot().sessionOrderByAccount.alpha).toEqual(['three', 'one', 'two'])
})
it.each(['workspace', 'flat', 'ungrouped'] as const)(
'keeps complete %s order through archived filters and both drag partitions',
async (mode) => {
@@ -1000,95 +904,32 @@ describe('WorkspaceBrowser', () => {
.toEqual(['c', 'a', 'b'])
})
it('surfaces pin and unpin rejections as toasts', async () => {
const pinSession = vi.fn(async () => { throw new Error('pin wire down') })
const unpinSession = vi.fn(async () => { throw new Error('unpin wire down') })
const b = mount({
useSessions: hook(sessionState([summary('one', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one'])])),
pinSession, unpinSession,
})
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByRole('button', { name: '会话“one”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '置顶会话' }))
await waitFor(() => {
expect(screen.getByRole('alert').textContent).toContain('置顶失败,请稍后重试')
})
rerender(b, { useWorkspaces: hook(workspaceState([workspace('alpha', ['one'])], [], [sid('one')])) })
fireEvent.click(screen.getByRole('button', { name: '会话“one”的操作' }))
fireEvent.click(screen.getByRole('menuitem', { name: '取消置顶' }))
await waitFor(() => {
expect(screen.getByRole('alert').textContent).toContain('取消置顶失败,请稍后重试')
})
})
it('confirms every archive with an undo/filter toast', async () => {
const archiveSession = vi.fn(async () => {})
const unarchiveSession = vi.fn(async () => {})
const b = mount({
useSessions: hook(sessionState([summary('one', 3), summary('two', 2), summary('three', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two', 'three'])])),
archiveSession, unarchiveSession,
})
fireEvent.click(screen.getByText('alpha'))
const archive = (name: string) => {
fireEvent.click(screen.getByRole('button', { name: `会话“${name}”的操作` }))
fireEvent.click(screen.getByRole('menuitem', { name: '归档会话' }))
}
const flush = () => act(async () => { await Promise.resolve() })
// Every archive confirms with the actionable toast; a back-to-back
// archive replaces the still-showing toast.
archive('two')
await flush()
expect(screen.getByRole('alert').textContent).toContain('会话已归档')
archive('three')
await flush()
expect(screen.getAllByRole('alert')).toHaveLength(1)
// 撤销 unarchives the toast's session and dismisses the banner.
fireEvent.click(screen.getByRole('button', { name: '撤销' }))
expect(unarchiveSession).toHaveBeenCalledWith(sid('three'))
expect(screen.queryByRole('alert')).toBeNull()
// 筛选查看 dismisses the banner and opens the view-options menu.
archive('two')
await flush()
fireEvent.click(screen.getByRole('button', { name: '筛选已归档会话' }))
expect(screen.queryByRole('alert')).toBeNull()
expect(screen.getByRole('menuitem', { name: '显示已归档' })).toBeTruthy()
// A chrome remount (window resized through the rail breakpoint) must not
// replay the toast-action bump and reopen the closed menu.
fireEvent.click(screen.getByRole('menuitem', { name: '显示已归档' }))
expect(screen.queryByRole('menuitem', { name: '显示已归档' })).toBeNull()
rerender(b, { wide: false })
rerender(b, { wide: true })
expect(screen.queryByRole('menuitem', { name: '显示已归档' })).toBeNull()
})
it.each(['show', 'only'] as const)('does not open an archived row in the %s filter', (filter) => {
it.each(['show', 'only'] as const)('does not open an archived row in the %s filter; it raises the not-openable notice instead', (filter) => {
const open = vi.fn()
const notifyArchivedNotOpenable = vi.fn()
const b = mount({
useSessions: hook(sessionState([summary('gone', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['gone'])], [sid('gone')])),
open,
notifyArchivedNotOpenable,
})
act(() => { b.store.actions.setArchivedFilter(filter) })
fireEvent.click(screen.getByText('alpha'))
fireEvent.click(screen.getByText('gone'))
expect(open).not.toHaveBeenCalled()
expect(screen.getByRole('alert').textContent).toBe('已归档对话暂时无法查看,请取消归档后查看')
expect(notifyArchivedNotOpenable).toHaveBeenCalledOnce()
expect(screen.getByText('gone').closest('[role="treeitem"]')?.getAttribute('aria-description'))
.toBe('已归档对话暂时无法查看,请取消归档后查看')
})
it('does not open an archived search result or clear its query', async () => {
it('does not open an archived search result or clear its query; it raises the not-openable notice instead', async () => {
const open = vi.fn()
const notifyArchivedNotOpenable = vi.fn()
const b = mount({
useSessions: hook(sessionState([summary('gone', 1)])),
useWorkspaces: hook(workspaceState([workspace('alpha', ['gone'])], [sid('gone')])),
open,
notifyArchivedNotOpenable,
})
act(() => { b.store.actions.setArchivedFilter('show') })
fireEvent.click(screen.getByRole('button', { name: '搜索会话' }))
@@ -1098,7 +939,7 @@ describe('WorkspaceBrowser', () => {
const row = within(screen.getByRole('tree', { name: '搜索结果' })).getByRole('treeitem')
fireEvent.click(row)
expect(open).not.toHaveBeenCalled()
expect(screen.getByRole('alert').textContent).toBe('已归档对话暂时无法查看,请取消归档后查看')
expect(notifyArchivedNotOpenable).toHaveBeenCalledOnce()
expect(row.getAttribute('aria-description')).toBe('已归档对话暂时无法查看,请取消归档后查看')
expect((input as HTMLInputElement).value).toBe('gone')
})
@@ -15,6 +15,7 @@ import { SessionId } from '@deepseek-ai/dsh-session/types'
import { LayoutController } from '@deepseek-ai/dsh-client-ui-layout/client'
import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client'
import { DirectoryBrowseError, UiWorkspaceService } from '../src/client/navigation.ts'
import { createWorkspaceViewStore, FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts'
const sid = (id: string): SessionId => SessionId(id)
const wid = (id: string): WorkspaceId => id as WorkspaceId
@@ -189,8 +190,14 @@ class FakeWorkspaces implements IWorkspaces {
declare readonly delete: IWorkspaces['delete']
declare readonly insertBefore: IWorkspaces['insertBefore']
declare readonly insertSessionBefore: IWorkspaces['insertSessionBefore']
declare readonly pinSession: IWorkspaces['pinSession']
declare readonly unpinSession: IWorkspaces['unpinSession']
readonly pinCalls: SessionId[] = []
readonly unpinCalls: SessionId[] = []
onPin: IWorkspaces['pinSession'] = async (sessionId) => {
this.list.update(state => ({
...state,
pinnedSessionIds: [sessionId, ...state.pinnedSessionIds.filter(id => id !== sessionId)],
}))
}
constructor(initial: WorkspaceSnapshot) {
this.list = new MutableSource(initial)
@@ -205,6 +212,19 @@ class FakeWorkspaces implements IWorkspaces {
this.unarchiveCalls.push(sessionId)
return this.onUnarchive(sessionId)
}
pinSession(sessionId: SessionId): Promise<void> {
this.pinCalls.push(sessionId)
return this.onPin(sessionId)
}
async unpinSession(sessionId: SessionId): Promise<void> {
this.unpinCalls.push(sessionId)
this.list.update(state => ({
...state,
pinnedSessionIds: state.pinnedSessionIds.filter(id => id !== sessionId),
}))
}
}
const listing: DirectoryListing = {
@@ -262,13 +282,15 @@ function bench(options: BenchOptions = {}) {
const workspaces = new FakeWorkspaces(options.workspaces ?? workspaceState([], [], 'pending'))
const sessions = new FakeSessions(options.sessions ?? sessionState([], 'pending'))
options.configureSessions?.(sessions)
const view = createWorkspaceViewStore().create()
const uiWorkspace = new UiWorkspaceService(
ctx,
directoryPicker.remote,
workspaces,
sessions,
view.actions,
)
return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel }
return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view }
}
describe('UiWorkspaceService', () => {
@@ -403,6 +425,28 @@ describe('UiWorkspaceService', () => {
expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('chosen'), { source: 'mainView' })
})
it('pins on the Host, then leads the Session in its group and flat saved orders; unpin leaves them', async () => {
const b = bench({
workspaces: workspaceState([workspace(wid('a'), [sid('one'), sid('two'), sid('three')])]),
sessions: sessionState([summary('one', { updatedAt: 3 }), summary('two', { updatedAt: 2 }), summary('three', { updatedAt: 1 })]),
})
b.view.actions.setSessionOrder('a', ['one', 'two', 'three'], {})
await b.uiWorkspace.pinSession(sid('three'))
expect(b.workspaces.pinCalls).toEqual([sid('three')])
expect(b.view.getSnapshot().sessionOrderByAccount).toMatchObject({
a: ['three', 'one', 'two'],
[FLAT_SESSION_ORDER_KEY]: ['three', 'one', 'two'],
})
// Unpin is a Host fact only: the saved positions do not move.
await b.uiWorkspace.unpinSession(sid('three'))
expect(b.workspaces.unpinCalls).toEqual([sid('three')])
expect(b.view.getSnapshot().sessionOrderByAccount.a).toEqual(['three', 'one', 'two'])
// A rejected pin writes no order.
b.workspaces.onPin = async () => { throw new Error('pin failed') }
await expect(b.uiWorkspace.pinSession(sid('one'))).rejects.toThrow('pin failed')
expect(b.view.getSnapshot().sessionOrderByAccount.a).toEqual(['three', 'one', 'two'])
})
it('reuses only an unarchived member blank and coalesces concurrent creation', async () => {
const b = bench({
sessions: sessionState([
@@ -696,7 +696,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace.directoryFlow\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:66',
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:99',
},
{
key: 'conversation.input.attachments',
@@ -2372,7 +2372,10 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'root\' (client-ui-layout), so it exists while that entry is mounted',
occupants: [],
occupants: [
'client-ui-workspace SessionRenameDialog id \'workspace.session-rename\'',
'client-ui-workspace RowActionToast id \'workspace.row-toast\'',
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'shell.overlay\', () => ctx.slots.register(\n { name: \'shell.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-layout/src/client/index.ts:91',
@@ -3236,14 +3239,14 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.directoryFlow\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:68',
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:101',
},
{
key: 'sidebar.workspaces.session.menu.action',
key: 'sidebar.workspaces.session.menu.item',
kind: 'list',
scope: 'root',
summary: 'Ordered third-party actions below the built-in Session row-menu actions.',
doc: 'Ordered third-party actions below the built-in Session row-menu actions.\nRegistrations use a fresh id and sort by lower order. Equal-order packaged\nregistrations keep registration sequence; equal-order dynamic registrations\nuse the facade\'s decreasing shadowing priority, so the newer entry comes\nfirst. Priority selects the active registration for one reused id; it does\nnot override order across distinct ids. Contributions render `MenuAction`\nso the shared primitive owns styling, keyboard behavior, dismissal, and\nfocus restoration. An empty list has no visible or accessible secondary group.',
summary: 'The rows of one Session\'s "..." menu, in ascending `order`.',
doc: 'The rows of one Session\'s "..." menu, in ascending `order`. ui-workspace\nregisters the shipped rows here — `pin` (100), `rename` (200), `fork`\n(300), `archive` (400) — so a plugin row is placed by its own `order`\namong them. Use a package-namespaced `id`; reusing a shipped id at\nanother `priority` shadows that row. Each entry renders one\n`MenuItemButton` (`separatorBefore` when it starts a new group), decides\nits own visibility from its own state, and dismisses the menu through the\ninjected `useMenuOpenState` hook after acting. Labels come from the\ncontributing package\'s locale namespace.',
registerOptions: [
{
name: 'id',
@@ -3265,7 +3268,62 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
},
],
ownerProps: [
'/** Point-in-time Session row information supplied to each menu action. */\nexport interface SessionMenuActionOwnerProps {\n /** Session targeted by the open row menu. */\n sessionId: SessionId\n /** Row display title: persisted title, project basename, or Session id. */\n displayTitle: string\n}',
'/** Owner share of one Session row action occurrence: the row the action belongs to. */\nexport interface SessionRowOwnerProps {\n /** Session the row shows. */\n sessionId: SessionId\n /** Row display title: persisted title, project basename, or Session id. */\n displayTitle: string\n}',
],
ownerPropsReferences: [
'SessionId',
],
standardProps: [
'useResource: UseResource',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
'usePanelInfo: UsePanelInfo',
'useSessions: UseSessions',
'useSessionStatus: UseSessionStatus',
'useSessionRetainInfo: UseSessionRetainInfo',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
],
keyDomain: '',
hookContext: 'MenuOpenState',
slotInject: '{ hooks: { menuOpenState: SlotHookFactory<\'sidebar.workspaces.session.menu.item\', UseMenuOpenState> } }',
declaredBy: 'an entry in \'sidebar.workspaces\' (client-ui-workspace), so it exists while that entry is mounted',
occupants: [
'client-ui-workspace PinSessionMenuItem id \'pin\'',
'client-ui-workspace RenameSessionMenuItem id \'rename\'',
'client-ui-workspace ForkSessionMenuItem id \'fork\'',
'client-ui-workspace ArchiveSessionMenuItem id \'archive\'',
],
replaceRisk: 'none',
example: 'const React = require(\'react\')\nconst { MenuItemButton } = require(\'@deepseek-ai/dsh-client-ui-primitives\')\n\nreturn {\n inject: [\'slots\'],\n apply(ctx) {\n const copyLabel = \'Copy Session ID\' // Localize in the contributing package.\n ctx.slots.inject(\'sidebar.workspaces.session.menu.item\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.item\', id: \'copy-session-id\', order: 500 },\n ({ sessionId, useMenuOpenState }) => {\n const [, setMenuOpen] = useMenuOpenState()\n return React.createElement(\n MenuItemButton,\n { onSelect: () => { setMenuOpen(false); void navigator.clipboard.writeText(sessionId) } },\n copyLabel,\n )\n },\n ))\n },\n}',
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:134',
},
{
key: 'sidebar.workspaces.session.row.action',
kind: 'list',
scope: 'root',
summary: 'The hover buttons at the end of one Session row, in ascending `order`, after the "..." menu trigger.',
doc: 'The hover buttons at the end of one Session row, in ascending `order`,\nafter the "..." menu trigger. ui-workspace registers `archive` (100) and\n`pin` (200) here. An entry renders one icon button (or nothing, when its\naction does not apply to the row) and owns the action it performs.',
registerOptions: [
{
name: 'id',
requirement: 'required',
type: 'string',
doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.',
},
{
name: 'order',
requirement: 'optional',
type: 'number',
doc: 'Position among the entries, ascending (default 0).',
},
{
name: 'label',
requirement: 'optional',
type: 'string | (() => string)',
doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.',
},
],
ownerProps: [
'/** Owner share of one Session row action occurrence: the row the action belongs to. */\nexport interface SessionRowOwnerProps {\n /** Session the row shows. */\n sessionId: SessionId\n /** Row display title: persisted title, project basename, or Session id. */\n displayTitle: string\n}',
],
ownerPropsReferences: [
'SessionId',
@@ -3283,10 +3341,13 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'sidebar.workspaces\' (client-ui-workspace), so it exists while that entry is mounted',
occupants: [],
occupants: [
'client-ui-workspace ArchiveSessionRowButton id \'archive\'',
'client-ui-workspace PinSessionRowButton id \'pin\'',
],
replaceRisk: 'none',
example: 'const React = require(\'react\')\nconst { MenuAction } = require(\'@deepseek-ai/dsh-client-ui-primitives\')\n\nreturn {\n inject: [\'slots\'],\n apply(ctx) {\n const copyLabel = \'Copy Session ID\' // Localize in the contributing package.\n ctx.slots.inject(\'sidebar.workspaces.session.menu.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.action\', id: \'copy-session-id\', order: 100 },\n ({ sessionId }) => React.createElement(\n MenuAction,\n { onSelect: () => { void navigator.clipboard.writeText(sessionId) } },\n copyLabel,\n ),\n ))\n },\n}',
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:97',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.session.row.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.row.action\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-workspace/src/client/contract/slots.ts:147',
},
{
key: 'tool.call.images',