feat: pinned tabs, tab context menu and group appearance (0.5.0)

Tab strip: pinned block, drag reorder with cross-boundary pin flip, middle-click close, double-click tab rename (never rewrites the session), context menu (close / others / right / pin / rename), responsive overflow; persistence v2 keeps pinned+title and still reads v1.

Sidebar: per-group colour and icon (20 presets or 1-4 char glyph) plus pinning, stored in the manual overlay 'appearance' map with strict-write/tolerant-read validation; animated group folding with the flower-branch overlay suppressed while rows move.

Tests: pure-logic suites for tabs, appearance partition and overlay parsing; verified by tools/verify-tabs.mjs and tools/verify-appearance.mjs (vitest cannot spawn in this sandbox).
This commit is contained in:
qyh15 2026-10-27 20:11:32 +08:00
parent 7e79aad9f5
commit 133b54d69d
35 changed files with 3753 additions and 402 deletions

View File

@ -140,7 +140,19 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa
挂路由 → 客户端照 `tab-persist.ts` 的 `fetch` 封装去调,注意 `Cache-Control: no-store`。
- **加标签条行为**:状态变换进 `tabs.ts`(纯),store 绑定在 `tab-store.ts`,
渲染在 `SessionTabs.tsx`,落盘走 `tab-persist.ts`;位置模型是「首次入列时定序」,
改动前先读 `tabs.ts` 顶部的 position model 注释。
改动前先读 `tabs.ts` 顶部的 position model 注释。两条不变量:**固定标签恒在未固定
之前**(`moveTab` 在固定区边界夹紧、`togglePinTab` 插到固定区尾/未固定区头),
**标签名与会话标题互不影响**(`renameTab` 只动 `title`)。除 `order` 之外的标签状态
(固定、自定义名)也必须由 `restoreTabsImpl` 原样复原,否则每次重启都丢配置。
- **加一个分组展示元数据(颜色 / 图标 / 置顶等)**:字段进 `types.ts`
(`CategoryAppearance` + `GROUP_COLORS`/`GROUP_ICON_IDS` 白名单)→ 校验进
`host-manual.ts` 的 `parseAppearance`(**严格写、宽容读**:不校验键对应的分类是否
还存在,否则删掉一条 YAML 分类就会让之后每次保存都 400)→ 派生进 `matcher.ts`
(要影响排序就必须放 `effectiveCategories`,只在渲染层排会让拖拽落点与看到的顺序
不一致)→ `tree.ts` 节点带 `appearance` → `rows.tsx` 渲染 → `styles.css` 配色/
动画 → `locales.ts` 双语文案。写路径统一走
`GroupsBrowser.tsx` 的 `updateCategoryAppearance`;**改名要重映射 `appearance` 的键、
删除要清掉**(键空间是 display name,与 `categoryOrder` 一致)。
- **新增平台依赖**:先确认 DSH shell 的 module table 真有那一行,再往
`CLIENT_EXTERNALS` 里加,否则运行时 `require` 会拿不到模块。
@ -149,7 +161,11 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa
- **沙箱内跑不了 vitest**:`spawn` 被 DSH 沙箱拦(EPERM),在普通 PowerShell 终端里跑。
- **`node_modules/.bin/*.CMD` 直调会挂**:pnpm 里嵌套的 pnpm 脚本在 DSH 沙箱下会
`Could not determine executable`,统一用 `node <pnpm.cjs> <script>` 形式。
- **单测语义比源码旧**:`tests/` 是按早期版本写的,0.4.2 的标签条/快切没有覆盖,
改到这些区域时补测试。
- **单测覆盖不齐**:`tests/` 是早期版本写的,现已补 `tests/tabs.test.ts`(标签条纯逻辑:
固定区不变量、拖动夹紧、关闭其他/右侧、持久化恢复);**快切面板
(`quick.ts` / `QuickPanel.tsx`)与分组外观仍无单测**,改到这些区域时补。
- **改持久化格式一律「严格写、宽容读」**:新增字段必须是可选的,旧文件读不进来不算
错;悬挂键(如已删除的分类/会话)不得拒写,否则用户会卡在 400 上再也保存不了;
新字段在 `restore*` 里必须原样带过去(`pinned`/`title` 漏带就等于重启丢配置)。
- **package 版本号语义混乱**:仓库 HEAD 里是 `0.1.0`,但提交里写 `feat(v0.7)`;
重建树统一对齐到安装版的 `0.4.2`。发布前自己定一版号。

View File

@ -64,6 +64,20 @@
- **Distinct row icons**: group rows use a folder glyph, project rows a project glyph
(same as the official workspace browser) — groups and projects are easy to tell apart
### Group appearance (color / icon / pin)
- **Per-group colour**: ten palette accents, painted as a 2px inset bar on the group row
together with a tinted folder glyph
- **Per-group icon**: twenty built-in glyphs taken from the DSH icon set, or a 1–4 character
custom glyph (emoji or latin) — an unknown value falls back to the folder icon instead of
erroring, so data and client versions can move independently
- **Pin groups**: pinned groups sort to the front of the tree; dragging a group across the pin
boundary re-pins it in the same write, so the drop lands where the indicator showed it
- **Animated folding**: expanding/collapsing a group or project animates rows and fades the
flower-branch overlay while they move, so the vine never drifts; animation is skipped for
large subtrees, during drag folding, and under `prefers-reduced-motion`
- Stored in the overlay's `appearance` map — **never in the rule YAML** (see below)
### Search & operations
- **Tree-shaped search**: results keep the three-level structure (category → project → matched
session), matched rows highlighted with a content snippet, 250ms debounce
@ -73,7 +87,8 @@
### Persistence & zero intrusion
- Every manual action (groups, grouping, ordering, rename, hide) is written to the plugin's own
overlay (`~/.dsh/workspace-groups.manual.json`), validated by the host and **written
atomically** (a malformed write returns 400 and keeps the previous file)
atomically** (a malformed write returns 400 and keeps the previous file); the tab strip gets
the same treatment in its own file (`~/.dsh/workspace-groups.tabs.json`)
- **Zero intrusion**: never touches `~/.dsh/storages/workspace.json`, session on-disk
structures, or the official `@deepseek-ai/dsh-client-ui-workspace` package; the rule YAML
is never rewritten
@ -188,7 +203,11 @@ UI operations**, at `$DSH_HOME/workspace-groups.manual.json` (e.g. `~/.dsh/works
"categoryOrder": ["临时", "DSH 插件"],
"workspaceOrder": { "临时": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"] },
"renamed": { "DSH 插件": "插件集" },
"hidden": ["文档"]
"hidden": ["文档"],
"appearance": {
"插件集": { "color": "blue", "icon": "code", "pinned": true },
"临时": { "color": "amber" }
}
}
```
@ -201,6 +220,18 @@ UI operations**, at `$DSH_HOME/workspace-groups.manual.json` (e.g. `~/.dsh/works
- `workspaceOrder` — per-group manual ordering of projects (written by drag ordering).
- `renamed` / `hidden` — UI rename/delete of rule categories (a hidden category's rules become
inert and its matches go top-level); the rule YAML stays untouched.
- `appearance` — per-group presentation keyed by **display name** (same key space as
`categoryOrder`): `color` (one of `red`/`orange`/`amber`/`green`/`teal`/`blue`/`indigo`/
`purple`/`pink`/`gray`), `icon` (a built-in icon id or a 1–4 character glyph) and
`pinned` (sort before unpinned groups). Every sub-field is optional and empty values are
dropped on write, so un-styling a group removes the entry instead of storing `false`/`''`.
A key whose category no longer exists is **tolerated on read and on write** — otherwise
deleting one YAML category would make every later save fail with 400. Colours/icons live
here only: `parseGroupsConfig` drops unknown YAML keys, so a `color:` in the sidecar is
silently ignored.
- **Downgrade note**: an older build rewrites the whole overlay and would drop the
`appearance` map on its next save (same class of risk as `categoryOrder`). Copy
`workspace-groups.manual.json` aside before rolling the plugin back.
- The file is written in full by the browser UI (`PUT /workspace-groups/manual`, atomic
replace); manual edits also take effect on next load. A malformed write returns 400 and
keeps the previous file — the rule YAML is never at risk.
@ -209,12 +240,32 @@ UI operations**, at `$DSH_HOME/workspace-groups.manual.json` (e.g. `~/.dsh/works
|---|---|
| Create group | "新建分组" button in the section header (folder icon), enter a name in the dialog |
| Rename/delete group | hover `⋯` menu on **any** group (rule categories included); deleting sends its projects back to the top level |
| Style a group | `⋯` menu → "颜色与图标…": colour palette, icon grid and a custom-glyph field; every click is written immediately (no OK button) |
| Pin a group | `⋯` menu → "置顶分组" / "取消置顶"; dragging a group across the pin boundary flips it in the same write |
| Drag project into group | drag a project row onto a target group row / any project row inside a group, release to move |
| Reorder projects | drag a project row onto another project row in the same group: **top half = insert before, bottom half = insert after** (indicator shows the spot); all project rows fold while dragging and restore on dragend |
| Reorder top-level projects | drag a top-level row onto another top-level row: **top half = insert before, bottom half = insert after**; order persists under `workspaceOrder["__topLevel__"]` |
| Move out of a group | drop anywhere on the **top-level area** (an insertion line shows the spot — reorder before/after a top-level row, or append below the last row; when the top level is empty a line shows under the last group), or the project row's "移出分组" menu (forced top-level) |
| Reorder groups | drag a group row onto another group row: **top half = move before, bottom half = move after** (indicator shows the spot; all groups fold while dragging, restored on dragend) |
## Session tabs (tab strip)
A horizontal tab strip is seated above the tree — one chip per session you have opened, each
showing its project name and tab label:
- **Open / activate / close**: opening a session adds a chip at the end of the strip; click a
chip to make that session the open one; the `×` closes it.
- **Middle-click** a chip to close it; **drag** a chip to reorder the strip. Pinned chips stay
in the leading pinned block, and a drag never crosses that boundary.
- **Rename a tab**: double-click a chip to give the tab its own label (blank restores the
session title). Renaming the session itself stays in the context menu, so a tab label never
rewrites the session title.
- **Context menu**: pin/unpin, rename tab, rename session, close, **close others** and
**close tabs to the right**. "Close others" always keeps pinned chips.
- **Persisted**: the strip is stored in `$DSH_HOME/workspace-groups.tabs.json` via the host
routes `GET/PUT /workspace-groups/tabs`. A strip stored by an older build (no pin/label
fields) upgrades transparently — absent fields simply read as "unpinned, no custom label".
## Topics
This repo targets automatic discovery by the DSH plugin ecosystem (community marketplaces

View File

@ -54,6 +54,17 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
- **行图标可区分**:分组行是文件夹图标、项目行是项目符号图标(官方同款),
分组与项目一眼可分
### 分组外观(颜色 / 图标 / 置顶)
- **分组配色**:10 种主题色,在分组行左侧画 2px 内嵌色条,并把文件夹图标染色
- **分组图标**:20 个内置图标(取自 DSH 图标集),或 1–4 个字符的自定义字形(emoji/拉丁);
未知值降级为默认文件夹图标而不是报错,数据与客户端版本因此可以各自演进
- **置顶分组**:置顶分组排到树的最前面;把分组拖过置顶边界时会在同一次写入里翻转
置顶状态,落点就是指示线显示的位置
- **折叠动画**:展开/收起分组或项目时行高与透明度过渡,动画期间花枝覆盖层淡出,
藤蔓不会漂移;大树、拖动折叠中、`prefers-reduced-motion` 下自动跳过动画
- 存放在 overlay 的 `appearance` 里,**绝不写进规则 YAML**
### 搜索与操作
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +
内容摘要,防抖 250ms
@ -63,7 +74,7 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
### 持久化与零侵入
- 所有手动操作(分组、归类、排序、改名、隐藏)写入插件自有 overlay
(`~/.dsh/workspace-groups.manual.json`),host 校验后**原子写入**(写坏返回 400 并
保留原文件)
保留原文件);标签栏同样处理,独立文件 `~/.dsh/workspace-groups.tabs.json`
- **零侵入**:不修改 `~/.dsh/storages/workspace.json`、不修改会话落盘结构、不修改官方
`@deepseek-ai/dsh-client-ui-workspace` 包;规则 YAML 永不改写
- **产物自包含**:`lib/` 已构建并随仓库分发,Git 安装无需执行任何依赖脚本
@ -172,7 +183,11 @@ categories:
"categoryOrder": ["临时", "DSH 插件"],
"workspaceOrder": { "临时": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"] },
"renamed": { "DSH 插件": "插件集" },
"hidden": ["文档"]
"hidden": ["文档"],
"appearance": {
"插件集": { "color": "blue", "icon": "code", "pinned": true },
"临时": { "color": "amber" }
}
}
```
@ -183,6 +198,16 @@ categories:
- `workspaceOrder` —— 每个分组内项目的手动排序(拖拽排序写入)。
- `renamed` / `hidden` —— 规则分类的 UI 改名/删除(隐藏后其规则失效,匹配项目
变顶层);规则 YAML 原样保留。
- `appearance` —— 按**显示名**(与 `categoryOrder` 同一键空间)记录分组外观:
`color`(`red`/`orange`/`amber`/`green`/`teal`/`blue`/`indigo`/`purple`/`pink`/`gray`)、
`icon`(内置图标 id 或 1–4 个字符的字形)、`pinned`(排到未置顶分组之前)。三个字段
都可选,写回时会把空值删掉,所以「取消设置」表现为字段消失,而不是存 `false`/`''`。
指向**已不存在分类**的键在读写两侧都被容忍——否则删掉一条 YAML 分类后每次保存都会
400。**颜色/图标只存在这里**:`parseGroupsConfig` 会丢弃 YAML 的未知键,所以在
sidecar 里写 `color:` 会被静默忽略。
- **降级提醒**:旧版本会整文件覆盖 overlay,下一次保存就会丢掉 `appearance`
(与 `categoryOrder` 同级别风险)。回退插件版本前请先备份
`workspace-groups.manual.json`。
- 文件由浏览器 UI 全量写入(`PUT /workspace-groups/manual`,原子替换),手工编辑
同样生效(下次加载时读取);写坏会返回 400 并保留原文件,不会破坏规则 YAML。
@ -190,12 +215,30 @@ categories:
|---|---|
| 新建分组 | 区头「新建分组」按钮(文件夹图标),弹窗输入名称 |
| 重命名/删除分组 | **任意分组**(含规则分类)悬停 `⋯` 菜单;删除后组内项目回顶层 |
| 设置分组外观 | `⋯` 菜单「颜色与图标…」:色板、图标网格、自定义字形;每次点击立即写入(没有「确定」按钮) |
| 置顶分组 | `⋯` 菜单「置顶分组」/「取消置顶」;把分组拖过置顶边界时会在同一次写入里自动翻转 |
| 拖项目进分组 | 拖动项目行到目标分组行 / 分组内任意项目行,松手即移入 |
| 项目排序 | 拖动项目行到同组另一项目行:**上半 = 插到它前、下半 = 插到它后**(指示线显示落点);拖动时所有项目行收起、dragend 恢复 |
| 顶层排序 | 拖动顶层项目行到另一顶层行:**上半 = 插到它前、下半 = 插到它后**;顺序持久化 `workspaceOrder["__topLevel__"]` |
| 移出分组 | 拖到**顶层区域任意位置**(用插入横线指示落点——拖到顶层行前/后、最后一行下方追加、顶层为空时最后分组行下方独立横线),或项目行菜单「移出分组」(强制移到顶层) |
| 分组排序 | 拖动分组行到另一分组行:**上半 = 移到它前、下半 = 移到它后**(指示线显示落点;拖动时所有分组收起、dragend 恢复) |
## 会话标签栏(tab strip)
侧栏树上方常驻一条横向标签栏,每个「打开过的会话」对应一个标签,显示项目名 + 标签名:
- **打开 / 切换 / 关闭**:打开一个会话即在标签栏尾部新增一个标签;点击标签切换会话,
点击 `×` 关闭该标签。
- **中键单击**标签直接关闭;**拖动**标签可调整顺序。固定标签始终留在前部的固定区,
拖动不会跨越该边界。
- **重命名标签**:双击标签即可给标签单独起名(留空恢复为会话标题)。真正的会话改名
仍在右键菜单里,标签名不会改写会话标题。
- **右键菜单**:固定/取消固定、重命名标签、重命名会话、关闭、**关闭其他标签**、
**关闭右侧标签**。「关闭其他标签」始终保留已固定的标签。
- **持久化**:标签栏写入 `$DSH_HOME/workspace-groups.tabs.json`,走宿主路由
`GET/PUT /workspace-groups/tabs`;旧版本写下的标签栏(没有固定/自定义名
字段)可无缝升级——缺字段按「未固定、无自定义名」读取。
## 收录标签(topics)
本仓库面向 DSH 插件生态的自动收录(社区市场靠 GitHub topic 扫描发现),已设置:

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -2446,6 +2446,19 @@ function requireJsYaml() {
const { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump } = /* @__PURE__ */ getDefaultExportFromCjs(requireJsYaml());
//#endregion
//#region src/core/types.ts
/** Whitelist shared by the host write-validation and the client picker. */
const GROUP_COLORS = [
"red",
"orange",
"amber",
"green",
"teal",
"blue",
"indigo",
"purple",
"pink",
"gray"
];
/**
* Legacy label of the fallback bucket. The top-level (ungrouped) concept
* replaced the rendered "未分类" bucket: workspaces in no group render as
@ -2607,6 +2620,16 @@ function parseManualGroups(raw) {
}
manual.renamed = renamed;
}
if (source.appearance !== void 0) {
if (typeof source.appearance !== "object" || source.appearance === null || Array.isArray(source.appearance)) throw new Error("workspace-groups.manual.json: appearance must be a mapping");
const appearance = {};
for (const [key, value] of Object.entries(source.appearance)) {
if (key.trim() === "") throw new Error("workspace-groups.manual.json: appearance keys must be non-empty");
const parsed = parseAppearance(value, key);
if (parsed !== void 0) appearance[key.trim()] = parsed;
}
if (Object.keys(appearance).length > 0) manual.appearance = appearance;
}
if (source.workspaceOrder !== void 0) {
if (typeof source.workspaceOrder !== "object" || source.workspaceOrder === null || Array.isArray(source.workspaceOrder)) throw new Error("workspace-groups.manual.json: workspaceOrder must be a mapping");
const workspaceOrder = {};
@ -2618,6 +2641,36 @@ function parseManualGroups(raw) {
}
return manual;
}
/** Preset icon ids are lowercase kebab-case; anything else must be a short glyph. */
const ICON_PATTERN = /^(?:[a-z][a-z0-9-]{0,23}|[^\s\u0000-\u001f\u007f]{1,4})$/u;
/** Narrow an unknown value to a palette id from the shared whitelist. */
function isGroupColor(value) {
return GROUP_COLORS.some((color) => color === value);
}
/**
* Parse one appearance entry. Unknown sub-keys are dropped; an entry that ends
* up empty is dropped entirely (returns undefined) so the file stays minimal.
*/
function parseAppearance(value, key) {
const field = `appearance["${key}"]`;
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`workspace-groups.manual.json: ${field} must be an object`);
const source = value;
const appearance = {};
if (source.color !== void 0) {
if (!isGroupColor(source.color)) throw new Error(`workspace-groups.manual.json: ${field}.color must be one of: ${GROUP_COLORS.join(", ")}`);
appearance.color = source.color;
}
if (source.icon !== void 0) {
const icon = typeof source.icon === "string" ? source.icon.trim() : "";
if (icon === "" || !ICON_PATTERN.test(icon)) throw new Error(`workspace-groups.manual.json: ${field}.icon must be an icon id or a 1–4 character glyph`);
appearance.icon = icon;
}
if (source.pinned !== void 0) {
if (typeof source.pinned !== "boolean") throw new Error(`workspace-groups.manual.json: ${field}.pinned must be a boolean`);
if (source.pinned) appearance.pinned = true;
}
return Object.keys(appearance).length === 0 ? void 0 : appearance;
}
/** Parse a list of non-empty strings, optionally de-duplicated. */
function parseStringList(value, field, unique) {
if (!Array.isArray(value)) throw new Error(`workspace-groups.manual.json: ${field} must be a list`);
@ -2732,6 +2785,27 @@ function defaultTabsPath() {
return resolve(home, "workspace-groups.tabs.json");
}
/**
* Normalize one tab row (used by both the file reader and the PUT body check, so
* the two can never drift).
*
* @param entry - one element of a stored/`posted` `tabs` array.
* @returns the tab, or null when the row is unusable.
*/
function parsePersistedTab(entry) {
if (typeof entry !== "object" || entry === null) return null;
const row = entry;
if (typeof row.sessionId !== "string" || row.sessionId === "") return null;
if (typeof row.order !== "number" || !Number.isFinite(row.order)) return null;
const pinned = row.pinned === true;
const title = typeof row.title === "string" && row.title.trim() !== "" ? row.title.trim() : void 0;
return {
sessionId: row.sessionId,
order: row.order,
...pinned ? { pinned: true } : {},
...title !== void 0 ? { title } : {}
};
}
/**
* Parse + shape-validate a tabs document.
*
* Tolerant on purpose: this file is a display cache, so a malformed one must
@ -2745,25 +2819,20 @@ function defaultTabsPath() {
function parseTabsDocument(raw) {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
const source = raw;
if (source.version !== 1) return null;
if (source.version !== 1 && source.version !== 2) return null;
if (typeof source.order !== "number" || !Number.isFinite(source.order)) return null;
if (!Array.isArray(source.tabs)) return null;
const tabs = [];
const seen = /* @__PURE__ */ new Set();
for (const entry of source.tabs) {
if (typeof entry !== "object" || entry === null) continue;
const row = entry;
if (typeof row.sessionId !== "string" || row.sessionId === "") continue;
if (typeof row.order !== "number" || !Number.isFinite(row.order)) continue;
if (seen.has(row.sessionId)) continue;
seen.add(row.sessionId);
tabs.push({
sessionId: row.sessionId,
order: row.order
});
const tab = parsePersistedTab(entry);
if (tab === null) continue;
if (seen.has(tab.sessionId)) continue;
seen.add(tab.sessionId);
tabs.push(tab);
}
return {
version: 1,
version: 2,
order: source.order,
tabs
};
@ -2822,7 +2891,7 @@ async function writeTabsDocument(path, document) {
function documentForTabs(state) {
const highest = state.tabs.reduce((max, tab) => Math.max(max, tab.order), 0);
return {
version: 1,
version: 2,
order: Math.max(state.order, highest),
tabs: [...state.tabs]
};
@ -2862,16 +2931,11 @@ function parseTabsPayload(raw) {
const tabs = [];
const seen = /* @__PURE__ */ new Set();
for (const entry of source.tabs) {
if (typeof entry !== "object" || entry === null) continue;
const row = entry;
if (typeof row.sessionId !== "string" || row.sessionId === "") continue;
if (typeof row.order !== "number" || !Number.isFinite(row.order)) continue;
if (seen.has(row.sessionId)) continue;
seen.add(row.sessionId);
tabs.push({
sessionId: row.sessionId,
order: row.order
});
const tab = parsePersistedTab(entry);
if (tab === null) continue;
if (seen.has(tab.sessionId)) continue;
seen.add(tab.sessionId);
tabs.push(tab);
}
return {
order: source.order,

View File

@ -4,7 +4,7 @@
*/
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive';
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
/** Simplified Chinese dictionary. */
export declare const zh: WorkspaceGroupsDict;

View File

@ -36,18 +36,31 @@ export interface RowDropProps {
/** Drop a workspace onto this row. */
onRowDrop?: (event: DragEvent) => void;
}
/**
* Render one stored icon value (preset artwork or a short glyph). Shared by the
* category row's icon slot and the appearance picker grid, so both show exactly
* the same artwork. `fallback` renders when the value is empty or unknown.
*/
export declare function CategoryGlyph({ icon, fallback }: {
icon: string | undefined;
fallback?: ReactNode;
}): JSX.Element;
/**
* One category folder row: toggle, rename/delete menu (every group — rule
* groups via overlay renames/hides), draggable source for group reorder and
* drop target for both workspace moves and group reorders.
*/
export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
node: CategoryNode;
t: T;
onToggle: () => void;
/** Rename/delete actions; the hover menu renders only when both provided. */
onRename?: () => void;
onDelete?: () => void;
/** Pin/unpin this group (menu row). */
onTogglePin?: () => void;
/** Open the appearance dialog (menu row). */
onEditAppearance?: () => void;
/** Group reorder source; the row becomes draggable only when provided. */
onDragStartCategory?: (event: DragEvent) => void;
} & RowDropProps): import("react").JSX.Element;
@ -84,6 +97,27 @@ export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename
export declare function TreeChildren({ children }: {
children: ReactNode;
}): import("react").JSX.Element;
/**
* Animated disclosure body shared by the category and project levels.
*
* Collapsed state renders nothing at all (same DOM as the old
* `{expanded && …}`), so hidden subtrees cost no layout. Expanding plays a
* 0fr→1fr grid animation; collapsing keeps the rows mounted for one closing
* animation and unmounts on its `animationend`. `prefers-reduced-motion`
* unmounts synchronously instead — waiting for an `animationend` that CSS
* disabled would leave the group stuck half-closed.
*
* The flower-branch overlay cannot follow a moving row box, so the animation
* phase exposes `data-wg-animating` (styles.css fades the vine while it is
* present).
*/
export declare function RowGroup({ expanded, className, animate, children }: {
expanded: boolean;
className?: string;
/** Disable the animation for huge subtrees or during drag folding. */
animate?: boolean;
children: ReactNode;
}): JSX.Element | null;
/** One session leaf row. */
export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
node: SessionNode;

View File

@ -23,6 +23,10 @@ export declare const TABS_ROUTE = "/workspace-groups/tabs";
export interface WireTab {
readonly sessionId: string;
readonly order: number;
/** Pinned tabs are restored at the front of the strip. */
readonly pinned?: boolean;
/** A label the user typed for the tab itself (absent = follow the session). */
readonly title?: string;
}
/**
* Fetch the stored strip.

View File

@ -18,7 +18,7 @@
*/
import { type EngineStoreHandle, type StoreHandle } from '@deepseek-ai/dsh-client-store';
import type { SessionId } from '@deepseek-ai/dsh-session/types';
import { closeTabImpl, restoreTabsImpl, touchTabImpl, type SessionTab, type SessionTabsState } from './tabs.ts';
import { closeAfterImpl, closeOthersImpl, closeTabImpl, moveTabImpl, pinTabImpl, renameTabImpl, restoreTabsImpl, touchTabImpl, type SessionTab, type SessionTabsState } from './tabs.ts';
export type { SessionTabsState };
/**
* Session-tab strip actions (bound by the framework, handed to the browser).
@ -43,12 +43,27 @@ export interface SessionTabsActions {
* opened a tab — a slow response must never discard what they just did.
*/
restore: (tabs: readonly SessionTab[]) => void;
/** Pin or unpin one tab (re-inserts it at the block boundary). */
pin: (sessionId: SessionId) => void;
/** Move one tab to an index in the resulting strip (drag and drop). */
move: (sessionId: SessionId, targetIndex: number) => void;
/** Set (or clear, with a blank value) one tab's own label. */
rename: (sessionId: SessionId, title: string | undefined) => void;
/** Close everything except one tab; pinned tabs are kept. */
closeOthers: (sessionId: SessionId) => void;
/** Close every tab after one in display order. */
closeAfter: (sessionId: SessionId) => void;
}
/** Annotation twin of the actions literal below (structural `ActionsDecl`). */
type SessionTabsActionsDecl = {
touch: typeof touchTabImpl;
close: typeof closeTabImpl;
restore: typeof restoreTabsImpl;
pin: typeof pinTabImpl;
move: typeof moveTabImpl;
rename: typeof renameTabImpl;
closeOthers: typeof closeOthersImpl;
closeAfter: typeof closeAfterImpl;
};
/**
* The tab store's registered handle: identity + spec + the instance factory the

View File

@ -2,12 +2,19 @@
* Pure session-tab state: the ordered strip of sessions the user has opened,
* the active one, and each tab's derived presentation.
*
* Position model: a tab's place in the strip is decided ONCE, when it is first
* opened, and never changes afterwards. Switching to a tab, or re-opening a
* session that already has one, leaves the strip exactly as it was — so clicking
* a chip never moves the chip out from under the pointer. Only two events change
* the order: a session opening for the FIRST time (append) and a tab closing
* (remove).
* Position model: a tab's place in the strip is decided when it is first opened
* and otherwise only moves when the USER moves it. Switching to a tab, or
* re-opening a session that already has one, leaves the strip exactly as it was
* — so clicking a chip never moves the chip out from under the pointer. The
* order changes on: a session opening for the FIRST time (append), a tab closing
* (remove), a drag (move), and a pin toggle (which carries the chip across the
* pinned boundary).
*
* The array IS the display order, with one invariant the transforms maintain:
* every pinned tab sits before every unpinned one. New tabs therefore append at
* the end (the unpinned block) and pinning/unpinning re-inserts at the boundary
* between the two blocks. A stored strip from an older build has no `pinned`
* flag, which reads as "unpinned" and satisfies the invariant as-is.
*
* Runtime-free on purpose (same discipline as `store-core.ts` / `quick.ts`):
* the component owns the ref + React state, this module owns every rule, and
@ -31,6 +38,21 @@ export interface SessionTab {
* React move an existing chip's DOM node instead of reconciling it in place.
*/
readonly order: number;
/**
* Pinned tabs stay at the front of the strip and survive `close others`.
*
* Absent means unpinned: that is both the `false` case and the shape an older
* build's stored strip has, so no migration step is needed to read one back.
*/
readonly pinned?: boolean;
/**
* A label the user typed for THIS tab, overriding the session's title.
*
* Kept separate from the session title on purpose: renaming a tab here must
* not rewrite the conversation's own name (which the sidebar and the search
* results show). Absent/empty means "follow the session".
*/
readonly title?: string;
}
/** Feature switch: whether opening a session also surfaces a tab. */
export type TabOpenMode = 'auto' | 'manual';
@ -66,6 +88,91 @@ export declare function appendTab(tabs: readonly SessionTab[], sessionId: Sessio
* @returns a new strip.
*/
export declare function removeTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[];
/**
* Count the leading pinned block.
*
* The transforms keep every pinned tab before every unpinned one, so the pinned
* block is always a prefix and its length is the single index that separates
* the two blocks — which is exactly where a chip lands when it changes sides.
*
* @param tabs - strip in display order.
* @returns how many leading tabs are pinned.
*/
export declare function pinnedCount(tabs: readonly SessionTab[]): number;
/**
* Stable-partition a strip so every pinned tab precedes every unpinned one.
*
* Needed by the restore path: stored tabs are merged onto whatever the startup
* flow already opened, and an append would otherwise park a pinned tab at the
* end of the strip. Already-normalized strips come back as a copy.
*
* @param tabs - any strip.
* @returns a strip satisfying the pinned-first invariant.
*/
export declare function normalizeTabs(tabs: readonly SessionTab[]): SessionTab[];
/**
* Move one tab to a new place in the strip (drag and drop).
*
* `targetIndex` is an index in the RESULTING strip. The move is clamped to the
* tab's own block — a dragged chip can be reordered within the pinned block or
* within the unpinned one, but never carried across that boundary. Crossing it
* is `togglePinTab`'s job, because it changes the tab's meaning rather than
* just its position: pinning is what makes a tab survive `close others`.
*
* @param tabs - strip in display order.
* @param sessionId - the tab being moved.
* @param targetIndex - desired index in the resulting strip.
* @returns a new strip, or the same array when nothing moved.
*/
export declare function moveTab(tabs: readonly SessionTab[], sessionId: SessionId, targetIndex: number): SessionTab[];
/**
* Pin or unpin one tab, re-inserting it at the boundary between the blocks.
*
* Pinning puts the chip at the END of the pinned block (next to the other
* kept tabs) and unpinning at the START of the unpinned one, so a toggle never
* throws a chip to the far end of the strip.
*
* @param tabs - strip in display order.
* @param sessionId - the tab to toggle.
* @returns a new strip, or the same array when the tab is absent.
*/
export declare function togglePinTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[];
/**
* Set or clear one tab's own label.
*
* A blank value CLEARS the override (the chip falls back to the session title)
* rather than storing an empty label, so "rename to nothing" and "rename back to
* the session title" are the same gesture.
*
* @param tabs - strip.
* @param sessionId - the tab to relabel.
* @param title - the new label; blank clears it.
* @returns a new strip, or the same array when the tab is absent.
*/
export declare function renameTab(tabs: readonly SessionTab[], sessionId: SessionId, title: string | undefined): SessionTab[];
/**
* Close every tab except one — pinned tabs stay.
*
* Pinning is exactly how a user says "keep this no matter what"; letting
* `close others` eat the pinned block would make the flag pointless.
*
* @param tabs - strip.
* @param keepSessionId - the tab to keep (plus every pinned one).
* @returns a new strip.
*/
export declare function closeOtherTabs(tabs: readonly SessionTab[], keepSessionId: SessionId): SessionTab[];
/**
* Close every tab after one in display order.
*
* "After" is display order (pinned block first), which is the order the user
* sees; a pinned tab is never after an unpinned one, so this cannot silently
* drop the kept block.
*
* @param tabs - strip in display order.
* @param sessionId - the last tab that stays.
* @returns a new strip, or the same array when the tab is absent.
*/
export declare function closeTabsAfter(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[];
/**
* Order the strip for display: strictly by arrival, regardless of which tab is
* active.
@ -225,3 +332,35 @@ export declare function closeTabImpl(state: SessionTabsState, sessionId: Session
* @param tabs - tabs read from the host, oldest first.
*/
export declare function restoreTabsImpl(state: SessionTabsState, tabs: readonly SessionTab[]): void;
/**
* Store transform: pin or unpin one tab.
* @param state - store draft, mutated in place.
* @param sessionId - the tab to toggle.
*/
export declare function pinTabImpl(state: SessionTabsState, sessionId: SessionId): void;
/**
* Store transform: move one tab to a new index (drag and drop).
* @param state - store draft, mutated in place.
* @param sessionId - the tab being moved.
* @param targetIndex - desired index in the resulting strip.
*/
export declare function moveTabImpl(state: SessionTabsState, sessionId: SessionId, targetIndex: number): void;
/**
* Store transform: set or clear one tab's own label.
* @param state - store draft, mutated in place.
* @param sessionId - the tab to relabel.
* @param title - the new label; blank clears it.
*/
export declare function renameTabImpl(state: SessionTabsState, sessionId: SessionId, title: string | undefined): void;
/**
* Store transform: close every unlisted tab, keeping the pinned ones.
* @param state - store draft, mutated in place.
* @param keepSessionId - the tab to keep.
*/
export declare function closeOthersImpl(state: SessionTabsState, keepSessionId: SessionId): void;
/**
* Store transform: close every tab after one in display order.
* @param state - store draft, mutated in place.
* @param sessionId - the last tab that stays.
*/
export declare function closeAfterImpl(state: SessionTabsState, sessionId: SessionId): void;

View File

@ -8,7 +8,7 @@ import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh
import type { WorkspaceId, WorkspaceView } 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 { type GroupsConfig, type ManualGroups } from '../core/types.ts';
import { type CategoryAppearance, type GroupsConfig, type ManualGroups } from '../core/types.ts';
/** Pending interaction kinds with dedicated Workspace-row presentation. */
export type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question';
/** Current unified UI status by Session (ui-session snapshot). */
@ -70,6 +70,8 @@ export interface CategoryNode {
containsCurrent: boolean;
/** Workspace folders in host order. */
workspaces: readonly WorkspaceGroupNode[];
/** Presentation (color / icon / pin) for this category, when configured. */
appearance?: CategoryAppearance;
}
/** Viewing state consumed by the derivation. */
export interface GroupsTreeView {

View File

@ -10,13 +10,22 @@
* override when present. Hidden rule categories are inert: workspaces that
* would match them become top-level (ungrouped).
*/
import { type GroupCategory, type GroupsConfig, type ManualGroups } from './types.ts';
import { type CategoryAppearance, type GroupCategory, type GroupsConfig, type ManualGroups } from './types.ts';
/** Classify a workspace by rules only; hidden categories are inert. */
export declare function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined;
/** Display name of a rule category: the rename override when present. */
export declare function ruleDisplayName(manual: ManualGroups | undefined, originalName: string): string;
/** Whether a rule category has been hidden by a UI delete. */
export declare function isHiddenRule(manual: ManualGroups | undefined, originalName: string): boolean;
/** Presentation for a category display key, or undefined when unset. */
export declare function categoryAppearance(manual: ManualGroups | undefined, key: string): CategoryAppearance | undefined;
/** Whether a category display key is pinned. */
export declare function isCategoryPinned(manual: ManualGroups | undefined, key: string): boolean;
/**
* Drop empty presentation fields: `undefined` values, `pinned: false`, `icon: ''`.
* Returns undefined when nothing is left, so callers can delete the whole entry.
*/
export declare function pruneAppearance(value: CategoryAppearance): CategoryAppearance | undefined;
/** Rule category display names, in YAML render order (hidden ones excluded). */
export declare function ruleDisplayNames(categories: readonly GroupCategory[], manual: ManualGroups | undefined): string[];
/** Original YAML rule name whose display name equals `key` (undefined when none). */
@ -27,6 +36,11 @@ export declare function originalRuleNameForDisplay(categories: readonly GroupCat
* creation order — unless `manual.categoryOrder` overrides the sequence.
* Top-level (ungrouped) workspaces are never included; they render as
* separate top-level rows after the group folders.
*
* The pin partition is part of DISPLAY ORDER, not a render-time concern:
* pinned groups sort before unpinned ones *within* the manual order, and both
* the tree and the drag-drop landing neighbours read this list, so they can
* never disagree about what sits next to what.
*/
export interface EffectiveCategory {
/** Display key (what the tree renders and assignments reference). */

View File

@ -21,6 +21,28 @@ export interface GroupCategory {
/** Rules; a workspace is classified here when ANY rule matches. */
rules: GroupRule[];
}
/** Theme-safe palette id for a group's accent. */
export type GroupColor = 'red' | 'orange' | 'amber' | 'green' | 'teal' | 'blue' | 'indigo' | 'purple' | 'pink' | 'gray';
/** Whitelist shared by the host write-validation and the client picker. */
export declare const GROUP_COLORS: readonly GroupColor[];
/** Curated icon ids (rendered from @deepseek-ai/dsh-client-ui-primitives). */
export type GroupIconId = 'folder' | 'workspace' | 'code' | 'plugin' | 'skill' | 'data' | 'database' | 'api' | 'plan' | 'goal' | 'light' | 'globe' | 'archive' | 'branch' | 'users' | 'clock' | 'shield' | 'checklist' | 'sparkle' | 'tree';
export declare const GROUP_ICON_IDS: readonly GroupIconId[];
/**
* Presentation metadata for one group. Every field optional.
*
* The explicit `| undefined` on each field is what lets a UI patch clear a
* value (`pruneAppearance` then drops it): under `exactOptionalPropertyTypes`
* a bare `color?: GroupColor` would reject `{ color: undefined }`.
*/
export interface CategoryAppearance {
/** Palette id; the CSS palette lives in styles.css `[data-wg-color]`. */
color?: GroupColor | undefined;
/** `GroupIconId` preset id, or a short glyph (1–4 code units, emoji/latin). */
icon?: string | undefined;
/** Pinned groups sort before unpinned ones (within the manual order). */
pinned?: boolean | undefined;
}
/** The full sidecar configuration (mirrors workspace-groups.yaml). */
export interface GroupsConfig {
/** Category folders, in render order. First match wins. */
@ -41,7 +63,9 @@ export interface GroupsConfig {
*
* All new fields are optional for backward compatibility (files written by
* older plugin versions keep working); rendering falls back to sensible
* defaults when they are absent.
* defaults when they are absent. Note that an older plugin version writes the
* whole file back, which silently drops fields it does not know about — e.g.
* `appearance` (group color / icon / pin) is lost after a downgrade.
*/
export interface ManualGroups {
/**
@ -80,6 +104,13 @@ export interface ManualGroups {
* inert: workspaces matching them become top-level (ungrouped).
*/
hidden?: string[];
/**
* Per-group presentation, keyed by category DISPLAY name (same key space as
* `categoryOrder`). Optional per field; an absent group has no presentation.
* Dangling keys (a YAML category that no longer exists) are tolerated on read
* and on write — see validateManualGroups.
*/
appearance?: Record<string, CategoryAppearance>;
}
/**
* Legacy label of the fallback bucket. The top-level (ungrouped) concept

View File

@ -4,17 +4,39 @@ export interface PersistedTab {
readonly sessionId: string;
/** Arrival key (React list identity). */
readonly order: number;
/** Pinned tabs are restored at the front of the strip. */
readonly pinned?: boolean;
/** A label the user typed for the tab itself (absent = follow the session). */
readonly title?: string;
}
/** The persisted document. */
export interface TabsDocument {
/** Shape version; a mismatch discards the file rather than guessing. */
readonly version: 1;
/**
* Shape version.
*
* 1 = `{sessionId, order}` only (what the shipped build writes); 2 adds the
* optional `pinned` / `title` per tab. A version-1 file is READ as version 2
* with every tab unpinned and untitled — that is exactly what it meant — and
* the next write upgrades it. The two shapes are field-compatible, so no
* conversion step exists: an older build reading a version-2 file would drop
* the extra flags and keep working, which is why this stayed a tolerance
* instead of a hard rejection.
*/
readonly version: 2;
/** Arrival counter, kept ahead of every tab's own order. */
readonly order: number;
readonly tabs: readonly PersistedTab[];
}
/** Default location: `$DSH_HOME/workspace-groups.tabs.json`. */
export declare function defaultTabsPath(): string;
/**
* Normalize one tab row (used by both the file reader and the PUT body check, so
* the two can never drift).
*
* @param entry - one element of a stored/`posted` `tabs` array.
* @returns the tab, or null when the row is unusable.
*/
export declare function parsePersistedTab(entry: unknown): PersistedTab | null;
/**
* Parse + shape-validate a tabs document.
*

View File

@ -1,6 +1,6 @@
{
"name": "@dsh-xhl/workspace-groups",
"version": "0.4.2",
"version": "0.5.0",
"description": "Complete workspace grouping manager for the DSH web sidebar: 分类 → 项目 → 会话 three-level tree, manual group create/rename/delete, drag-and-drop grouping & ordering with insertion indicator, rule-based auto-classification, tree search, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlay, zero core-storage intrusion.",
"keywords": [
"dsh",

View File

@ -32,16 +32,28 @@ import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-
import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'
import {
displayCategoryKeys,
isCategoryPinned,
moveAfter,
moveBefore,
originalRuleNameForDisplay,
pruneAppearance,
resolveCategory,
takenCategoryNames,
} from '../core/matcher.ts'
import { TOP_LEVEL_ORDER_KEY, UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'
import {
GROUP_COLORS,
GROUP_ICON_IDS,
TOP_LEVEL_ORDER_KEY,
UNCATEGORIZED_LABEL,
type CategoryAppearance,
type GroupColor,
type GroupsConfig,
type ManualGroups,
} from '../core/types.ts'
import type { GroupsBrowserProps } from './contract.ts'
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
import { CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, SessionRow, TreeChildren, WorkspaceRow } from './rows.tsx'
import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'
import type { WorkspaceGroupsKey } from './locales.ts'
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { QuickPanel } from './QuickPanel.tsx'
import { SessionTabs } from './SessionTabs.tsx'
@ -55,7 +67,7 @@ const SEARCH_QUERY_MAX_CODE_UNITS = 500
type NormalizedManual = Required<ManualGroups>
const EMPTY_MANUAL: NormalizedManual = {
categories: [], assignments: {}, categoryOrder: [], workspaceOrder: {}, renamed: {}, hidden: [],
categories: [], assignments: {}, categoryOrder: [], workspaceOrder: {}, renamed: {}, hidden: [], appearance: {},
}
/** Materialize optional overlay fields so every update is a plain object edit. */
@ -67,9 +79,42 @@ function normalizeManual(manual: ManualGroups): NormalizedManual {
workspaceOrder: manual.workspaceOrder ?? {},
renamed: manual.renamed ?? {},
hidden: manual.hidden ?? [],
appearance: manual.appearance ?? {},
}
}
/**
* Largest subtree (rows including the level header) that still animates: a
* 100-session project expanding with a grid animation janks the sidebar, so
* wide subtrees snap open instead.
*/
const ANIMATION_ROW_CAP = 40
/**
* Mirrors the host icon validator (`parseAppearance`) so invalid custom glyphs
* fail locally instead of turning the whole overlay PUT into a 400.
*/
const ICON_VALUE_PATTERN = /^(?:[a-z][a-z0-9-]{0,23}|[^\s\u0000-\u001f\u007f]{1,4})$/u
/** Rows a group reveals when expanded (projects + their visible sessions). */
function categoryRowCount(category: CategoryNode): number {
return category.workspaces.reduce((total, workspace) => total + 1 + (workspace.expanded ? workspace.sessions.length : 0), 0)
}
/** Palette id → i18n key for the colour picker (keeps literal key types intact). */
const COLOR_LABEL_KEYS: Record<GroupColor, WorkspaceGroupsKey> = {
red: 'color.red',
orange: 'color.orange',
amber: 'color.amber',
green: 'color.green',
teal: 'color.teal',
blue: 'color.blue',
indigo: 'color.indigo',
purple: 'color.purple',
pink: 'color.pink',
gray: 'color.gray',
}
function sanitizeSearchQuery(value: string): string {
const withoutNul = value.replaceAll('\0', '')
if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul
@ -513,6 +558,13 @@ export function GroupsBrowser({
const [groupDeleting, setGroupDeleting] = useState(false)
const [groupDeleteError, setGroupDeleteError] = useState<string | null>(null)
// Appearance dialog (color / icon / pin) for one group display key. Every
// control applies immediately (optimistic merge + save); there is no OK, so
// `appearanceTarget` also doubles as the open flag.
const [appearanceTarget, setAppearanceTarget] = useState<string | null>(null)
const [appearanceDraft, setAppearanceDraft] = useState<CategoryAppearance>({})
const [appearanceError, setAppearanceError] = useState<string | null>(null)
const takenNames = useMemo(() => takenCategoryNames(config, manual), [config, manual])
const groupTrimmed = groupDraft.trim()
@ -551,6 +603,13 @@ export function GroupsBrowser({
Object.entries(manual.workspaceOrder).map(([key, ids]): [string, string[]] => [key === from ? name : key, ids]),
),
categoryOrder: manual.categoryOrder.map(key => key === from ? name : key),
// Appearance is keyed by display name too: move the entry instead of
// leaving the colour/icon/pin behind under the old name.
appearance: from === undefined || from === name
? manual.appearance
: Object.fromEntries(
Object.entries(manual.appearance).map(([key, value]): [string, CategoryAppearance] => [key === from ? name : key, value]),
),
}
}
@ -591,6 +650,11 @@ export function GroupsBrowser({
assignments,
workspaceOrder,
categoryOrder: manual.categoryOrder.filter(key => key !== name),
// Drop the presentation entry with the group itself (a dangling key would
// silently re-attach if a new group ever reused the name).
appearance: Object.fromEntries(
Object.entries(manual.appearance).filter(([key]) => key !== name),
),
...(originalRule !== undefined
? {
renamed: Object.fromEntries(Object.entries(manual.renamed).filter(([key]) => key !== originalRule)),
@ -705,7 +769,22 @@ export function GroupsBrowser({
const categoryOrder = afterKey !== undefined
? moveAfter(order, draggedKey, afterKey)
: moveBefore(order, draggedKey, beforeKey)
const next: NormalizedManual = { ...manual, categoryOrder }
// Pinned groups sort before unpinned ones, so a drop across that boundary
// only sticks when the dragged group adopts the neighbour's pin state in
// the SAME write. Otherwise the derived order snaps it back and the drop
// looks broken (spec §7.2).
const neighbourKey = afterKey ?? beforeKey
let appearance = manual.appearance
if (neighbourKey !== undefined && isCategoryPinned(manual, neighbourKey) !== isCategoryPinned(manual, draggedKey)) {
const cleaned = pruneAppearance({
...(manual.appearance[draggedKey] ?? {}),
pinned: isCategoryPinned(manual, neighbourKey),
})
appearance = { ...manual.appearance }
if (cleaned === undefined) delete appearance[draggedKey]
else appearance[draggedKey] = cleaned
}
const next: NormalizedManual = { ...manual, categoryOrder, appearance }
await saveManualOverlay(next)
setManual(next)
setManualError(null)
@ -716,6 +795,61 @@ export function GroupsBrowser({
}
}
/**
* Merge a presentation patch for one group and persist the overlay.
* Optimistic: the tree reflects the change immediately and rolls back if the
* host refuses the write (the dialog has no confirm step).
*/
const updateCategoryAppearance = async (key: string, patch: CategoryAppearance): Promise<void> => {
if (manualSaving) return
setManualSaving(true)
const previous = manual
try {
const merged: CategoryAppearance = { ...(manual.appearance[key] ?? {}), ...patch }
const appearance = { ...manual.appearance }
const cleaned = pruneAppearance(merged)
if (cleaned === undefined) delete appearance[key]
else appearance[key] = cleaned
const next: NormalizedManual = { ...manual, appearance }
setManual(next)
await saveManualOverlay(next)
setManualError(null)
} catch (reason) {
setManual(previous)
setManualError(reason instanceof Error ? reason.message : String(reason))
} finally {
setManualSaving(false)
}
}
/** Pin/unpin a group (pinned groups render above the normal order). */
const toggleCategoryPinned = async (key: string): Promise<void> => {
await updateCategoryAppearance(key, { pinned: !isCategoryPinned(manual, key) })
}
/** Appearance currently shown in the dialog (empty while it is closed). */
const appearanceCurrent: CategoryAppearance = appearanceTarget === null
? {}
: (manual.appearance[appearanceTarget] ?? {})
/**
* Commit the custom-icon text field. Invalid input is blocked locally (the
* host would 400 the whole overlay save); an empty field clears the icon.
*/
const commitAppearanceIcon = (): void => {
if (appearanceTarget === null) return
const icon = (appearanceDraft.icon ?? '').trim()
if (icon !== '' && !ICON_VALUE_PATTERN.test(icon)) {
setAppearanceError(t('group.iconInvalid'))
return
}
setAppearanceError(null)
/* Blur fires before a neighbouring click and on every dialog close: skip
the PUT when the field still matches the stored value. */
if (icon === (appearanceCurrent.icon ?? '')) return
void updateCategoryAppearance(appearanceTarget, { icon: icon === '' ? undefined : icon })
}
/**
* Drop on a row. The insertion point is re-derived from the drop event's
* position (top half = before, bottom half = after), so it always matches
@ -1028,6 +1162,13 @@ export function GroupsBrowser({
setGroupDeleteTarget(category.key)
setGroupDeleteError(null)
}}
onGroupTogglePin={() => { void toggleCategoryPinned(category.key) }}
onGroupAppearance={() => {
setAppearanceDraft(manual.appearance[category.key] ?? {})
setAppearanceError(null)
setAppearanceTarget(category.key)
}}
animate={dragging === null}
onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}
onOpenInFolder={openInFolder}
canMoveOut={(workspaceId) => {
@ -1127,6 +1268,109 @@ export function GroupsBrowser({
{groupDeleteError !== null && <div className="wgAddError" role="alert">{groupDeleteError}</div>}
</Modal>
{/* Group appearance dialog: every control writes immediately (optimistic
patch + rollback banner), so the footer is only "done". */}
<Modal
open={appearanceTarget !== null}
onClose={() => { setAppearanceTarget(null) }}
closeLabel={t('group.appearanceDone')}
title={t('group.appearanceTitle')}
footer={(
<Button variant="primary" onClick={() => { setAppearanceTarget(null) }}>{t('group.appearanceDone')}</Button>
)}
>
{appearanceTarget !== null && (
<>
<div className="wgAppearanceSection">
<div className="wgAppearanceLabel">{t('group.color')}</div>
<div className="wgSwatchRow" role="group" aria-label={t('group.color')}>
<button
type="button"
className={`wgSwatch wgSwatchDefault${appearanceCurrent.color === undefined ? ' wgSwatchActive' : ''}`}
aria-pressed={appearanceCurrent.color === undefined}
aria-label={t('group.colorDefault')}
title={t('group.colorDefault')}
disabled={manualSaving}
onClick={() => { void updateCategoryAppearance(appearanceTarget, { color: undefined }) }}
/>
{GROUP_COLORS.map((color) => {
const active = appearanceCurrent.color === color
return (
<button
key={color}
type="button"
className={`wgSwatch${active ? ' wgSwatchActive' : ''}`}
data-wg-color={color}
aria-pressed={active}
aria-label={t(COLOR_LABEL_KEYS[color])}
title={t(COLOR_LABEL_KEYS[color])}
disabled={manualSaving}
onClick={() => { void updateCategoryAppearance(appearanceTarget, { color }) }}
/>
)
})}
</div>
</div>
<div className="wgAppearanceSection">
<div className="wgAppearanceLabel">{t('group.icon')}</div>
<div className="wgIconGrid" role="group" aria-label={t('group.icon')}>
{GROUP_ICON_IDS.map((id) => {
const active = appearanceCurrent.icon === id
return (
<button
key={id}
type="button"
className="wgIconCell"
aria-pressed={active}
aria-label={id}
title={id}
disabled={manualSaving}
onClick={() => {
setAppearanceDraft({ ...appearanceDraft, icon: id })
setAppearanceError(null)
void updateCategoryAppearance(appearanceTarget, { icon: id })
}}
>
<CategoryGlyph icon={id} />
</button>
)
})}
</div>
<input
className="wgRenameInput"
value={appearanceDraft.icon ?? ''}
aria-label={t('group.iconCustom')}
placeholder={t('group.iconDefault')}
disabled={manualSaving}
onChange={(e) => {
setAppearanceDraft({ ...appearanceDraft, icon: e.target.value })
setAppearanceError(null)
}}
onKeyDown={(e) => { if (e.key === 'Enter') commitAppearanceIcon() }}
onBlur={(event) => {
/* A swatch / preset click moves focus out of the field in the
same gesture and writes its own patch — committing the stale
draft here would race it and could overwrite the preset. */
const next = event.relatedTarget
if (next instanceof Element && next.closest('.wgSwatch, .wgIconCell') !== null) return
commitAppearanceIcon()
}}
/>
</div>
<div className="wgAppearanceSection">
<Button
variant={appearanceCurrent.pinned === true ? 'primary' : 'outline'}
disabled={manualSaving}
onClick={() => { void updateCategoryAppearance(appearanceTarget, { pinned: appearanceCurrent.pinned !== true }) }}
>
{appearanceCurrent.pinned === true ? t('group.unpin') : t('group.pin')}
</Button>
</div>
{appearanceError !== null && <div className="wgAddError" role="alert">{appearanceError}</div>}
</>
)}
</Modal>
{/* Workspace rename dialog */}
<Modal
open={renameTarget !== null}
@ -1251,12 +1495,14 @@ function categoriesForCurrent(
}
/** One category section: header row + expanded workspace folders. */
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onMoveOut, canMoveOut, onOpenInFolder }: {
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder }: {
category: CategoryNode
current: SessionId | undefined
now: number
t: GroupsBrowserProps['t']
dragIndicator: DragIndicator
/** Whether the disclosure animation may play (false while a drag folds rows). */
animate: boolean
onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void
onDragLeaveRow: (event: DragEvent) => void
/** Drop factory: bind the target category and the row kind (before/after re-derived at drop time). */
@ -1274,6 +1520,10 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
onFork: (sessionId: SessionId) => void
onGroupRename: () => void
onGroupDelete: () => void
/** Pin/unpin this group from its row menu. */
onGroupTogglePin: () => void
/** Open the appearance dialog for this group. */
onGroupAppearance: () => void
onMoveOut: (workspaceId: WorkspaceId) => void
canMoveOut: (workspaceId: WorkspaceId) => boolean
/** Absent when the host resolved no folder application. */
@ -1291,6 +1541,8 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
onToggle={onToggleCategory}
onRename={onGroupRename}
onDelete={onGroupDelete}
onTogglePin={onGroupTogglePin}
onEditAppearance={onGroupAppearance}
onDragStartCategory={onDragStartCategory}
dropActive={categoryInto}
{...(categoryLine !== undefined ? { insertLine: categoryLine } : {})}
@ -1298,52 +1550,56 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
onRowDragLeave={onDragLeaveRow}
onRowDrop={onDropRow(category.key, { kind: 'category', key: category.key })}
/>
{category.expanded && (
<div role="group">
{category.workspaces.map((workspace) => (
<div key={workspace.workspaceId} role="group">
<WorkspaceRow
node={workspace}
t={t}
onToggle={() => { onToggleWorkspace(workspace.workspaceId as string) }}
onNewSession={() => { onNewSession(workspace.workspaceId) }}
onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}
onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}
canMoveOut={canMoveOut(workspace.workspaceId)}
onMoveOut={() => { onMoveOut(workspace.workspaceId) }}
{...(onOpenInFolder !== undefined
? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }
: {})}
dropActive={false}
{...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'workspace' && dragIndicator.row.key === workspace.workspaceId
? { insertLine: dragIndicator.before ? 'before' : 'after' }
: {})}
onRowDragOver={onDragOverRow({ kind: 'workspace', key: workspace.workspaceId })}
onRowDragLeave={onDragLeaveRow}
onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })}
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
/>
{workspace.expanded && (
<TreeChildren>
{workspace.sessions.map((session) => (
<SessionRow
key={session.id}
node={session}
currentId={current}
now={now}
t={t}
onOpen={onOpen}
onRename={onSessionRename}
onFork={onFork}
onArchive={onSessionArchive}
/>
))}
</TreeChildren>
)}
</div>
))}
</div>
)}
<RowGroup
expanded={category.expanded}
className="wgCategoryChildren"
animate={animate && categoryRowCount(category) <= ANIMATION_ROW_CAP}
>
{category.workspaces.map((workspace) => (
<div key={workspace.workspaceId} role="group">
<WorkspaceRow
node={workspace}
t={t}
onToggle={() => { onToggleWorkspace(workspace.workspaceId as string) }}
onNewSession={() => { onNewSession(workspace.workspaceId) }}
onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}
onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}
canMoveOut={canMoveOut(workspace.workspaceId)}
onMoveOut={() => { onMoveOut(workspace.workspaceId) }}
{...(onOpenInFolder !== undefined
? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }
: {})}
dropActive={false}
{...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'workspace' && dragIndicator.row.key === workspace.workspaceId
? { insertLine: dragIndicator.before ? 'before' : 'after' }
: {})}
onRowDragOver={onDragOverRow({ kind: 'workspace', key: workspace.workspaceId })}
onRowDragLeave={onDragLeaveRow}
onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })}
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
/>
<RowGroup
expanded={workspace.expanded}
className="wgTreeChildren"
animate={animate && workspace.sessions.length <= ANIMATION_ROW_CAP}
>
{workspace.sessions.map((session) => (
<SessionRow
key={session.id}
node={session}
currentId={current}
now={now}
t={t}
onOpen={onOpen}
onRename={onSessionRename}
onFork={onFork}
onArchive={onSessionArchive}
/>
))}
</RowGroup>
</div>
))}
</RowGroup>
</div>
)
}
@ -1424,23 +1680,25 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
onRowDrop={onDropRow(UNCATEGORIZED_KEY, { kind: 'topLevel', key: workspace.workspaceId })}
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
/>
{workspace.expanded && (
<TreeChildren>
{workspace.sessions.map((session) => (
<SessionRow
key={session.id}
node={session}
currentId={current}
now={now}
t={t}
onOpen={onOpen}
onRename={onSessionRename}
onFork={onFork}
onArchive={onSessionArchive}
/>
))}
</TreeChildren>
)}
<RowGroup
expanded={workspace.expanded}
className="wgTreeChildren"
animate={!dragging && workspace.sessions.length <= ANIMATION_ROW_CAP}
>
{workspace.sessions.map((session) => (
<SessionRow
key={session.id}
node={session}
currentId={current}
now={now}
t={t}
onOpen={onOpen}
onRename={onSessionRename}
onFork={onFork}
onArchive={onSessionArchive}
/>
))}
</RowGroup>
</div>
))}
</div>

View File

@ -10,13 +10,32 @@
*
* The active chip is derived, never stored: it is the chip whose session is the
* open one, so clicking a background chip immediately shows that chip active.
*
* Every affordance beyond "click to switch" is an explicit USER gesture, and
* each one maps to exactly one store action: middle-click closes, the context
* menu pins / renames / closes a range, a drag reorders, and a double-click
* edits the tab's own label. None of them can run on their own — the strip stays
* a record of what the user opened.
*/
import { useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { IconCloseFillMedium, StateDot, Tooltip, type StateDotState } from '@deepseek-ai/dsh-client-ui-primitives'
import {
IconCloseFillMedium,
IconPinFillMedium,
StateDot,
Tooltip,
type StateDotState,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { SessionsTabsProps } from './contract.ts'
import { mountTabSeat } from './tab-seat.ts'
import { orderedTabs, projectIndex, tabIndicator, type SessionTab, type SessionTabIndicator } from './tabs.ts'
import {
orderedTabs,
projectIndex,
tabIndicator,
type SessionTab,
type SessionTabIndicator,
} from './tabs.ts'
import { currentSessionId } from './tree.ts'
/** Dot state for one tab (the sidebar's session rows share this vocabulary). */
@ -26,6 +45,50 @@ function dotState(indicator: SessionTabIndicator): StateDotState {
return 'done'
}
/** Where the context menu is pinned, and which chip it belongs to. */
interface MenuAnchor {
readonly sessionId: SessionId
readonly x: number
readonly y: number
}
/** Which chip a drag is hovering, and which half of it. */
interface DropTarget {
readonly sessionId: SessionId
readonly side: 'before' | 'after'
}
/** In-flight inline label edit. */
interface LabelEdit {
readonly sessionId: SessionId
readonly draft: string
}
/** One row of the tab context menu. */
function MenuRow({
label,
onSelect,
disabled = false,
danger = false,
}: {
readonly label: string
readonly onSelect: () => void
readonly disabled?: boolean
readonly danger?: boolean
}) {
return (
<button
type="button"
role="menuitem"
className={`wgTabMenuItem${danger ? ' wgTabMenuDanger' : ''}`}
disabled={disabled}
onClick={onSelect}
>
{label}
</button>
)
}
/**
* Render the session tab strip into the conversation column's head seat.
* @param props - tab store, catalog/status hooks, navigation, locale.
@ -58,6 +121,16 @@ export function SessionTabs({
const [seat, setSeat] = useState<HTMLElement | null>(null)
// The scrolling row, for wheel redirection and keep-active-in-view.
const scrollRef = useRef<HTMLDivElement | null>(null)
// The open context menu, its chip, and its viewport position.
const [menu, setMenu] = useState<MenuAnchor | null>(null)
// The chip whose label is being typed into, plus the in-progress text.
const [editing, setEditing] = useState<LabelEdit | null>(null)
// The chip being dragged and the chip/half it would land on.
const [dragging, setDragging] = useState<SessionId | null>(null)
const [dropTarget, setDropTarget] = useState<DropTarget | null>(null)
// Timestamp of the last drag end: a drop must not also count as a click on
// the chip it landed on (which would navigate away from what was just moved).
const dragEndedAt = useRef(0)
useEffect(() => {
const mounted = mountTabSeat(setSeat)
@ -77,9 +150,8 @@ export function SessionTabs({
// vanished" sweep: a tab is removed when the USER closes it, and by nothing
// else. Trimming automatically also misfires — the catalog is briefly empty on
// every load, which deleted restored tabs before the sessions arrived.
//
// Arrival order is the only order: the active tab is marked, never moved.
const display = useMemo(() => orderedTabs(tabs, currentId), [tabs, currentId])
const index = useMemo(() => new Map(display.map((tab, at) => [tab.sessionId, at])), [display])
// With the row scrollable, the active chip can sit outside the viewport —
// e.g. after clicking a session in the sidebar that has a tab far to the
@ -93,99 +165,316 @@ export function SessionTabs({
chip?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
}, [currentId, display.length])
// Dismiss the context menu on any interaction outside it. Pointerdown covers
// both buttons; Escape and a viewport change (which would leave a fixed menu
// pointing at the wrong chip) close it too. `capture` matters for the scroll
// case: the strip's own row scrolls without bubbling a scroll event up.
useEffect(() => {
if (menu === null) return
const dismiss = (): void => { setMenu(null) }
const onPointerDown = (event: PointerEvent): void => {
const target = event.target
if (target instanceof Element && target.closest('.wgTabMenu') !== null) return
dismiss()
}
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') dismiss()
}
document.addEventListener('pointerdown', onPointerDown, true)
document.addEventListener('keydown', onKeyDown)
window.addEventListener('resize', dismiss)
window.addEventListener('scroll', dismiss, true)
return () => {
document.removeEventListener('pointerdown', onPointerDown, true)
document.removeEventListener('keydown', onKeyDown)
window.removeEventListener('resize', dismiss)
window.removeEventListener('scroll', dismiss, true)
}
}, [menu])
if (seat === null || display.length === 0) return null
return createPortal(
<div className="wgTabs" role="tablist" aria-label={t('tabs.aria')}>
/** Commit the in-flight label edit (blank clears the override). */
const commitEdit = (): void => {
if (editing === null) return
actions.rename(editing.sessionId, editing.draft)
setEditing(null)
}
/** Start editing a tab's own label, pre-filled with what the chip shows. */
const startEdit = (sessionId: SessionId, current: string): void => {
setMenu(null)
setEditing({ sessionId, draft: current })
}
/** Translate a drop onto `target` into an index in the resulting strip. */
const dropIndexFor = (draggedSessionId: SessionId, target: DropTarget): number | null => {
const from = index.get(draggedSessionId)
const at = index.get(target.sessionId)
if (from === undefined || at === undefined || from === at) return null
// Insertion index in the CURRENT strip, then corrected for the removal the
// move implies: removing a chip before the insertion point shifts it left.
const insertion = at + (target.side === 'after' ? 1 : 0)
return from < insertion ? insertion - 1 : insertion
}
const chips = display.map((tab: SessionTab, at: number) => {
const summary = list.byId[tab.sessionId]
// A restored tab can render before its catalog row arrives. Show the
// session id meanwhile rather than an empty chip — the tab is real, and
// the title fills in as soon as the catalog catches up.
const sessionLabel = summary === undefined
? tab.sessionId
: summary.blank ? t('newSession') : summary.displayTitle
// The user's own label wins over the session title; blank means "follow the
// session", so the override is absent rather than empty.
const label = tab.title ?? sessionLabel
const active = tab.sessionId === currentId
const pinned = tab.pinned === true
const indicator = tabIndicator(summary, statuses.get(tab.sessionId))
// The project this session belongs to. Absent for a session that is in
// no workspace (a bare session, or one just created before the
// registry caught up) — the chip then shows the title alone rather
// than a placeholder.
const project = projects.get(tab.sessionId)
// Title attribute carries the full pair plus the directory, so the
// truncated chip text is recoverable on hover.
const tip = project === undefined
? label
: `${project.label} · ${label}\n${project.path}`
const drop = dropTarget !== null && dropTarget.sessionId === tab.sessionId ? dropTarget.side : null
const isEditing = editing !== null && editing.sessionId === tab.sessionId
const draft = isEditing && editing !== null ? editing.draft : ''
const className = [
'wgTab',
active ? 'wgTabActive' : '',
pinned ? 'wgTabPinned' : '',
dragging === tab.sessionId ? 'wgTabDragging' : '',
drop === 'before' ? 'wgTabDropBefore' : '',
drop === 'after' ? 'wgTabDropAfter' : '',
].filter(part => part !== '').join(' ')
return (
<div
className="wgTabsScroll"
ref={scrollRef}
onWheel={(event) => {
// A plain wheel reports only `deltaY`, and the overflow here is
// horizontal, so without this the wheel would do nothing over the
// strip (or scroll the transcript behind it). Redirect the dominant
// delta to scrollLeft, and only swallow the event once there is
// somewhere left to scroll — otherwise a wheel at either end keeps
// propagating and the page still scrolls normally.
const el = event.currentTarget
if (el.scrollWidth <= el.clientWidth) return
const delta = Math.abs(event.deltaY) > Math.abs(event.deltaX) ? event.deltaY : event.deltaX
if (delta === 0) return
const atStart = el.scrollLeft <= 0 && delta < 0
const atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 1 && delta > 0
if (atStart || atEnd) return
el.scrollLeft += delta
key={tab.order}
className={className}
data-tab-session={tab.sessionId}
{...(project !== undefined ? { 'data-tab-project': project.workspaceId } : {})}
draggable={!isEditing}
onAuxClick={(event) => {
// Middle click closes, the way every other tab strip behaves. Only
// button 1: a right click opens the menu instead.
if (event.button !== 1) return
event.preventDefault()
actions.close(tab.sessionId)
}}
onContextMenu={(event) => {
event.preventDefault()
setEditing(null)
setMenu({
sessionId: tab.sessionId,
// Clamp inside the viewport so a chip near the right edge does not
// open a menu that runs off-screen.
x: Math.min(event.clientX, window.innerWidth - 208),
y: Math.min(event.clientY, window.innerHeight - 240),
})
}}
onDragStart={(event) => {
event.dataTransfer.effectAllowed = 'move'
event.dataTransfer.setData('text/plain', tab.sessionId)
setDragging(tab.sessionId)
setMenu(null)
}}
onDragOver={(event) => {
if (dragging === null || dragging === tab.sessionId) return
event.preventDefault()
event.dataTransfer.dropEffect = 'move'
const rect = event.currentTarget.getBoundingClientRect()
const side = event.clientX < rect.left + rect.width / 2 ? 'before' : 'after'
setDropTarget({ sessionId: tab.sessionId, side })
}}
onDrop={(event) => {
event.preventDefault()
if (dragging !== null && dropTarget !== null) {
const target = dropIndexFor(dragging, dropTarget)
if (target !== null) actions.move(dragging, target)
}
setDragging(null)
setDropTarget(null)
dragEndedAt.current = Date.now()
}}
onDragEnd={() => {
setDragging(null)
setDropTarget(null)
dragEndedAt.current = Date.now()
}}
>
{display.map((tab: SessionTab) => {
const summary = list.byId[tab.sessionId]
// A restored tab can render before its catalog row arrives. Show the
// session id meanwhile rather than an empty chip — the tab is real, and
// the title fills in as soon as the catalog catches up.
const label = summary === undefined
? tab.sessionId
: summary.blank ? t('newSession') : summary.displayTitle
const active = tab.sessionId === currentId
const indicator = tabIndicator(summary, statuses.get(tab.sessionId))
// The project this session belongs to. Absent for a session that is in
// no workspace (a bare session, or one just created before the
// registry caught up) — the chip then shows the title alone rather
// than a placeholder.
const project = projects.get(tab.sessionId)
// Title attribute carries the full pair plus the directory, so the
// truncated chip text is recoverable on hover.
const tip = project === undefined
? label
: `${project.label} · ${label}\n${project.path}`
return (
<div
key={tab.order}
className={`wgTab${active ? ' wgTabActive' : ''}`}
data-tab-session={tab.sessionId}
{...(project !== undefined ? { 'data-tab-project': project.workspaceId } : {})}
{isEditing ? (
<input
className="wgTabRename"
value={draft}
placeholder={t('tabs.renamePlaceholder')}
aria-label={t('tabs.rename')}
autoFocus
onFocus={(event) => { event.currentTarget.select() }}
onChange={(event) => { setEditing({ sessionId: tab.sessionId, draft: event.target.value }) }}
onClick={(event) => { event.stopPropagation() }}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault()
commitEdit()
} else if (event.key === 'Escape') {
event.preventDefault()
setEditing(null)
}
}}
onBlur={() => { commitEdit() }}
/>
) : (
<>
<button
type="button"
role="tab"
aria-selected={active}
className="wgTabMain"
title={pinned ? `${t('tabs.pinned')} · ${tip}` : tip}
onClick={() => {
if (Date.now() - dragEndedAt.current < 250) return
activate(tab.sessionId)
}}
onDoubleClick={() => { startEdit(tab.sessionId, label) }}
>
<span className="wgTabStatus" data-tab-state={indicator.attention ? 'attention' : indicator.running ? 'running' : indicator.unread ? 'unread' : indicator.settled ? 'settled' : 'idle'}>
<StateDot state={dotState(indicator)} />
</span>
{/* Two stacked lines, folder-style: the project (short, quiet)
over the session title (long, primary). The project line is
omitted for a session in no workspace, which lets the title
use the full height rather than leaving a blank row. */}
<span className="wgTabText">
{project !== undefined && (
<span className="wgTabProject" title={project.path}>{project.label}</span>
)}
<span className="wgTabLabel">{label}</span>
</span>
</button>
{pinned && (
<span className="wgTabPin" title={t('tabs.pinned')} aria-hidden>
<IconPinFillMedium />
</span>
)}
<Tooltip label={t('tabs.close')} side="top" delayMs={600}>
<button
type="button"
role="tab"
aria-selected={active}
className="wgTabMain"
title={tip}
onClick={() => { activate(tab.sessionId) }}
onDoubleClick={() => { rename(tab.sessionId, label) }}
className="wgTabClose"
aria-label={`${t('tabs.close')} ${label}`}
onClick={(event) => {
event.stopPropagation()
actions.close(tab.sessionId)
}}
>
<span className="wgTabStatus" data-tab-state={indicator.attention ? 'attention' : indicator.running ? 'running' : indicator.unread ? 'unread' : indicator.settled ? 'settled' : 'idle'}>
<StateDot state={dotState(indicator)} />
</span>
{/* Two stacked lines, folder-style: the project (short, quiet)
over the session title (long, primary). The project line is
omitted for a session in no workspace, which lets the title
use the full height rather than leaving a blank row. */}
<span className="wgTabText">
{project !== undefined && (
<span className="wgTabProject" title={project.path}>{project.label}</span>
)}
<span className="wgTabLabel">{label}</span>
</span>
<IconCloseFillMedium />
</button>
<Tooltip label={t('tabs.close')} side="top" delayMs={600}>
<button
type="button"
className="wgTabClose"
aria-label={`${t('tabs.close')} ${label}`}
onClick={(event) => {
event.stopPropagation()
actions.close(tab.sessionId)
}}
>
<IconCloseFillMedium />
</button>
</Tooltip>
</div>
)
})}
</Tooltip>
</>
)}
</div>
</div>,
)
})
// The menu's chip, resolved against the current strip: a menu opened on a chip
// that has since disappeared renders nothing rather than acting on a stale id.
const menuTab = menu === null ? undefined : display.find(tab => tab.sessionId === menu.sessionId)
const menuIndex = menuTab === undefined ? -1 : at(display, menuTab)
const menuLabel = menuTab === undefined
? ''
: menuTab.title ?? list.byId[menuTab.sessionId]?.displayTitle ?? menuTab.sessionId
const menuPinned = menuTab?.pinned === true
const canCloseRight = menuIndex >= 0 && menuIndex < display.length - 1
return createPortal(
<>
<div className="wgTabs" role="tablist" aria-label={t('tabs.aria')}>
<div
className="wgTabsScroll"
ref={scrollRef}
onWheel={(event) => {
// A plain wheel reports only `deltaY`, and the overflow here is
// horizontal, so without this the wheel would do nothing over the
// strip (or scroll the transcript behind it). Redirect the dominant
// delta to scrollLeft, and only swallow the event once there is
// somewhere left to scroll — otherwise a wheel at either end keeps
// propagating and the page still scrolls normally.
const el = event.currentTarget
if (el.scrollWidth <= el.clientWidth) return
const delta = Math.abs(event.deltaY) > Math.abs(event.deltaX) ? event.deltaY : event.deltaX
if (delta === 0) return
const atStart = el.scrollLeft <= 0 && delta < 0
const atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 1 && delta > 0
if (atStart || atEnd) return
el.scrollLeft += delta
event.preventDefault()
}}
>
{chips}
</div>
</div>
{menu !== null && menuTab !== undefined && createPortal(
<div
className="wgTabMenu"
role="menu"
aria-label={menuLabel}
style={{ left: menu.x, top: menu.y }}
>
<MenuRow
label={menuPinned ? t('tabs.unpin') : t('tabs.pin')}
onSelect={() => {
actions.pin(menu.sessionId)
setMenu(null)
}}
/>
<MenuRow
label={t('tabs.rename')}
onSelect={() => { startEdit(menu.sessionId, menuLabel) }}
/>
<MenuRow
label={t('tabs.renameSession')}
onSelect={() => {
setMenu(null)
rename(menu.sessionId, menuLabel)
}}
/>
<div className="wgTabMenuSeparator" role="separator" />
<MenuRow
label={t('tabs.close')}
onSelect={() => {
setMenu(null)
actions.close(menu.sessionId)
}}
/>
<MenuRow
label={t('tabs.closeOthers')}
onSelect={() => {
setMenu(null)
actions.closeOthers(menu.sessionId)
}}
/>
<MenuRow
label={t('tabs.closeRight')}
disabled={!canCloseRight}
onSelect={() => {
setMenu(null)
actions.closeAfter(menu.sessionId)
}}
/>
</div>,
document.body,
)}
</>,
seat,
)
}
/** Index of one tab in the strip, used by the menu's range actions. */
function at(tabs: readonly SessionTab[], target: SessionTab): number {
return tabs.findIndex(tab => tab.sessionId === target.sessionId)
}

View File

@ -139,7 +139,12 @@ export function apply(ctx: Context): void {
void loadTabs().then((tabs) => {
if (cancelled) return
if (tabs.length > 0) {
tabWrites.restore(tabs.map(tab => ({ sessionId: tab.sessionId as SessionId, order: tab.order })))
tabWrites.restore(tabs.map(tab => ({
sessionId: tab.sessionId as SessionId,
order: tab.order,
...(tab.pinned === true ? { pinned: true } : {}),
...(tab.title !== undefined ? { title: tab.title } : {}),
})))
}
hydrated = true
}).catch(() => {

View File

@ -48,6 +48,28 @@ export type WorkspaceGroupsKey =
| 'group.deleteCancel'
| 'group.nameDuplicate'
| 'group.nameReserved'
| 'group.pin'
| 'group.unpin'
| 'group.pinned'
| 'group.appearance'
| 'group.appearanceTitle'
| 'group.appearanceDone'
| 'group.color'
| 'group.colorDefault'
| 'group.icon'
| 'group.iconDefault'
| 'group.iconCustom'
| 'group.iconInvalid'
| 'color.red'
| 'color.orange'
| 'color.amber'
| 'color.green'
| 'color.teal'
| 'color.blue'
| 'color.indigo'
| 'color.purple'
| 'color.pink'
| 'color.gray'
| 'section.topLevel'
| 'manual.saveError'
| 'session.new'
@ -85,6 +107,15 @@ export type WorkspaceGroupsKey =
| 'tabs.aria'
| 'tabs.close'
| 'tabs.archive'
| 'tabs.pin'
| 'tabs.unpin'
| 'tabs.pinned'
| 'tabs.rename'
| 'tabs.renameSession'
| 'tabs.renamePlaceholder'
| 'tabs.closeOthers'
| 'tabs.closeRight'
| 'tabs.dragHint'
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>
@ -132,6 +163,28 @@ export const zh: WorkspaceGroupsDict = {
'group.deleteCancel': '取消删除',
'group.nameDuplicate': '已存在同名分组',
'group.nameReserved': '该名称不可用',
'group.pin': '置顶分组',
'group.unpin': '取消置顶',
'group.pinned': '已置顶',
'group.appearance': '颜色与图标…',
'group.appearanceTitle': '分组外观',
'group.appearanceDone': '完成',
'group.color': '颜色',
'group.colorDefault': '默认',
'group.icon': '图标',
'group.iconDefault': '默认图标',
'group.iconCustom': '自定义字符',
'group.iconInvalid': '图标需为预设图标或 1–4 个字符',
'color.red': '红色',
'color.orange': '橙色',
'color.amber': '琥珀',
'color.green': '绿色',
'color.teal': '青色',
'color.blue': '蓝色',
'color.indigo': '靛蓝',
'color.purple': '紫色',
'color.pink': '粉色',
'color.gray': '灰色',
'section.topLevel': '顶层项目',
'manual.saveError': '分组变更保存失败',
'session.new': '新建会话',
@ -169,6 +222,15 @@ export const zh: WorkspaceGroupsDict = {
'tabs.aria': '已打开的会话',
'tabs.close': '关闭标签',
'tabs.archive': '归档',
'tabs.pin': '固定标签',
'tabs.unpin': '取消固定',
'tabs.pinned': '已固定(关闭其他时保留)',
'tabs.rename': '重命名标签',
'tabs.renameSession': '重命名会话…',
'tabs.renamePlaceholder': '标签名,留空恢复会话标题',
'tabs.closeOthers': '关闭其他标签',
'tabs.closeRight': '关闭右侧标签',
'tabs.dragHint': '拖动可排序',
}
/** English dictionary. */
@ -215,6 +277,28 @@ export const en: WorkspaceGroupsDict = {
'group.deleteCancel': 'Cancel delete',
'group.nameDuplicate': 'A group with this name already exists',
'group.nameReserved': 'This name is not available',
'group.pin': 'Pin group',
'group.unpin': 'Unpin group',
'group.pinned': 'Pinned',
'group.appearance': 'Color & icon…',
'group.appearanceTitle': 'Group appearance',
'group.appearanceDone': 'Done',
'group.color': 'Color',
'group.colorDefault': 'Default',
'group.icon': 'Icon',
'group.iconDefault': 'Default icon',
'group.iconCustom': 'Custom character',
'group.iconInvalid': 'Use a preset icon or 1–4 characters',
'color.red': 'Red',
'color.orange': 'Orange',
'color.amber': 'Amber',
'color.green': 'Green',
'color.teal': 'Teal',
'color.blue': 'Blue',
'color.indigo': 'Indigo',
'color.purple': 'Purple',
'color.pink': 'Pink',
'color.gray': 'Gray',
'section.topLevel': 'Top-level projects',
'manual.saveError': 'Could not save group changes',
'session.new': 'New Session',
@ -252,4 +336,13 @@ export const en: WorkspaceGroupsDict = {
'tabs.aria': 'Open sessions',
'tabs.close': 'Close tab',
'tabs.archive': 'Archive',
'tabs.pin': 'Pin tab',
'tabs.unpin': 'Unpin tab',
'tabs.pinned': 'Pinned (kept by Close others)',
'tabs.rename': 'Rename tab',
'tabs.renameSession': 'Rename session…',
'tabs.renamePlaceholder': 'Tab name — blank restores the session title',
'tabs.closeOthers': 'Close other tabs',
'tabs.closeRight': 'Close tabs to the right',
'tabs.dragHint': 'Drag to reorder',
}

View File

@ -8,22 +8,45 @@
* workspace rows, standing for their containing category) are drop targets.
* The payload is a custom dataTransfer type so only in-plugin drags land.
*/
import { useState, type DragEvent, type ReactNode } from 'react'
import { useEffect, useRef, useState, type AnimationEvent, type DragEvent, type ReactNode } from 'react'
import {
IconApiOutlineMedium,
IconArchiveOutlineRegular,
IconArchiveOutlineMedium,
IconBranchOutlineMedium,
IconBranchOutlineRegular,
IconChecklistOutlineMedium,
IconClockOutlineMedium,
IconCodeOutlineMedium,
IconCordisPluginOutlineMedium,
IconDataOutlineMedium,
IconDatabaseOutlineMedium,
IconEditOutlineRegular,
IconEllipsisOutlineRegular,
IconFolderCloseMedium,
IconFolderOpenMedium,
IconFolderOpenOutlineRegular,
IconGlobeOutlineMedium,
IconGoalOutlineMedium,
IconLightOutlineMedium,
IconPinFillMedium,
IconPinOutlineRegular,
IconPlanOutlineMedium,
IconPlusOutlineRegular,
IconProjectAddOutlineRegular,
IconRightUpOutlineRegular,
IconShieldOutlineMedium,
IconSkillOutlineMedium,
IconSlidersTwoOutlineRegular,
IconSparkleMedium,
IconTreeCornerMedium,
IconTriangleRightFillMedium,
IconTrashOutlineRegular,
IconUsersOutlineMedium,
IconWorkspaceTreeOutlineMedium,
Menu,
StateDot,
type MenuEntry,
type StateDotState,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
@ -90,31 +113,101 @@ export interface RowDropProps {
onRowDrop?: (event: DragEvent) => void
}
/**
* Preset group icon ids → primitives artwork. Medium stroke to match the
* folder glyph used by unprefixed groups. Keyed by plain string so an id from
* a newer host (or a hand-edited JSON file) degrades instead of throwing.
*/
const CATEGORY_ICONS: Record<string, ReactNode> = {
folder: <IconFolderCloseMedium />,
workspace: <IconWorkspaceTreeOutlineMedium />,
code: <IconCodeOutlineMedium />,
plugin: <IconCordisPluginOutlineMedium />,
skill: <IconSkillOutlineMedium />,
data: <IconDataOutlineMedium />,
database: <IconDatabaseOutlineMedium />,
api: <IconApiOutlineMedium />,
plan: <IconPlanOutlineMedium />,
goal: <IconGoalOutlineMedium />,
light: <IconLightOutlineMedium />,
globe: <IconGlobeOutlineMedium />,
archive: <IconArchiveOutlineMedium />,
branch: <IconBranchOutlineMedium />,
users: <IconUsersOutlineMedium />,
clock: <IconClockOutlineMedium />,
shield: <IconShieldOutlineMedium />,
checklist: <IconChecklistOutlineMedium />,
sparkle: <IconSparkleMedium />,
tree: <IconTreeCornerMedium />,
}
/**
* Resolve a stored `appearance.icon` value: a preset id renders the artwork,
* a 1–4 character glyph renders as text, and anything else returns null so the
* caller keeps the default folder icon.
*/
function resolveCategoryIcon(icon: string | undefined): ReactNode | null {
if (icon === undefined || icon === '') return null
const preset = CATEGORY_ICONS[icon]
if (preset !== undefined) return preset
return Array.from(icon).length <= 4 ? <span className="wgCategoryGlyph">{icon}</span> : null
}
/**
* Render one stored icon value (preset artwork or a short glyph). Shared by the
* category row's icon slot and the appearance picker grid, so both show exactly
* the same artwork. `fallback` renders when the value is empty or unknown.
*/
export function CategoryGlyph({ icon, fallback = null }: { icon: string | undefined; fallback?: ReactNode }): JSX.Element {
return <>{resolveCategoryIcon(icon) ?? fallback}</>
}
/**
* One category folder row: toggle, rename/delete menu (every group — rule
* groups via overlay renames/hides), draggable source for group reorder and
* drop target for both workspace moves and group reorders.
*/
export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
export function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
node: CategoryNode
t: T
onToggle: () => void
/** Rename/delete actions; the hover menu renders only when both provided. */
onRename?: () => void
onDelete?: () => void
/** Pin/unpin this group (menu row). */
onTogglePin?: () => void
/** Open the appearance dialog (menu row). */
onEditAppearance?: () => void
/** Group reorder source; the row becomes draggable only when provided. */
onDragStartCategory?: (event: DragEvent) => void
} & RowDropProps) {
const [menuOpen, setMenuOpen] = useState(false)
const count = node.workspaces.length
const manageable = onRename !== undefined && onDelete !== undefined
const pinned = node.appearance?.pinned === true
const menuItems: MenuEntry[] = [
...(onTogglePin === undefined
? []
: [{
id: 'pin',
label: pinned ? t('group.unpin') : t('group.pin'),
icon: pinned ? <IconPinFillMedium /> : <IconPinOutlineRegular />,
}]),
...(onEditAppearance === undefined
? []
: [{ id: 'appearance', label: t('group.appearance'), icon: <IconSlidersTwoOutlineRegular /> }]),
{ type: 'separator', id: 'group-menu-separator' },
{ id: 'rename', label: t('group.rename'), icon: <IconEditOutlineRegular /> },
{ id: 'delete', label: t('group.delete'), icon: <IconTrashOutlineRegular />, danger: true },
]
return (
<div
className={`wgCategoryRow${dropActive ? ' wgDropTarget' : ''}${insertLine === 'before' ? ' wgInsertBefore' : insertLine === 'after' ? ' wgInsertAfter' : ''}`}
role="treeitem"
aria-expanded={node.expanded}
aria-label={t('section.workspaces')}
aria-label={pinned ? `${t('section.workspaces')} · ${t('group.pinned')}` : t('section.workspaces')}
data-wg-category={node.key}
data-wg-color={node.appearance?.color}
/* Flower-branch hooks: a category row starts a group, so the stem kinks
here. Deliberately NOT marked active even when it contains the open
session — the session row below it carries that marker, and only one
@ -132,21 +225,28 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
<IconTriangleRightFillMedium />
</span>
<span className="wgCategoryIcon" data-wg-row-icon="group">
{node.expanded ? <IconFolderOpenMedium /> : <IconFolderCloseMedium />}
<CategoryGlyph
icon={node.appearance?.icon}
fallback={node.expanded ? <IconFolderOpenMedium /> : <IconFolderCloseMedium />}
/>
</span>
<span className="wgCategoryLabel">{node.label}</span>
<span className="wgCategoryCount">{count}</span>
{pinned && (
<span className="wgCategoryPin" aria-hidden>
<IconPinFillMedium />
</span>
)}
{manageable && (
<span className="wgRowActions">
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={[
{ id: 'rename', label: t('group.rename'), icon: <IconEditOutlineRegular /> },
{ id: 'delete', label: t('group.delete'), icon: <IconTrashOutlineRegular />, danger: true },
]}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'pin') onTogglePin?.()
if (id === 'appearance') onEditAppearance?.()
if (id === 'rename') onRename()
if (id === 'delete') onDelete()
}}
@ -295,6 +395,86 @@ export function TreeChildren({ children }: { children: ReactNode }) {
)
}
/** Keyframe names the disclosure animation relies on (styles.css). */
const ROW_GROUP_OPEN_ANIMATION = 'wg-rows-in'
const ROW_GROUP_CLOSE_ANIMATION = 'wg-rows-out'
/** Upper bound for one disclosure animation (180ms open / 160ms close). */
const ROW_GROUP_ANIMATION_FALLBACK_MS = 400
/** Lifecycle of one animated disclosure body. */
type RowGroupPhase = 'opening' | 'open' | 'closing' | 'closed'
/** Whether the user asked the OS to reduce motion (no sync unmount without it). */
function prefersReducedMotion(): boolean {
return typeof window !== 'undefined'
&& typeof window.matchMedia === 'function'
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches
}
/**
* Animated disclosure body shared by the category and project levels.
*
* Collapsed state renders nothing at all (same DOM as the old
* `{expanded && …}`), so hidden subtrees cost no layout. Expanding plays a
* 0fr→1fr grid animation; collapsing keeps the rows mounted for one closing
* animation and unmounts on its `animationend`. `prefers-reduced-motion`
* unmounts synchronously instead — waiting for an `animationend` that CSS
* disabled would leave the group stuck half-closed.
*
* The flower-branch overlay cannot follow a moving row box, so the animation
* phase exposes `data-wg-animating` (styles.css fades the vine while it is
* present).
*/
export function RowGroup({ expanded, className, animate = true, children }: {
expanded: boolean
className?: string
/** Disable the animation for huge subtrees or during drag folding. */
animate?: boolean
children: ReactNode
}): JSX.Element | null {
const [phase, setPhase] = useState<RowGroupPhase>(expanded ? 'open' : 'closed')
const previousExpanded = useRef(expanded)
// Adjust state while rendering (React's documented prop-change pattern) so a
// reduced-motion collapse unmounts in the same commit instead of flashing
// the old rows for a frame.
if (previousExpanded.current !== expanded) {
previousExpanded.current = expanded
if (expanded) setPhase(animate && !prefersReducedMotion() ? 'opening' : 'open')
else setPhase(animate && !prefersReducedMotion() ? 'closing' : 'closed')
}
// Insurance against a missing `animationend` (interrupted or skipped
// animation): the animating phase holds `pointer-events:none` and keeps a
// collapsed body mounted, so it must always settle on its own.
useEffect(() => {
if (phase !== 'opening' && phase !== 'closing') return undefined
const timer = window.setTimeout(() => {
setPhase(phase === 'opening' ? 'open' : 'closed')
}, ROW_GROUP_ANIMATION_FALLBACK_MS)
return () => { window.clearTimeout(timer) }
}, [phase])
if (phase === 'closed') return null
const animating = phase === 'opening' || phase === 'closing'
const classes = `wgRows${className === undefined ? '' : ` ${className}`}${phase === 'opening' ? ' wgRowsOpening' : ''}${phase === 'closing' ? ' wgRowsClosing' : ''}`
const onAnimationEnd = (event: AnimationEvent<HTMLDivElement>): void => {
if (event.target !== event.currentTarget) return
if (phase === 'opening' && event.animationName === ROW_GROUP_OPEN_ANIMATION) setPhase('open')
if (phase === 'closing' && event.animationName === ROW_GROUP_CLOSE_ANIMATION) setPhase('closed')
}
return (
<div
role="group"
className={classes}
aria-hidden={!expanded}
{...(animating ? { 'data-wg-animating': '' } : {})}
style={animating ? { pointerEvents: 'none' } : undefined}
onAnimationEnd={onAnimationEnd}
>
<div className="wgRowsInner">{children}</div>
</div>
)
}
/** One session leaf row. */
export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
node: SessionNode

View File

@ -110,6 +110,30 @@
position:relative;
}
/* Palette: one custom property per colour id, shared by the group row and the
appearance picker swatches. An uncoloured group never gets data-wg-color, so
existing overlays render byte-identically. */
[data-wg-color=red]{--wg-group-tint:#d9534f}
[data-wg-color=orange]{--wg-group-tint:#e08a3c}
[data-wg-color=amber]{--wg-group-tint:#d9a521}
[data-wg-color=green]{--wg-group-tint:#3fa45b}
[data-wg-color=teal]{--wg-group-tint:#2f9e93}
[data-wg-color=blue]{--wg-group-tint:#4a90d9}
[data-wg-color=indigo]{--wg-group-tint:#5b6fd6}
[data-wg-color=purple]{--wg-group-tint:#9a63c9}
[data-wg-color=pink]{--wg-group-tint:#d4659c}
[data-wg-color=gray]{--wg-group-tint:#8a8a8a}
/* inset shadow instead of a new element: no layout shift, no clash with the
drag insert-line pseudo-elements above. */
.wgCategoryRow[data-wg-color] {
box-shadow:inset 2px 0 0 var(--wg-group-tint);
}
.wgCategoryRow[data-wg-color] .wgCategoryIcon {
color:var(--wg-group-tint);
}
.wgCategoryRow:hover {
background:var(--dsw-bg-hover,#7f7f7f1f);
}
@ -185,6 +209,17 @@
font-size:11px;
}
.wgCategoryGlyph {
font-size:12px;
line-height:1;
}
.wgCategoryPin {
color:var(--dsw-fg-3,#7f7f7fcc);
flex:none;
display:inline-flex;
}
.wgProjectRow {
cursor:pointer;
user-select:none;
@ -271,6 +306,13 @@
top:0;
left:0;
overflow:visible;
transition:opacity .12s ease;
}
/* Disclosure animation moves rows before FlowerBranch re-measures: hide the
vine overlay while any RowGroup animates so the stem never lags behind. */
.wgTreeWrap:has([data-wg-animating]) .wgBranch {
opacity:0;
}
.wgTreeWrap>.wgList {
@ -319,7 +361,43 @@
}
@media (prefers-reduced-motion:reduce) {
.wgBranchGrown,.wgBranchDot{transition:none}.wgFlowerArt{animation:none};
.wgBranchGrown,.wgBranchDot{transition:none}.wgFlowerArt{animation:none}.wgRowsOpening,.wgRowsClosing{animation:none}.wgBranch{transition:none};
}
/* Animated disclosure body (RowGroup): 0fr ↔ 1fr interpolates the row box
without measuring heights. The inner element must shrink during the +row
collapse, and overflow is only clipped while a class is present so idle
hover halos and focus rings are never cut off. */
.wgRows {
display:grid;
grid-template-rows:1fr;
}
.wgRowsInner {
min-height:0;
}
.wgRowsOpening {
animation:wg-rows-in .18s cubic-bezier(.2,.8,.2,1);
}
.wgRowsClosing {
pointer-events:none;
animation:wg-rows-out .16s cubic-bezier(.4,0,1,1) forwards;
}
.wgRowsOpening .wgRowsInner,.wgRowsClosing .wgRowsInner {
overflow:hidden;
}
@keyframes wg-rows-in {
0%{grid-template-rows:0fr;opacity:.35}
to{grid-template-rows:1fr;opacity:1}
}
@keyframes wg-rows-out {
0%{grid-template-rows:1fr;opacity:1}
to{grid-template-rows:0fr;opacity:0}
}
.wgTreeChildren {
@ -471,6 +549,85 @@
border-color:var(--dsw-accent,#4a90d9);
}
/* Appearance dialog: colour swatches, icon picker grid, pin toggle. */
.wgAppearanceSection {
display:flex;
flex-direction:column;
gap:6px;
}
.wgAppearanceLabel {
color:var(--dsw-fg-3,#7f7f7fcc);
font-size:11px;
font-weight:600;
}
.wgSwatchRow {
gap:6px;
display:flex;
flex-wrap:wrap;
}
.wgSwatch {
cursor:pointer;
border:1px solid var(--dsw-alias-border-l2,#7f7f7f47);
width:20px;
height:20px;
border-radius:5px;
padding:0;
}
.wgSwatch[data-wg-color] {
background:var(--wg-group-tint);
}
.wgSwatch:disabled {
cursor:default;
opacity:.5;
}
.wgSwatchActive {
outline:2px solid var(--dsw-accent,#4a90d9);
outline-offset:1px;
}
.wgSwatchDefault {
background:var(--dsw-bg-hover,#7f7f7f1f);
}
.wgIconGrid {
gap:4px;
grid-template-columns:repeat(10,1fr);
display:grid;
}
.wgIconCell {
cursor:pointer;
color:var(--dsw-fg-2,inherit);
border:0;
border-radius:5px;
justify-content:center;
align-items:center;
width:24px;
height:24px;
padding:0;
display:inline-flex;
background:transparent;
}
.wgIconCell:hover:not(:disabled) {
background:var(--dsw-bg-hover,#7f7f7f1f);
}
.wgIconCell[aria-pressed=true] {
background:var(--dsw-bg-selected,#4a90d92e);
}
.wgIconCell:disabled {
cursor:default;
opacity:.5;
}
.wgQuickOverlay {
z-index:1100;
background:var(--dsw-alias-bg-mask-1,#00000052);
@ -846,3 +1003,110 @@
.wgTabClose:hover {
background:var(--dsw-alias-interactive-bg-hover-solid,#7f7f7f33);
}
/* ---- tab strip: pin / drag / inline rename / context menu ------------------ */
.wgTab {
position:relative;
}
.wgTabPinned {
box-shadow:inset 0 0 0 1px var(--dsw-alias-label-secondary,#7f7f7f73);
}
.wgTabPin {
flex:none;
justify-content:center;
align-items:center;
width:12px;
height:12px;
margin-left:4px;
opacity:.55;
color:inherit;
display:inline-flex;
}
.wgTabDragging {
opacity:.42;
}
.wgTabDropBefore:before,.wgTabDropAfter:before {
content:"";
position:absolute;
top:2px;
bottom:2px;
background:var(--dsw-alias-label-primary,var(--dsw-fg-1,#4a90d9));
border-radius:2px;
width:2px;
}
.wgTabDropBefore:before {
left:-4px;
}
.wgTabDropAfter:before {
right:-4px;
}
.wgTabRename {
box-sizing:border-box;
min-width:88px;
height:100%;
color:inherit;
background:var(--dsw-alias-bg-elevated,var(--dsw-bg-1,transparent));
border:1px solid var(--dsw-alias-label-secondary,#7f7f7f73);
border-radius:6px;
outline:none;
flex:auto;
margin:2px 0;
padding:0 6px;
font-family:inherit;
font-size:12px;
}
.wgTabMenu {
z-index:2147483000;
box-sizing:border-box;
min-width:196px;
background:var(--dsw-alias-bg-popup,var(--dsw-bg-2,#1e1e1e));
border:1px solid var(--dsw-alias-border-l2,#7f7f7f33);
border-radius:8px;
flex-direction:column;
padding:4px;
display:flex;
position:fixed;
box-shadow:0 8px 24px #00000033,0 1px 2px #0000001f;
}
.wgTabMenuItem {
width:100%;
color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));
text-align:left;
cursor:pointer;
background:0 0;
border:none;
border-radius:5px;
padding:6px 10px;
font-family:inherit;
font-size:12px;
line-height:16px;
}
.wgTabMenuItem:hover:not(:disabled) {
background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f));
}
.wgTabMenuItem:disabled {
cursor:default;
opacity:.4;
}
.wgTabMenuDanger {
color:var(--dsw-alias-label-error,var(--dsw-fg-error,#d9534f));
}
.wgTabMenuSeparator {
background:var(--dsw-alias-border-l2,#7f7f7f33);
height:1px;
margin:4px 6px;
}

View File

@ -25,6 +25,30 @@ export const TABS_ROUTE = '/workspace-groups/tabs'
export interface WireTab {
readonly sessionId: string
readonly order: number
/** Pinned tabs are restored at the front of the strip. */
readonly pinned?: boolean
/** A label the user typed for the tab itself (absent = follow the session). */
readonly title?: string
}
/**
* Read one tab row off the wire, dropping the row when it is unusable.
* @param entry - one element of the stored `tabs` array.
* @returns the tab, or null for a malformed row.
*/
function parseWireTab(entry: unknown): WireTab | null {
if (typeof entry !== 'object' || entry === null) return null
const row = entry as Record<string, unknown>
if (typeof row.sessionId !== 'string' || row.sessionId === '') return null
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) return null
const pinned = row.pinned === true
const title = typeof row.title === 'string' && row.title.trim() !== '' ? row.title.trim() : undefined
return {
sessionId: row.sessionId,
order: row.order,
...(pinned ? { pinned: true } : {}),
...(title !== undefined ? { title } : {}),
}
}
/**
@ -46,11 +70,8 @@ export async function loadTabs(fetchImpl: typeof fetch = fetch): Promise<WireTab
if (!Array.isArray(list)) return []
const tabs: WireTab[] = []
for (const entry of list) {
if (typeof entry !== 'object' || entry === null) continue
const row = entry as Record<string, unknown>
if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) continue
tabs.push({ sessionId: row.sessionId, order: row.order })
const tab = parseWireTab(entry)
if (tab !== null) tabs.push(tab)
}
return tabs
} catch {

View File

@ -19,7 +19,12 @@
import { defineStore, type EngineStoreHandle, type StoreHandle } from '@deepseek-ai/dsh-client-store'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import {
closeAfterImpl,
closeOthersImpl,
closeTabImpl,
moveTabImpl,
pinTabImpl,
renameTabImpl,
restoreTabsImpl,
touchTabImpl,
type SessionTab,
@ -51,6 +56,16 @@ export interface SessionTabsActions {
* opened a tab — a slow response must never discard what they just did.
*/
restore: (tabs: readonly SessionTab[]) => void
/** Pin or unpin one tab (re-inserts it at the block boundary). */
pin: (sessionId: SessionId) => void
/** Move one tab to an index in the resulting strip (drag and drop). */
move: (sessionId: SessionId, targetIndex: number) => void
/** Set (or clear, with a blank value) one tab's own label. */
rename: (sessionId: SessionId, title: string | undefined) => void
/** Close everything except one tab; pinned tabs are kept. */
closeOthers: (sessionId: SessionId) => void
/** Close every tab after one in display order. */
closeAfter: (sessionId: SessionId) => void
}
/** Annotation twin of the actions literal below (structural `ActionsDecl`). */
@ -58,6 +73,11 @@ type SessionTabsActionsDecl = {
touch: typeof touchTabImpl
close: typeof closeTabImpl
restore: typeof restoreTabsImpl
pin: typeof pinTabImpl
move: typeof moveTabImpl
rename: typeof renameTabImpl
closeOthers: typeof closeOthersImpl
closeAfter: typeof closeAfterImpl
}
/**
@ -94,6 +114,11 @@ export function createSessionTabsStore(): EngineStoreHandle<SessionTabsState, Se
touch: touchTabImpl,
close: closeTabImpl,
restore: restoreTabsImpl,
pin: pinTabImpl,
move: moveTabImpl,
rename: renameTabImpl,
closeOthers: closeOthersImpl,
closeAfter: closeAfterImpl,
},
})
}

View File

@ -2,12 +2,19 @@
* Pure session-tab state: the ordered strip of sessions the user has opened,
* the active one, and each tab's derived presentation.
*
* Position model: a tab's place in the strip is decided ONCE, when it is first
* opened, and never changes afterwards. Switching to a tab, or re-opening a
* session that already has one, leaves the strip exactly as it was — so clicking
* a chip never moves the chip out from under the pointer. Only two events change
* the order: a session opening for the FIRST time (append) and a tab closing
* (remove).
* Position model: a tab's place in the strip is decided when it is first opened
* and otherwise only moves when the USER moves it. Switching to a tab, or
* re-opening a session that already has one, leaves the strip exactly as it was
* — so clicking a chip never moves the chip out from under the pointer. The
* order changes on: a session opening for the FIRST time (append), a tab closing
* (remove), a drag (move), and a pin toggle (which carries the chip across the
* pinned boundary).
*
* The array IS the display order, with one invariant the transforms maintain:
* every pinned tab sits before every unpinned one. New tabs therefore append at
* the end (the unpinned block) and pinning/unpinning re-inserts at the boundary
* between the two blocks. A stored strip from an older build has no `pinned`
* flag, which reads as "unpinned" and satisfies the invariant as-is.
*
* Runtime-free on purpose (same discipline as `store-core.ts` / `quick.ts`):
* the component owns the ref + React state, this module owns every rule, and
@ -32,6 +39,21 @@ export interface SessionTab {
* React move an existing chip's DOM node instead of reconciling it in place.
*/
readonly order: number
/**
* Pinned tabs stay at the front of the strip and survive `close others`.
*
* Absent means unpinned: that is both the `false` case and the shape an older
* build's stored strip has, so no migration step is needed to read one back.
*/
readonly pinned?: boolean
/**
* A label the user typed for THIS tab, overriding the session's title.
*
* Kept separate from the session title on purpose: renaming a tab here must
* not rewrite the conversation's own name (which the sidebar and the search
* results show). Absent/empty means "follow the session".
*/
readonly title?: string
}
/** Feature switch: whether opening a session also surfaces a tab. */
@ -78,6 +100,166 @@ export function removeTab(tabs: readonly SessionTab[], sessionId: SessionId): Se
return tabs.filter(tab => tab.sessionId !== sessionId)
}
/**
* Whether a tab is pinned (absent counts as unpinned).
* @param tab - the tab.
* @returns true when the tab belongs in the pinned block.
*/
function isPinned(tab: SessionTab): boolean {
return tab.pinned === true
}
/**
* Count the leading pinned block.
*
* The transforms keep every pinned tab before every unpinned one, so the pinned
* block is always a prefix and its length is the single index that separates
* the two blocks — which is exactly where a chip lands when it changes sides.
*
* @param tabs - strip in display order.
* @returns how many leading tabs are pinned.
*/
export function pinnedCount(tabs: readonly SessionTab[]): number {
let count = 0
while (count < tabs.length && isPinned(tabs[count] as SessionTab)) count += 1
return count
}
/**
* Stable-partition a strip so every pinned tab precedes every unpinned one.
*
* Needed by the restore path: stored tabs are merged onto whatever the startup
* flow already opened, and an append would otherwise park a pinned tab at the
* end of the strip. Already-normalized strips come back as a copy.
*
* @param tabs - any strip.
* @returns a strip satisfying the pinned-first invariant.
*/
export function normalizeTabs(tabs: readonly SessionTab[]): SessionTab[] {
const pinned = tabs.filter(isPinned)
if (pinned.length === 0 || pinned.length === tabs.length) return [...tabs]
return [...pinned, ...tabs.filter(tab => !isPinned(tab))]
}
/**
* Move one tab to a new place in the strip (drag and drop).
*
* `targetIndex` is an index in the RESULTING strip. The move is clamped to the
* tab's own block — a dragged chip can be reordered within the pinned block or
* within the unpinned one, but never carried across that boundary. Crossing it
* is `togglePinTab`'s job, because it changes the tab's meaning rather than
* just its position: pinning is what makes a tab survive `close others`.
*
* @param tabs - strip in display order.
* @param sessionId - the tab being moved.
* @param targetIndex - desired index in the resulting strip.
* @returns a new strip, or the same array when nothing moved.
*/
export function moveTab(
tabs: readonly SessionTab[],
sessionId: SessionId,
targetIndex: number,
): SessionTab[] {
const from = tabs.findIndex(tab => tab.sessionId === sessionId)
if (from < 0) return tabs as SessionTab[]
const moving = tabs[from] as SessionTab
const rest = tabs.filter(tab => tab.sessionId !== sessionId)
const boundary = pinnedCount(rest)
const min = isPinned(moving) ? 0 : boundary
const max = isPinned(moving) ? boundary : rest.length
const clamped = Math.min(Math.max(Math.trunc(targetIndex), min), max)
if (clamped === from) return tabs as SessionTab[]
return [...rest.slice(0, clamped), moving, ...rest.slice(clamped)]
}
/**
* Pin or unpin one tab, re-inserting it at the boundary between the blocks.
*
* Pinning puts the chip at the END of the pinned block (next to the other
* kept tabs) and unpinning at the START of the unpinned one, so a toggle never
* throws a chip to the far end of the strip.
*
* @param tabs - strip in display order.
* @param sessionId - the tab to toggle.
* @returns a new strip, or the same array when the tab is absent.
*/
export function togglePinTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {
const from = tabs.findIndex(tab => tab.sessionId === sessionId)
if (from < 0) return tabs as SessionTab[]
const moving = tabs[from] as SessionTab
const rest = tabs.filter(tab => tab.sessionId !== sessionId)
const boundary = pinnedCount(rest)
const repinned: SessionTab = isPinned(moving)
? { sessionId: moving.sessionId, order: moving.order, ...(moving.title !== undefined ? { title: moving.title } : {}) }
: { sessionId: moving.sessionId, order: moving.order, pinned: true, ...(moving.title !== undefined ? { title: moving.title } : {}) }
return [...rest.slice(0, boundary), repinned, ...rest.slice(boundary)]
}
/**
* Set or clear one tab's own label.
*
* A blank value CLEARS the override (the chip falls back to the session title)
* rather than storing an empty label, so "rename to nothing" and "rename back to
* the session title" are the same gesture.
*
* @param tabs - strip.
* @param sessionId - the tab to relabel.
* @param title - the new label; blank clears it.
* @returns a new strip, or the same array when the tab is absent.
*/
export function renameTab(
tabs: readonly SessionTab[],
sessionId: SessionId,
title: string | undefined,
): SessionTab[] {
const from = tabs.findIndex(tab => tab.sessionId === sessionId)
if (from < 0) return tabs as SessionTab[]
const trimmed = title?.trim() ?? ''
// No change: return the same array so the store can skip the write.
if ((tabs[from]?.title ?? '') === trimmed) return tabs as SessionTab[]
return tabs.map((tab) => {
if (tab.sessionId !== sessionId) return tab
if (trimmed === '') {
const { title: _cleared, ...rest } = tab
void _cleared
return rest
}
return { ...tab, title: trimmed }
})
}
/**
* Close every tab except one — pinned tabs stay.
*
* Pinning is exactly how a user says "keep this no matter what"; letting
* `close others` eat the pinned block would make the flag pointless.
*
* @param tabs - strip.
* @param keepSessionId - the tab to keep (plus every pinned one).
* @returns a new strip.
*/
export function closeOtherTabs(tabs: readonly SessionTab[], keepSessionId: SessionId): SessionTab[] {
if (!tabs.some(tab => tab.sessionId === keepSessionId)) return tabs as SessionTab[]
return tabs.filter(tab => isPinned(tab) || tab.sessionId === keepSessionId)
}
/**
* Close every tab after one in display order.
*
* "After" is display order (pinned block first), which is the order the user
* sees; a pinned tab is never after an unpinned one, so this cannot silently
* drop the kept block.
*
* @param tabs - strip in display order.
* @param sessionId - the last tab that stays.
* @returns a new strip, or the same array when the tab is absent.
*/
export function closeTabsAfter(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {
const from = tabs.findIndex(tab => tab.sessionId === sessionId)
if (from < 0) return tabs as SessionTab[]
return tabs.slice(0, from + 1)
}
/**
* Order the strip for display: strictly by arrival, regardless of which tab is
* active.
@ -332,8 +514,78 @@ export function restoreTabsImpl(state: SessionTabsState, tabs: readonly SessionT
// Re-key onto a fresh, monotonically increasing counter so a restored key
// can never collide with one already spent.
order += 1
additions.push({ sessionId: tab.sessionId, order })
// Carry the chip's own presentation across the restore: a pinned tab or a
// custom label that came back unpinned/untitled would silently lose the
// user's configuration on every restart.
additions.push({
sessionId: tab.sessionId,
order,
...(tab.pinned === true ? { pinned: true } : {}),
...(tab.title !== undefined ? { title: tab.title } : {}),
})
}
if (additions.length > 0) {
const merged = [...state.tabs, ...additions]
// Restored tabs can be pinned, and appending them would park a pinned chip
// past the unpinned ones. Re-establish the pinned-first invariant.
state.tabs = merged.some(isPinned) ? normalizeTabs(merged) : merged
}
if (additions.length > 0) state.tabs = [...state.tabs, ...additions]
state.order = order
}
/**
* Store transform: pin or unpin one tab.
* @param state - store draft, mutated in place.
* @param sessionId - the tab to toggle.
*/
export function pinTabImpl(state: SessionTabsState, sessionId: SessionId): void {
const next = togglePinTab(state.tabs, sessionId)
if (next === state.tabs) return
state.tabs = next
}
/**
* Store transform: move one tab to a new index (drag and drop).
* @param state - store draft, mutated in place.
* @param sessionId - the tab being moved.
* @param targetIndex - desired index in the resulting strip.
*/
export function moveTabImpl(state: SessionTabsState, sessionId: SessionId, targetIndex: number): void {
const next = moveTab(state.tabs, sessionId, targetIndex)
if (next === state.tabs) return
state.tabs = next
}
/**
* Store transform: set or clear one tab's own label.
* @param state - store draft, mutated in place.
* @param sessionId - the tab to relabel.
* @param title - the new label; blank clears it.
*/
export function renameTabImpl(state: SessionTabsState, sessionId: SessionId, title: string | undefined): void {
const next = renameTab(state.tabs, sessionId, title)
if (next === state.tabs) return
state.tabs = next
}
/**
* Store transform: close every unlisted tab, keeping the pinned ones.
* @param state - store draft, mutated in place.
* @param keepSessionId - the tab to keep.
*/
export function closeOthersImpl(state: SessionTabsState, keepSessionId: SessionId): void {
const next = closeOtherTabs(state.tabs, keepSessionId)
if (next.length === state.tabs.length) return
state.tabs = next
}
/**
* Store transform: close every tab after one in display order.
* @param state - store draft, mutated in place.
* @param sessionId - the last tab that stays.
*/
export function closeAfterImpl(state: SessionTabsState, sessionId: SessionId): void {
const next = closeTabsAfter(state.tabs, sessionId)
if (next.length === state.tabs.length) return
state.tabs = next
}

View File

@ -16,8 +16,14 @@ import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { indexSubagentDescendants, type SubagentDescendantSummary } from './subagent-lineage.ts'
import { effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'
import { TOP_LEVEL_ORDER_KEY, UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'
import { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'
import {
TOP_LEVEL_ORDER_KEY,
UNCATEGORIZED_LABEL,
type CategoryAppearance,
type GroupsConfig,
type ManualGroups,
} from '../core/types.ts'
/** Pending interaction kinds with dedicated Workspace-row presentation. */
export type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question'
@ -99,6 +105,8 @@ export interface CategoryNode {
containsCurrent: boolean
/** Workspace folders in host order. */
workspaces: readonly WorkspaceGroupNode[]
/** Presentation (color / icon / pin) for this category, when configured. */
appearance?: CategoryAppearance
}
/** Viewing state consumed by the derivation. */
@ -249,12 +257,14 @@ export function deriveGroups(
sessions: wsExpanded ? sessions : [],
})
}
const appearance = categoryAppearance(manual, key)
nodes.push({
key,
label: key,
expanded,
containsCurrent,
workspaces: workspaceNodes,
...(appearance === undefined ? {} : { appearance }),
})
}
return nodes
@ -478,12 +488,14 @@ export function deriveSearchGroups(
for (const key of effectiveCategories(config, manual).map(e => e.key)) {
const workspaceNodes = byCategory.get(key)
if (workspaceNodes === undefined || workspaceNodes.length === 0) continue
const appearance = categoryAppearance(manual, key)
categories.push({
key,
label: key,
expanded: true,
containsCurrent: false,
workspaces: workspaceNodes,
...(appearance === undefined ? {} : { appearance }),
})
}
return { categories, topLevel }

View File

@ -13,6 +13,7 @@
import {
normalizePath,
UNCATEGORIZED_LABEL,
type CategoryAppearance,
type GroupCategory,
type GroupRule,
type GroupsConfig,
@ -50,6 +51,31 @@ export function isHiddenRule(manual: ManualGroups | undefined, originalName: str
return manual?.hidden?.includes(originalName) ?? false
}
/** Presentation for a category display key, or undefined when unset. */
export function categoryAppearance(
manual: ManualGroups | undefined,
key: string,
): CategoryAppearance | undefined {
return manual?.appearance?.[key]
}
/** Whether a category display key is pinned. */
export function isCategoryPinned(manual: ManualGroups | undefined, key: string): boolean {
return categoryAppearance(manual, key)?.pinned === true
}
/**
* Drop empty presentation fields: `undefined` values, `pinned: false`, `icon: ''`.
* Returns undefined when nothing is left, so callers can delete the whole entry.
*/
export function pruneAppearance(value: CategoryAppearance): CategoryAppearance | undefined {
const result: CategoryAppearance = {}
if (value.color !== undefined) result.color = value.color
if (value.icon !== undefined && value.icon.trim() !== '') result.icon = value.icon
if (value.pinned === true) result.pinned = true
return Object.keys(result).length === 0 ? undefined : result
}
/** Rule category display names, in YAML render order (hidden ones excluded). */
export function ruleDisplayNames(categories: readonly GroupCategory[], manual: ManualGroups | undefined): string[] {
const names: string[] = []
@ -75,6 +101,11 @@ export function originalRuleNameForDisplay(
* creation order — unless `manual.categoryOrder` overrides the sequence.
* Top-level (ungrouped) workspaces are never included; they render as
* separate top-level rows after the group folders.
*
* The pin partition is part of DISPLAY ORDER, not a render-time concern:
* pinned groups sort before unpinned ones *within* the manual order, and both
* the tree and the drag-drop landing neighbours read this list, so they can
* never disagree about what sits next to what.
*/
export interface EffectiveCategory {
/** Display key (what the tree renders and assignments reference). */
@ -83,6 +114,32 @@ export interface EffectiveCategory {
source: 'rule' | 'manual'
}
/** Apply `manual.categoryOrder` to the default sequence (stable). */
function orderByCategoryOrder(
entries: EffectiveCategory[],
order: readonly string[] | undefined,
): EffectiveCategory[] {
if (order === undefined || order.length === 0) return entries
// Stable sort by position in categoryOrder; entries absent from the order
// keep their relative default position after all ordered ones.
const position = new Map(order.map((key, index) => [key, index]))
return [...entries].sort((a, b) => {
const pa = position.get(a.key)
const pb = position.get(b.key)
if (pa !== undefined && pb !== undefined) return pa - pb
if (pa !== undefined) return -1
if (pb !== undefined) return 1
return 0
})
}
/** Stable partition: pinned groups first, unpinned ones keep their order. */
function pinnedFirst(entries: EffectiveCategory[], manual: ManualGroups | undefined): EffectiveCategory[] {
if (manual?.appearance === undefined) return entries
const pinned = (entry: EffectiveCategory): number => Number(isCategoryPinned(manual, entry.key))
return [...entries].sort((a, b) => pinned(b) - pinned(a))
}
export function effectiveCategories(
config: GroupsConfig,
manual: ManualGroups | undefined,
@ -101,19 +158,7 @@ export function effectiveCategories(
seen.add(name)
entries.push({ key: name, source: 'manual' })
}
const order = manual?.categoryOrder
if (order === undefined || order.length === 0) return entries
// Stable sort by position in categoryOrder; entries absent from the order
// keep their relative default position after all ordered ones.
const position = new Map(order.map((key, index) => [key, index]))
return [...entries].sort((a, b) => {
const pa = position.get(a.key)
const pb = position.get(b.key)
if (pa !== undefined && pb !== undefined) return pa - pb
if (pa !== undefined) return -1
if (pb !== undefined) return 1
return 0
})
return pinnedFirst(orderByCategoryOrder(entries, manual?.categoryOrder), manual)
}
/** Display keys of all effective categories (top-level workspaces excluded). */

View File

@ -24,6 +24,47 @@ export interface GroupCategory {
rules: GroupRule[]
}
/** Theme-safe palette id for a group's accent. */
export type GroupColor =
| 'red' | 'orange' | 'amber' | 'green' | 'teal'
| 'blue' | 'indigo' | 'purple' | 'pink' | 'gray'
/** Whitelist shared by the host write-validation and the client picker. */
export const GROUP_COLORS: readonly GroupColor[] = [
'red', 'orange', 'amber', 'green', 'teal',
'blue', 'indigo', 'purple', 'pink', 'gray',
]
/** Curated icon ids (rendered from @deepseek-ai/dsh-client-ui-primitives). */
export type GroupIconId =
| 'folder' | 'workspace' | 'code' | 'plugin' | 'skill' | 'data'
| 'database' | 'api' | 'plan' | 'goal' | 'light' | 'globe'
| 'archive' | 'branch' | 'users' | 'clock' | 'shield' | 'checklist'
| 'sparkle' | 'tree'
export const GROUP_ICON_IDS: readonly GroupIconId[] = [
'folder', 'workspace', 'code', 'plugin', 'skill', 'data',
'database', 'api', 'plan', 'goal', 'light', 'globe',
'archive', 'branch', 'users', 'clock', 'shield', 'checklist',
'sparkle', 'tree',
]
/**
* Presentation metadata for one group. Every field optional.
*
* The explicit `| undefined` on each field is what lets a UI patch clear a
* value (`pruneAppearance` then drops it): under `exactOptionalPropertyTypes`
* a bare `color?: GroupColor` would reject `{ color: undefined }`.
*/
export interface CategoryAppearance {
/** Palette id; the CSS palette lives in styles.css `[data-wg-color]`. */
color?: GroupColor | undefined
/** `GroupIconId` preset id, or a short glyph (1–4 code units, emoji/latin). */
icon?: string | undefined
/** Pinned groups sort before unpinned ones (within the manual order). */
pinned?: boolean | undefined
}
/** The full sidecar configuration (mirrors workspace-groups.yaml). */
export interface GroupsConfig {
/** Category folders, in render order. First match wins. */
@ -45,7 +86,9 @@ export interface GroupsConfig {
*
* All new fields are optional for backward compatibility (files written by
* older plugin versions keep working); rendering falls back to sensible
* defaults when they are absent.
* defaults when they are absent. Note that an older plugin version writes the
* whole file back, which silently drops fields it does not know about — e.g.
* `appearance` (group color / icon / pin) is lost after a downgrade.
*/
export interface ManualGroups {
/**
@ -84,6 +127,13 @@ export interface ManualGroups {
* inert: workspaces matching them become top-level (ungrouped).
*/
hidden?: string[]
/**
* Per-group presentation, keyed by category DISPLAY name (same key space as
* `categoryOrder`). Optional per field; an absent group has no presentation.
* Dangling keys (a YAML category that no longer exists) are tolerated on read
* and on write — see validateManualGroups.
*/
appearance?: Record<string, CategoryAppearance>
}
/**

View File

@ -13,7 +13,14 @@ import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { homedir } from 'node:os'
import { ruleDisplayName } from './core/matcher.ts'
import { TOP_LEVEL_ORDER_KEY, UNCATEGORIZED_LABEL, type ManualGroups } from './core/types.ts'
import {
GROUP_COLORS,
TOP_LEVEL_ORDER_KEY,
UNCATEGORIZED_LABEL,
type CategoryAppearance,
type GroupColor,
type ManualGroups,
} from './core/types.ts'
/** Default overlay location: `$DSH_HOME/workspace-groups.manual.json`. */
export function defaultManualPath(): string {
@ -104,6 +111,18 @@ export function parseManualGroups(raw: unknown): ManualGroups {
}
manual.renamed = renamed
}
if (source.appearance !== undefined) {
if (typeof source.appearance !== 'object' || source.appearance === null || Array.isArray(source.appearance)) {
throw new Error('workspace-groups.manual.json: appearance must be a mapping')
}
const appearance: Record<string, CategoryAppearance> = {}
for (const [key, value] of Object.entries(source.appearance)) {
if (key.trim() === '') throw new Error('workspace-groups.manual.json: appearance keys must be non-empty')
const parsed = parseAppearance(value, key)
if (parsed !== undefined) appearance[key.trim()] = parsed
}
if (Object.keys(appearance).length > 0) manual.appearance = appearance
}
if (source.workspaceOrder !== undefined) {
if (typeof source.workspaceOrder !== 'object' || source.workspaceOrder === null || Array.isArray(source.workspaceOrder)) {
throw new Error('workspace-groups.manual.json: workspaceOrder must be a mapping')
@ -121,6 +140,50 @@ export function parseManualGroups(raw: unknown): ManualGroups {
return manual
}
/** Preset icon ids are lowercase kebab-case; anything else must be a short glyph. */
const ICON_PATTERN = /^(?:[a-z][a-z0-9-]{0,23}|[^\s\u0000-\u001f\u007f]{1,4})$/u
/** Narrow an unknown value to a palette id from the shared whitelist. */
function isGroupColor(value: unknown): value is GroupColor {
return GROUP_COLORS.some(color => color === value)
}
/**
* Parse one appearance entry. Unknown sub-keys are dropped; an entry that ends
* up empty is dropped entirely (returns undefined) so the file stays minimal.
*/
function parseAppearance(value: unknown, key: string): CategoryAppearance | undefined {
const field = `appearance["${key}"]`
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error(`workspace-groups.manual.json: ${field} must be an object`)
}
const source = value as Record<string, unknown>
const appearance: CategoryAppearance = {}
if (source.color !== undefined) {
if (!isGroupColor(source.color)) {
throw new Error(
`workspace-groups.manual.json: ${field}.color must be one of: ${GROUP_COLORS.join(', ')}`,
)
}
appearance.color = source.color
}
if (source.icon !== undefined) {
const icon = typeof source.icon === 'string' ? source.icon.trim() : ''
if (icon === '' || !ICON_PATTERN.test(icon)) {
throw new Error(`workspace-groups.manual.json: ${field}.icon must be an icon id or a 1–4 character glyph`)
}
appearance.icon = icon
}
if (source.pinned !== undefined) {
if (typeof source.pinned !== 'boolean') {
throw new Error(`workspace-groups.manual.json: ${field}.pinned must be a boolean`)
}
// Never persist `pinned: false` — an absent flag already means unpinned.
if (source.pinned) appearance.pinned = true
}
return Object.keys(appearance).length === 0 ? undefined : appearance
}
/** Parse a list of non-empty strings, optionally de-duplicated. */
function parseStringList(value: unknown, field: string, unique: boolean): string[] {
if (!Array.isArray(value)) {
@ -186,6 +249,10 @@ export function validateManualGroups(manual: ManualGroups, ruleCategoryNames: re
throw new Error(`workspace-groups.manual.json: hidden references unknown rule category "${original}"`)
}
}
// `appearance` is deliberately NOT cross-validated against existing
// categories: a presentation entry for a temporarily removed YAML category
// must survive, otherwise removing one category from the YAML would make
// every subsequent overlay save fail with 400 and freeze the whole tree.
}
/** Read + parse the overlay file. A missing file yields an empty overlay. */

View File

@ -31,12 +31,26 @@ export interface PersistedTab {
readonly sessionId: string
/** Arrival key (React list identity). */
readonly order: number
/** Pinned tabs are restored at the front of the strip. */
readonly pinned?: boolean
/** A label the user typed for the tab itself (absent = follow the session). */
readonly title?: string
}
/** The persisted document. */
export interface TabsDocument {
/** Shape version; a mismatch discards the file rather than guessing. */
readonly version: 1
/**
* Shape version.
*
* 1 = `{sessionId, order}` only (what the shipped build writes); 2 adds the
* optional `pinned` / `title` per tab. A version-1 file is READ as version 2
* with every tab unpinned and untitled — that is exactly what it meant — and
* the next write upgrades it. The two shapes are field-compatible, so no
* conversion step exists: an older build reading a version-2 file would drop
* the extra flags and keep working, which is why this stayed a tolerance
* instead of a hard rejection.
*/
readonly version: 2
/** Arrival counter, kept ahead of every tab's own order. */
readonly order: number
readonly tabs: readonly PersistedTab[]
@ -50,6 +64,28 @@ export function defaultTabsPath(): string {
return resolve(home, 'workspace-groups.tabs.json')
}
/**
* Normalize one tab row (used by both the file reader and the PUT body check, so
* the two can never drift).
*
* @param entry - one element of a stored/`posted` `tabs` array.
* @returns the tab, or null when the row is unusable.
*/
export function parsePersistedTab(entry: unknown): PersistedTab | null {
if (typeof entry !== 'object' || entry === null) return null
const row = entry as Record<string, unknown>
if (typeof row.sessionId !== 'string' || row.sessionId === '') return null
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) return null
const pinned = row.pinned === true
const title = typeof row.title === 'string' && row.title.trim() !== '' ? row.title.trim() : undefined
return {
sessionId: row.sessionId,
order: row.order,
...(pinned ? { pinned: true } : {}),
...(title !== undefined ? { title } : {}),
}
}
/**
* Parse + shape-validate a tabs document.
*
@ -64,22 +100,22 @@ export function defaultTabsPath(): string {
export function parseTabsDocument(raw: unknown): TabsDocument | null {
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null
const source = raw as Record<string, unknown>
if (source.version !== 1) return null
// 1 and 2 are field-compatible; anything else is a shape this build cannot
// reason about and is discarded rather than guessed at.
if (source.version !== 1 && source.version !== 2) return null
if (typeof source.order !== 'number' || !Number.isFinite(source.order)) return null
if (!Array.isArray(source.tabs)) return null
const tabs: PersistedTab[] = []
const seen = new Set<string>()
for (const entry of source.tabs) {
if (typeof entry !== 'object' || entry === null) continue
const row = entry as Record<string, unknown>
if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) continue
if (seen.has(row.sessionId)) continue
seen.add(row.sessionId)
tabs.push({ sessionId: row.sessionId, order: row.order })
const tab = parsePersistedTab(entry)
if (tab === null) continue
if (seen.has(tab.sessionId)) continue
seen.add(tab.sessionId)
tabs.push(tab)
}
return {
version: 1,
version: 2,
order: source.order,
tabs,
}
@ -141,7 +177,7 @@ export async function writeTabsDocument(path: string, document: TabsDocument): P
export function documentForTabs(state: { order: number; tabs: readonly PersistedTab[] }): TabsDocument {
const highest = state.tabs.reduce((max, tab) => Math.max(max, tab.order), 0)
return {
version: 1,
version: 2,
order: Math.max(state.order, highest),
tabs: [...state.tabs],
}

View File

@ -28,6 +28,7 @@ import {
import {
defaultTabsPath,
documentForTabs,
parsePersistedTab,
readTabsDocument,
writeTabsDocument,
type PersistedTab,
@ -69,13 +70,11 @@ function parseTabsPayload(raw: unknown): { order: number; tabs: PersistedTab[] }
const tabs: PersistedTab[] = []
const seen = new Set<string>()
for (const entry of source.tabs) {
if (typeof entry !== 'object' || entry === null) continue
const row = entry as Record<string, unknown>
if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) continue
if (seen.has(row.sessionId)) continue
seen.add(row.sessionId)
tabs.push({ sessionId: row.sessionId, order: row.order })
const tab = parsePersistedTab(entry)
if (tab === null) continue
if (seen.has(tab.sessionId)) continue
seen.add(tab.sessionId)
tabs.push(tab)
}
return { order: source.order, tabs }
}

View File

@ -7,11 +7,13 @@ import { describe, expect, it } from 'vitest'
import {
displayCategoryKeys,
effectiveCategories,
isCategoryPinned,
isManualOnlyCategory,
moveAfter,
moveBefore,
orderedWorkspaceIds,
originalRuleNameForDisplay,
pruneAppearance,
resolveCategory,
ruleDisplayName,
takenCategoryNames,
@ -144,6 +146,46 @@ describe('isManualOnlyCategory', () => {
})
})
describe('category appearance (pin partition)', () => {
it('pinned groups sort first, each partition keeping the default order', () => {
const manual: ManualGroups = {
categories: ['临时', '归档'],
assignments: {},
appearance: { '归档': { pinned: true } },
}
expect(isCategoryPinned(manual, '归档')).toBe(true)
expect(isCategoryPinned(manual, '临时')).toBe(false)
expect(displayCategoryKeys(CONFIG, manual)).toEqual(['归档', 'DSH 插件', '文档', '临时'])
expect(effectiveCategories(CONFIG, manual).map(entry => entry.key)).toEqual(['归档', 'DSH 插件', '文档', '临时'])
})
it('pin partition applies after categoryOrder (composite display order)', () => {
const manual: ManualGroups = {
categories: ['临时'],
assignments: {},
categoryOrder: ['临时', '文档', 'DSH 插件'],
appearance: { '文档': { pinned: true } },
}
expect(displayCategoryKeys(CONFIG, manual)).toEqual(['文档', '临时', 'DSH 插件'])
})
it('no appearance means the untouched default order', () => {
expect(displayCategoryKeys(CONFIG, { categories: [], assignments: {} })).toEqual(['DSH 插件', '文档'])
})
it('pruneAppearance drops empty fields and returns undefined when nothing is left', () => {
expect(pruneAppearance({})).toBeUndefined()
expect(pruneAppearance({ color: undefined, icon: ' ', pinned: false })).toBeUndefined()
expect(pruneAppearance({ color: 'blue', pinned: false })).toEqual({ color: 'blue' })
expect(pruneAppearance({ icon: 'code', pinned: false })).toEqual({ icon: 'code' })
expect(pruneAppearance({ color: 'blue', icon: 'code', pinned: true })).toEqual({
color: 'blue',
icon: 'code',
pinned: true,
})
})
})
describe('takenCategoryNames', () => {
it('covers rule display names, manual groups and the reserved label', () => {
const manual: ManualGroups = {

View File

@ -91,6 +91,69 @@ describe('parseManualGroups', () => {
})
})
describe('appearance (host parsing)', () => {
it('parses a valid appearance block', () => {
const parsed = parseManualGroups({
categories: ['临时'],
assignments: {},
appearance: {
'临时': { color: 'blue', icon: 'code', pinned: true },
'DSH 插件': { color: 'red', icon: '🔥' },
},
})
expect(parsed.appearance).toEqual({
'临时': { color: 'blue', icon: 'code', pinned: true },
'DSH 插件': { color: 'red', icon: '🔥' },
})
})
it('an absent / empty appearance block stays absent', () => {
expect(parseManualGroups({}).appearance).toBeUndefined()
expect(parseManualGroups({ appearance: {} }).appearance).toBeUndefined()
expect(parseManualGroups({ appearance: { '临时': {} } }).appearance).toBeUndefined()
})
it('rejects a non-mapping appearance value', () => {
expect(() => parseManualGroups({ appearance: [] })).toThrow(/appearance must be a mapping/)
})
it('rejects an empty appearance key', () => {
expect(() => parseManualGroups({ appearance: { ' ': {} } })).toThrow(/appearance keys must be non-empty/)
})
it('rejects a colour outside the palette', () => {
expect(() => parseManualGroups({ appearance: { A: { color: 'chartreuse' } } })).toThrow(/\.color must be one of/)
})
it('rejects an illegal icon', () => {
expect(() => parseManualGroups({ appearance: { A: { icon: 'has space' } } })).toThrow(/icon/)
expect(() => parseManualGroups({ appearance: { A: { icon: 'a'.repeat(25) } } })).toThrow(/icon/)
expect(() => parseManualGroups({ appearance: { A: { icon: '' } } })).toThrow(/icon/)
})
it('rejects a non-boolean pinned', () => {
expect(() => parseManualGroups({ appearance: { A: { pinned: 'yes' } } })).toThrow(/pinned must be a boolean/)
})
it('drops empty entries and never persists pinned: false', () => {
const parsed = parseManualGroups({
appearance: { A: { pinned: false, color: 'teal' }, B: { color: undefined } },
})
expect(parsed.appearance).toEqual({ A: { color: 'teal' } })
})
})
describe('appearance (write boundary tolerance)', () => {
it('does not reject a dangling appearance key', () => {
const manual: ManualGroups = {
categories: [],
assignments: {},
appearance: { '幽灵分组': { color: 'blue', pinned: true } },
}
expect(() => validateManualGroups(manual, RULE_NAMES)).not.toThrow()
})
})
describe('validateManualGroups v2 (write boundary)', () => {
it('accepts null assignments and renamed-display targets', () => {
const manual: ManualGroups = {

216
tests/tabs.test.ts Normal file
View File

@ -0,0 +1,216 @@
import { describe, expect, it } from 'vitest'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import {
appendTab,
closeOtherTabs,
closeTabsAfter,
moveTab,
normalizeTabs,
pinnedCount,
removeTab,
renameTab,
restoreTabsImpl,
togglePinTab,
type SessionTab,
type SessionTabsState,
} from '../src/client/tabs.ts'
const id = (name: string): SessionId => name as SessionId
function strip(...names: string[]): SessionTab[] {
return names.map((name, at) => ({ sessionId: id(name), order: at + 1 }))
}
function pinnedStrip(...names: string[]): SessionTab[] {
return names.map((name, at) => ({ sessionId: id(name), order: at + 1, pinned: true }))
}
const names = (tabs: readonly SessionTab[]): string[] => tabs.map(tab => tab.sessionId as string)
describe('appendTab', () => {
it('appends a new session at the end of the unpinned block', () => {
expect(names(appendTab(strip('a', 'b'), id('c'), 3))).toEqual(['a', 'b', 'c'])
})
it('is a no-op (same array) for a session that already has a tab', () => {
const tabs = strip('a', 'b')
expect(appendTab(tabs, id('a'), 3)).toBe(tabs)
})
it('appends behind pinned tabs so the pinned-first invariant holds', () => {
// New tabs are unpinned, so appending preserves "pinned block first" — the
// invariant is a property of the placement rule, not an extra sort.
const tabs = [...pinnedStrip('p'), ...strip('u')]
expect(names(appendTab(tabs, id('n'), 9))).toEqual(['p', 'u', 'n'])
expect(pinnedCount(appendTab(tabs, id('n'), 9))).toBe(1)
})
})
describe('removeTab', () => {
it('drops exactly the one session', () => {
expect(names(removeTab(strip('a', 'b', 'c'), id('b')))).toEqual(['a', 'c'])
})
})
describe('moveTab', () => {
const tabs = ['a', 'b', 'c', 'd'].map((name, at) => ({ sessionId: id(name), order: at + 1 }))
it('moves a chip forward', () => {
expect(names(moveTab(tabs, id('a'), 2))).toEqual(['b', 'c', 'a', 'd'])
})
it('moves a chip backward', () => {
expect(names(moveTab(tabs, id('d'), 1))).toEqual(['a', 'd', 'b', 'c'])
})
it('is a no-op (same array) when the index does not change', () => {
expect(moveTab(tabs, id('b'), 1)).toBe(tabs)
})
it('unknown session is a no-op', () => {
expect(moveTab(tabs, id('zz'), 1)).toBe(tabs)
})
it('clamps inside the unpinned block and never crosses into the pinned one', () => {
const mixed = [...pinnedStrip('p1', 'p2'), ...tabs]
// Target 0 is inside the pinned block; an unpinned chip may not go there.
expect(names(moveTab(mixed, id('c'), 0))).toEqual(['p1', 'p2', 'c', 'a', 'b', 'd'])
expect(pinnedCount(moveTab(mixed, id('c'), 0))).toBe(2)
})
it('clamps a pinned chip inside the pinned block', () => {
const mixed = [...pinnedStrip('p1', 'p2'), ...tabs]
expect(names(moveTab(mixed, id('p1'), 5))).toEqual(['p2', 'p1', 'a', 'b', 'c', 'd'])
expect(pinnedCount(moveTab(mixed, id('p1'), 5))).toBe(2)
})
})
describe('togglePinTab', () => {
const tabs = ['a', 'b', 'c'].map((name, at) => ({ sessionId: id(name), order: at + 1 }))
it('pins to the end of the pinned block', () => {
const once = togglePinTab(tabs, id('b'))
expect(names(once)).toEqual(['b', 'a', 'c'])
const twice = togglePinTab(once, id('c'))
expect(names(twice)).toEqual(['b', 'c', 'a'])
expect(pinnedCount(twice)).toBe(2)
})
it('unpins to the start of the unpinned block', () => {
const mixed = togglePinTab(tabs, id('a'))
const unpinned = togglePinTab(mixed, id('a'))
expect(names(unpinned)).toEqual(['a', 'b', 'c'])
expect(pinnedCount(unpinned)).toBe(0)
expect(unpinned[0]?.pinned).toBeUndefined()
})
it('keeps a custom label through the toggle', () => {
const relabelled = renameTab(tabs, id('a'), 'alpha')
const mixed = togglePinTab(relabelled, id('a'))
expect(mixed[0]?.title).toBe('alpha')
expect(togglePinTab(mixed, id('a'))[0]?.title).toBe('alpha')
})
it('unknown session is a no-op', () => {
expect(togglePinTab(tabs, id('zz'))).toBe(tabs)
})
})
describe('renameTab', () => {
const tabs = strip('a', 'b')
it('sets a trimmed label', () => {
expect(renameTab(tabs, id('a'), ' alpha ')[0]?.title).toBe('alpha')
})
it('clears the override when the label is blank', () => {
const relabelled = renameTab(tabs, id('a'), 'alpha')
const cleared = renameTab(relabelled, id('a'), ' ')
expect(cleared[0]?.title).toBeUndefined()
})
it('is a no-op (same array) when the label does not change', () => {
expect(renameTab(tabs, id('a'), undefined)).toBe(tabs)
})
it('leaves the other tabs alone', () => {
const relabelled = renameTab(tabs, id('a'), 'alpha')
expect(relabelled[1]).toBe(tabs[1])
})
})
describe('closeOtherTabs', () => {
it('keeps the named tab plus every pinned one', () => {
const mixed = [...togglePinTab(strip('a', 'b', 'c', 'd'), id('a')), { sessionId: id('e'), order: 9 }]
expect(names(closeOtherTabs(mixed, id('c')))).toEqual(['a', 'c'])
})
it('unknown keep id is a no-op', () => {
const tabs = strip('a')
expect(closeOtherTabs(tabs, id('zz'))).toBe(tabs)
})
})
describe('closeTabsAfter', () => {
it('keeps the prefix through the named tab', () => {
expect(names(closeTabsAfter(strip('a', 'b', 'c'), id('b')))).toEqual(['a', 'b'])
})
it('never drops the pinned block under an unpinned anchor', () => {
const mixed = [...pinnedStrip('p'), { sessionId: id('u'), order: 2 }]
expect(names(closeTabsAfter(mixed, id('u')))).toEqual(['p', 'u'])
})
})
describe('normalizeTabs', () => {
it('partitions pinned before unpinned, stably', () => {
const messy: SessionTab[] = [
{ sessionId: id('u1'), order: 1 },
{ sessionId: id('p1'), order: 2, pinned: true },
{ sessionId: id('u2'), order: 3 },
{ sessionId: id('p2'), order: 4, pinned: true },
]
expect(names(normalizeTabs(messy))).toEqual(['p1', 'p2', 'u1', 'u2'])
})
it('returns a copy of an already-normalized strip', () => {
const tabs = strip('a')
const normalized = normalizeTabs(tabs)
expect(normalized).toEqual(tabs)
expect(normalized).not.toBe(tabs)
})
})
describe('restoreTabsImpl', () => {
it('merges stored tabs without duplicating or re-keying a live one', () => {
const state: SessionTabsState = {
tabs: [{ sessionId: id('live'), order: 7 }],
order: 7,
}
restoreTabsImpl(state, [
{ sessionId: id('stored'), order: 2 },
{ sessionId: id('live'), order: 3 },
])
expect(names(state.tabs)).toEqual(['live', 'stored'])
// Every restored key is lifted above the counter so a later append cannot
// reuse one (a reused key makes React move a chip's DOM node).
expect(state.tabs.every(tab => tab.order <= state.order)).toBe(true)
expect(state.order).toBe(8)
})
it('restores a pinned tab into the pinned block, not at the end', () => {
const state: SessionTabsState = {
tabs: [{ sessionId: id('live'), order: 4 }],
order: 4,
}
restoreTabsImpl(state, [{ sessionId: id('kept'), order: 1, pinned: true }])
expect(names(state.tabs)).toEqual(['kept', 'live'])
expect(state.tabs[0]?.pinned).toBe(true)
})
it('empty stored strip writes nothing', () => {
const state: SessionTabsState = { tabs: [], order: 0 }
restoreTabsImpl(state, [])
expect(state).toEqual({ tabs: [], order: 0 })
})
})

View File

@ -5,18 +5,14 @@
* rows after the group folders (no "未分类" bucket).
* Pure derivation (no DOM), fixtures cast to the runtime contract types.
*
* The browser runtime bundle self-registers via window.__ModuleLoader__ and
* cannot execute in a plain node process, so the one value import it provides
* (`indexSubagentDescendants`) is stubbed; the fixtures carry no subagents.
* Every import reached from `tree.ts` is type-only except `indexSubagentDescendants`,
* which lives in this package (`subagent-lineage.ts`) and needs no stub; the
* fixtures carry no subagents.
*/
import { describe, expect, it, vi } from 'vitest'
vi.mock('@deepseek-ai/dsh-client-runtime/client', () => ({
indexSubagentDescendants: () => new Map(),
}))
import type { SessionListState, SessionSummary, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client'
import { deriveGroups, deriveTopLevel } from '../src/client/tree.ts'
import { describe, expect, it } from 'vitest'
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
import { deriveGroups, deriveSearchGroups, deriveTopLevel } from '../src/client/tree.ts'
import type { GroupsConfig, ManualGroups } from '../src/core/types.ts'
const CONFIG: GroupsConfig = {
@ -154,6 +150,35 @@ describe('deriveGroups with the manual overlay', () => {
})
})
describe('category appearance on the tree nodes', () => {
const ws = [workspace('ws-a', '/Users/zcol/Project/SomePlugin', 'DSH插件Demo', ['s1'])]
it('deriveGroups carries the appearance entry of each category', () => {
const manual: ManualGroups = {
categories: [],
assignments: {},
appearance: { 'DSH 插件': { color: 'blue', icon: 'code', pinned: true } },
}
const groups = deriveGroups(listState(ws), ws, [], CONFIG, VIEW, manual)
expect(groups[0]?.appearance).toEqual({ color: 'blue', icon: 'code', pinned: true })
})
it('deriveGroups omits appearance when the overlay has none', () => {
const groups = deriveGroups(listState(ws), ws, [], CONFIG, VIEW, { categories: [], assignments: {} })
expect(groups[0]?.appearance).toBeUndefined()
})
it('deriveSearchGroups carries appearance too', () => {
const manual: ManualGroups = {
categories: [],
assignments: {},
appearance: { 'DSH 插件': { color: 'red' } },
}
const tree = deriveSearchGroups(listState(ws), ws, CONFIG, new Set([session('s1', 'x').id]), [], manual)
expect(tree.categories[0]?.appearance).toEqual({ color: 'red' })
})
})
describe('deriveTopLevel', () => {
const ws = [
workspace('ws-a', '/Users/zcol/Project/SomePlugin', 'DSH插件Demo'),