v0.4: 拖拽插入位置指示 + 上下半落点判定(修复分组向下拖逻辑)

- 根因:分组排序仅支持 moveBefore(插到目标行前),向下拖想放目标后
  却落在其前;且无任何插入位置指示
- 新增 core/matcher.ts moveAfter(与 moveBefore 对称,目标缺失=追加)
- 拖拽按行上下半判定落点:上半=行前 / 下半=行后;2px 插入指示线
  .wgInsertBefore / .wgInsertAfter 实时显示落点,drop 按事件坐标即时重判
- 分组与项目排序均支持前/后双向;拖到未分类=追加末尾(恒最末)
- 更新展示截图 screenshot.png
- 单测 65/65,真机 CDP 30/30(含向下拖 6 项新断言),零侵入+现场恢复
This commit is contained in:
zcol 2026-08-22 01:20:12 +03:00
parent b56507bcf1
commit e08c4ed1e8
28 changed files with 3602 additions and 349 deletions

4
.gitignore vendored
View File

@ -1,3 +1,7 @@
node_modules/
*.log
.DS_Store
# 开发工程文件:docs 五级文档框架不进项目 git 仓库
docs/
AGENTS.md

View File

@ -20,8 +20,21 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
调整归类,无需改代码、无需重启(刷新页面生效)
- **树形搜索**:搜索命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮并
显示内容摘要,而不是扁平的结果列表
- **手动分组管理(所有分组)**:侧边栏区头「新建分组」按钮即建即显(空分组也渲染);
**每个分组行**(含规则分类)悬停出现 `⋯` 菜单 → 重命名 / 删除。删除分组后,
组内所有项目回到「未分类」;规则分类的重命名/删除经 overlay 生效(`renamed`/
`hidden`),规则 YAML 原样保留
- **拖拽归类 + 排序**:拖动项目文件夹到任意分组行 / 分组内项目行 = 移入该组
(拖到某项目行上半 = 插到它前面、下半 = 插到它后面,即**组内位置排序**,
拖动时实时显示 2px **插入位置指示线**,落点所见即所得);拖动时
**其他分组的项目自动收起**,源分组保留以便排序;拖到「未分类」或菜单
「移到未分类」= 强制归入未分类
- **分组拖拽排序**:分组行也可拖动(拖动时所有分组收起),拖到另一个分组行
上半 = 移到它前面、下半 = 移到它后面(指示线显示落点),即改变分组顺序;
**「未分类」永远在列表最底部**(分组恒在未分类项目之上)
- **零侵入**:不修改 `~/.dsh/storages/workspace.json`、不修改会话落盘结构、
不修改官方 `@deepseek-ai/dsh-client-ui-workspace` 包
不修改官方 `@deepseek-ai/dsh-client-ui-workspace` 包;手动分组/归类/排序写入独立
sidecar JSON(`~/.dsh/workspace-groups.manual.json`),规则 YAML 原样保留
- **功能不退化**:打开/新建/搜索会话、Add Workspace、项目重命名/删除、
会话重命名/派生/归档、展开状态持久化(独立 key,重启保留)
- **产物自包含**:`lib/` 已构建并随仓库分发,Git 安装无需执行任何依赖脚本
@ -33,8 +46,14 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
(官方以 priority 0 注册;single 槽位最低 priority 胜出)。
- 数据源全部复用运行时 API:`useWorkspaces` / `useSessions` 全局 hooks 与
`ctx.workspaces.*` / `ctx.sessions.*`,分类只是**展示层变换**。
- host 半只做一件事:把 sidecar YAML 解析为 JSON,经
`/workspace-groups/config` 路由(`Cache-Control: no-cache`)供 client 获取。
- host 半做两件事:把 sidecar YAML 解析为 JSON 与运行时 overlay 合并,经
`GET /workspace-groups/config` 路由(`Cache-Control: no-cache`)供 client 获取;
`PUT /workspace-groups/manual` 接收整份 overlay(手动分组、每工作区归类覆盖、
分组/项目排序、规则分类改名与隐藏),校验后原子写入
`$DSH_HOME/workspace-groups.manual.json`。
- **归类优先级**:手动覆盖(拖拽/菜单写入;`null` = 强制未分类)→ YAML 规则
自动归类(被隐藏的规则分类失效)→ 「未分类」桶(恒在最底部)。
YAML 永不改写。
## 安装(GitHub 分发)
@ -109,6 +128,45 @@ categories:
未命中任何分类的项目进入「未分类」桶,不会被隐藏。
## 手动分组与拖拽归类(runtime overlay)
规则 YAML 之外,还有一份插件自有的运行时 overlay,**只记录 UI 里的手动操作**,
默认位置 `$DSH_HOME/workspace-groups.manual.json`(例如 `~/.dsh/workspace-groups.manual.json`):
```json
{
"categories": ["临时", "归档"],
"assignments": {
"a1b2c3d4-e5f6-7890-abcd-ef1234567890": "临时",
"a1b2c3d4-e5f6-7890-abcd-ef1234567891": null
},
"categoryOrder": ["临时", "DSH 插件"],
"workspaceOrder": { "临时": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"] },
"renamed": { "DSH 插件": "插件集" },
"hidden": ["文档"]
}
```
- `categories` —— 手动新建的分组名(无规则,空分组也渲染);名称不可与规则分类
或「未分类」重复。
- `assignments` —— 工作区 → 分组的归类覆盖,键是稳定的工作区 id(重命名不影响)。
**优先级高于 YAML 规则**;值为 `null` 表示**强制归入未分类**(即使规则能匹配)。
- `categoryOrder` —— 分组显示顺序(「未分类」恒在最底部,不在此列)。
- `workspaceOrder` —— 每个分组内项目的手动排序(拖拽排序写入)。
- `renamed` / `hidden` —— 规则分类的 UI 改名/删除(隐藏后其规则失效,匹配项目
落入未分类);规则 YAML 原样保留。
- 文件由浏览器 UI 全量写入(`PUT /workspace-groups/manual`,原子替换),手工编辑
同样生效(下次加载时读取);写坏会返回 400 并保留原文件,不会破坏规则 YAML。
| 操作 | 入口 |
|---|---|
| 新建分组 | 区头「新建分组」按钮(文件夹图标),弹窗输入名称 |
| 重命名/删除分组 | **任意分组**(含规则分类)悬停 `⋯` 菜单;删除后组内项目回「未分类」 |
| 拖项目进分组 | 拖动项目行到目标分组行 / 分组内任意项目行,松手即移入 |
| 项目排序 | 拖动项目行到同组另一项目行:**上半 = 插到它前、下半 = 插到它后**(指示线显示落点);拖动时其他分组项目自动收起 |
| 移出分组 | 拖到「未分类」,或项目行菜单「移到未分类」(强制归入未分类) |
| 分组排序 | 拖动分组行到另一分组行:**上半 = 移到它前、下半 = 移到它后**(指示线显示落点;拖动时所有分组收起);未分类恒在底部 |
## 收录标签(topics)
本仓库面向 DSH 插件生态的自动收录(社区市场靠 GitHub topic 扫描发现),已设置:
@ -125,9 +183,10 @@ categories:
```sh
pnpm install
pnpm typecheck # host + client 双 program 类型检查
pnpm test # 核心规则与配置解析单测
pnpm test # 核心规则、overlay、树派生单测
pnpm build # 构建 lib/(node 半 + client bundle)
pnpm watch # tsdown 监听(client HMR)
node scripts/verify-groups.mjs # 真机 CDP 验证(host 已重启时;自启独立 headless Chrome,自动恢复现场)
```
产物契约(与官方 client 包一致):
@ -146,28 +205,46 @@ pnpm watch # tsdown 监听(client HMR)
```
src/
index.ts # host 半:config 路由
index.ts # host 半:config 快照路由 + manual 写路由
host-config.ts # sidecar YAML 读取/校验
host-manual.ts # runtime overlay 读写/校验(原子发布)
context-types.ts # host 侧 cordis 服务结构类型
core/
types.ts # 配置类型(两半共享)
matcher.ts # 分类规则纯函数(两半共享)
matcher.ts # 分类规则 + 手动覆盖优先级纯函数(两半共享)
client/
index.ts # apply:注册 sidebar.workspaces(priority -1)
contract.ts # 注入面类型
stores.ts # 展开状态 store(persist: dsh.workspace.groups.view.v1)
tree.ts # 三层树派生 + 树形搜索派生
GroupsBrowser.tsx # 浏览区域组件
rows.tsx # 分类/项目/会话/搜索结果行
GroupsBrowser.tsx # 浏览区域组件(分组弹窗 + 拖拽归类)
rows.tsx # 分类/项目/会话/搜索结果行(拖拽源/目标)
locales.ts # 中英文案
styles.css # 内联样式
tests/
core.test.ts # 分类规则 + 配置解析单测
core.test.ts # 分类规则 + 手动覆盖优先级 + 配置解析
manual.test.ts # overlay 校验 + 文件原子往返
tree.test.ts # 树派生渲染契约(手动分组空渲染/覆盖优先)
scripts/
verify-groups.mjs # 真机 CDP 验证(自启 headless Chrome,自动恢复现场)
docs/ # 五级项目文档(A 基准 / B 开发运维 / C 长期记忆 / dev / archive)
A/A-01-PRD/ # 001-分组存储 Service / 002-分组管理工具 / 003-分组可视化 UI
A/A-02-技术架构/ # 02-技术选型、05-角色推导
A/A-04-前端架构/ # 前端架构(client)
B/ # 开发规范 / 部署 / 测试 / BUG 库 / 工具清单 / 角色规格卡 / 子agent / 引导
C/C-01-项目长期记忆.md # 长期记忆(迁移、版本、已知限制)
archive/ # 归档(如 v0.1 验证记录)
```
## 验证记录
见 `docs/verification.md`(真实组合验证:headless Chrome + CDP 实操记录)。
- v0.1/v0.2 真实组合验证(headless Chrome + CDP 实操):
`docs/archive/verification-dsh-workspace-groups.md`(已归档,结论回写 C-01)。
- v0.3 真机验证 24/24(`scripts/verify-groups.mjs`:建组/拖拽/排序/收起/规则分类
菜单/重命名/删除回未分类/置底/现场恢复,零侵入断言),记录见 C-01。
- v0.4 真机验证 30/30(新增:插入指示线、项目/分组**向下拖**(行下半 → 插到目标
之后)、分组向上拖(行上半 → 移到目标之前);现场恢复通过),记录见 C-01。
- 可复跑的自动化真机验证:`node scripts/verify-groups.mjs`(需 host 已重启)。
## License

View File

@ -1,94 +0,0 @@
# 真实组合验证记录(dsh-workspace-groups)
验证日期:2026-08-21
验证对象:`dsh-workspace-groups@0.1.0`(link 安装于 `~/.dsh/profiles/web`)
运行环境:`dsh web`(PID 90954),GUI http://127.0.0.1:3080,官方 dsh 0.1.1-rc.2
## 1. 安装与组合层验证
| 检查项 | 结果 |
|---|---|
| `dsh plugin --profile web add` 自动对账 bundles | ✅ 追加 `dsh-workspace-groups` 至 `dsh.profile.bundles` |
| `dsh --profile web --dump-config` 出现插件层 | ✅ `- id: workspace-groups / name: dsh-workspace-groups / config: {}` |
| 重启后 boot manifest 含插件 client 行 | ✅ `dsh-workspace-groups` 出现于 `__DSH_BOOT__.entries` |
| client bundle 可服务 | ✅ `/plugins/dsh-workspace-groups/client.js` 返回 ModuleLoader 包装 |
| host config 路由 | ✅ `GET /workspace-groups/config` 200,返回 sidecar JSON |
## 2. 顶替与数据链路(最小验证先行,三项全绿)
1. **顶替默认 WorkspaceBrowser**:侧边栏渲染 `.wgRoot` 树(非官方浏览器);
CDP 断言 `officialBrowser: false`、`wgRoot: true` ✅
2. **useWorkspaces 数据完整**:6 个工作区全部可见并按 sidecar 归类 ✅
3. **一层树渲染**:分类 → 项目 → 会话三层结构渲染成功 ✅
## 3. 分类结果(sidecar 实际生效)
```
DSH 插件 (4) ← pathPrefix 规则命中
├── DSH-工作区分组
├── DeepSeek峰谷小组件
├── Documentation-Driven AI Coding
└── SkillsManagePlugins
个人项目 (2)
├── 闲谝
└── yeluzi
```
计数与 `~/.dsh/storages/workspace.json` 的 6 个工作区精确一致。
## 4. 交互验证(headless Chrome + CDP 实操)
| 操作 | 结果 |
|---|---|
| 点击分类「个人项目」 | ✅ 展开,显示闲谝 / yeluzi 项目 |
| 刷新页面 | ✅ 展开状态保留(store `dsh.workspace.groups.view.v1` 持久化) |
| 点击会话 `Docs AI Coding` | ✅ 选中态迁移到该会话(`.wgSelected`),打开生效 |
| 搜索「DSH」 | ✅ 返回 `Docs AI Coding · DSH-工作区分组`(workspace 归属保留) |
| 清除搜索 | ✅ 恢复三层树 |
## 5. 存储零侵入断言
| 检查项 | 结果 |
|---|---|
| `workspace.json` 结构 | ✅ 无 `category` 字段,unit.version=2 不变,workspace 计数 6 |
| 会话落盘 | ✅ 未新增/改动任何 session 文件 |
| 官方 view store | ✅ `dsh.workspace.view.v5` 未被触碰(仅新增独立 key `dsh.workspace.groups.view.v1`) |
| host 暴露面 | ✅ 仅一个只读 GET 路由 `/workspace-groups/config`(no-cache) |
## 6. 构建与质量门
| 检查项 | 结果 |
|---|---|
| `pnpm typecheck`(host + client 双 program) | ✅ 0 错误 |
| `pnpm test` | ✅ 12/12 通过(分类规则、配置解析) |
| `pnpm build` | ✅ lib/index.js(96KB,js-yaml 内联)+ lib/client.js(56KB)+ types |
| client bundle purity | ✅ 仅 require 平台 seed(react / runtime/client / primitives),跨插件值 import 被拒 |
| host bundle 自包含 | ✅ 零外部运行时 require(js-yaml 已内联) |
## 7. 已知限制(非缺陷)
- 会话拖拽排序未实现(当前行交互为打开/重命名/派生/归档;官方浏览器同样具备的
拖拽排序在 v0.1 未移植)。项目拖拽排序同样未移植。
- 分类/项目的折叠状态自动展开当前会话所在分类与项目(与官方行为一致)。
- Add Workspace 使用原生目录选择器(`ctx.workspaces.pickDirectory`),
无官方 WorkspacePickFlow 的菜单选择既有工作区功能 —— 已在功能上等价覆盖
(既有工作区在树中始终可见)。
## 8. 缺陷修复记录(2026-08-21 二轮验证)
**Bug:当前分类/项目无法收缩**(用户报告)
- 现象:包含当前会话的「DSH 插件」分类与其下「DSH-工作区分组」项目无法折叠,
其他节点正常。
- 根因:store 折叠用 `delete` 删 key + auto-expand effect 用 `!expansion[key]`
守卫 —— 折叠后 key 缺失 → effect 重新展开。
- 修复:折叠改写入 `false`(key 保留,同官方 `setGroupExpanded` 语义);
auto-expand 守卫改 `Object.hasOwn`(仅从未操作过的 key 自动展开)。
- 验证(CDP 实操,全新 profile):
| 操作 | 结果 |
|---|---|
| 收缩「DSH 插件」(当前分类) | ✅ 折叠,2s 后不反弹,store `{"DSH 插件": false}` |
| 再展开「DSH 插件」 | ✅ 恢复正常 |
| 折叠后刷新 | ✅ 折叠状态持久保留 |
| 收缩「DSH-工作区分组」(当前项目)后刷新 | ✅ 保持折叠(sessions 隐藏) |
- 回归:`pnpm typecheck` 0 错误;`pnpm test` 18/18(新增 6 个 store 语义测试)。

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,5 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { homedir } from "node:os";
//#region node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs
function getDefaultExportFromCjs(x) {
@ -2445,6 +2445,16 @@ 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
/** The label of the fallback bucket for unmatched workspaces. */
const UNCATEGORIZED_LABEL = "未分类";
//#endregion
//#region src/core/matcher.ts
/** Display name of a rule category: the rename override when present. */
function ruleDisplayName(manual, originalName) {
return manual?.renamed?.[originalName] ?? originalName;
}
//#endregion
//#region src/host-config.ts
/**
* Sidecar config reading for dsh-workspace-groups. The classification rules
@ -2516,19 +2526,211 @@ async function readGroupsConfig(path) {
return parseGroupsConfig(load(text));
}
//#endregion
//#region src/host-manual.ts
/**
* Runtime grouping overlay for dsh-workspace-groups: manual groups created in
* the sidebar UI and per-workspace category overrides. Stored in a plugin-
* owned JSON sidecar (`$DSH_HOME/workspace-groups.manual.json`), separate from
* the operator YAML — the YAML stays the rule source, this file only records
* runtime decisions, and writes are atomic (temp file + fsync + rename).
*
* The browser PUT route writes the whole overlay (idempotent, last write
* wins); reads tolerate hand-edited content (parse-only) while the write
* boundary cross-validates against the current rule categories.
*/
/** Default overlay location: `$DSH_HOME/workspace-groups.manual.json`. */
function defaultManualPath() {
const home = process.env.DSH_HOME !== void 0 && process.env.DSH_HOME !== "" ? process.env.DSH_HOME : resolve(homedir(), ".dsh");
return resolve(home, "workspace-groups.manual.json");
}
/**
* Parse + shape-validate a raw overlay document into a ManualGroups.
* Validates types only — category references are checked against the rule set
* at the write boundary (validateManualGroups), because reads must tolerate
* files written while the rule set was different.
* @param raw - parsed JSON value.
* @returns the normalized overlay.
* @throws when the shape is malformed (non-mapping, bad names, duplicates,
* the reserved uncategorized label, bad assignment/order values).
*/
function parseManualGroups(raw) {
if (raw === void 0 || raw === null) return {
categories: [],
assignments: {}
};
if (typeof raw !== "object" || Array.isArray(raw)) throw new Error("workspace-groups.manual.json: top-level value must be a mapping");
const source = raw;
const categories = [];
if (source.categories !== void 0) {
if (!Array.isArray(source.categories)) throw new Error("workspace-groups.manual.json: categories must be a list");
const seen = /* @__PURE__ */ new Set();
for (const entry of source.categories) {
if (typeof entry !== "string" || entry.trim() === "") throw new Error("workspace-groups.manual.json: each manual category must be a non-empty string");
const name = entry.trim();
if (name === "未分类") throw new Error(`workspace-groups.manual.json: manual category name "${name}" is reserved`);
if (seen.has(name)) throw new Error(`workspace-groups.manual.json: duplicate manual category "${name}"`);
seen.add(name);
categories.push(name);
}
}
const assignments = {};
if (source.assignments !== void 0) {
if (typeof source.assignments !== "object" || source.assignments === null || Array.isArray(source.assignments)) throw new Error("workspace-groups.manual.json: assignments must be a mapping");
for (const [workspaceId, category] of Object.entries(source.assignments)) {
if (workspaceId.trim() === "") throw new Error("workspace-groups.manual.json: assignment keys must be non-empty");
if (category === null) {
assignments[workspaceId] = null;
continue;
}
if (typeof category !== "string" || category.trim() === "") throw new Error(`workspace-groups.manual.json: assignment "${workspaceId}" must be a category name or null`);
assignments[workspaceId] = category.trim();
}
}
const manual = {
categories,
assignments
};
if (source.categoryOrder !== void 0) manual.categoryOrder = parseStringList(source.categoryOrder, "categoryOrder", true);
if (source.hidden !== void 0) manual.hidden = parseStringList(source.hidden, "hidden", true);
if (source.renamed !== void 0) {
if (typeof source.renamed !== "object" || source.renamed === null || Array.isArray(source.renamed)) throw new Error("workspace-groups.manual.json: renamed must be a mapping");
const renamed = {};
for (const [original, display] of Object.entries(source.renamed)) {
if (original.trim() === "") throw new Error("workspace-groups.manual.json: renamed keys must be non-empty");
if (typeof display !== "string" || display.trim() === "") throw new Error(`workspace-groups.manual.json: renamed "${original}" must be a non-empty string`);
renamed[original] = display.trim();
}
manual.renamed = renamed;
}
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 = {};
for (const [categoryKey, ids] of Object.entries(source.workspaceOrder)) {
if (categoryKey.trim() === "") throw new Error("workspace-groups.manual.json: workspaceOrder keys must be non-empty");
workspaceOrder[categoryKey] = parseStringList(ids, `workspaceOrder["${categoryKey}"]`, true);
}
manual.workspaceOrder = workspaceOrder;
}
return manual;
}
/** 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`);
const seen = /* @__PURE__ */ new Set();
const result = [];
for (const entry of value) {
if (typeof entry !== "string" || entry.trim() === "") throw new Error(`workspace-groups.manual.json: ${field} entries must be non-empty strings`);
const trimmed = entry.trim();
if (unique && seen.has(trimmed)) throw new Error(`workspace-groups.manual.json: ${field} has duplicate entry "${trimmed}"`);
seen.add(trimmed);
result.push(trimmed);
}
return result;
}
/**
* Cross-validate a parsed overlay against the current rule categories
* (write boundary only). Every assignment value must be `null`, a rule
* display name, a manual category name, or the uncategorized label; order
* keys must reference existing categories; renames/hides must reference
* actual rule categories.
* @param manual - parsed overlay.
* @param ruleCategoryNames - current YAML rule category original names.
* @throws when the overlay references categories that do not exist.
*/
function validateManualGroups(manual, ruleCategoryNames) {
const ruleNames = new Set(ruleCategoryNames);
const allowed = new Set(ruleCategoryNames.map((name) => ruleDisplayName(manual, name)));
for (const name of manual.categories) allowed.add(name);
allowed.add(UNCATEGORIZED_LABEL);
for (const [workspaceId, category] of Object.entries(manual.assignments)) {
if (category === null) continue;
if (!allowed.has(category)) throw new Error(`workspace-groups.manual.json: assignment "${workspaceId}" references unknown category "${category}"`);
}
for (const key of manual.categoryOrder ?? []) if (!allowed.has(key) || key === "未分类") throw new Error(`workspace-groups.manual.json: categoryOrder references unknown category "${key}"`);
for (const key of Object.keys(manual.workspaceOrder ?? {})) if (!allowed.has(key) || key === "未分类") throw new Error(`workspace-groups.manual.json: workspaceOrder references unknown category "${key}"`);
for (const original of Object.keys(manual.renamed ?? {})) if (!ruleNames.has(original)) throw new Error(`workspace-groups.manual.json: renamed references unknown rule category "${original}"`);
for (const original of manual.hidden ?? []) if (!ruleNames.has(original)) throw new Error(`workspace-groups.manual.json: hidden references unknown rule category "${original}"`);
}
/** Read + parse the overlay file. A missing file yields an empty overlay. */
async function readManualGroups(path) {
let text;
try {
text = await readFile(path, "utf8");
} catch (error) {
if (error.code === "ENOENT") return {
categories: [],
assignments: {}
};
throw error;
}
return parseManualGroups(JSON.parse(text));
}
/**
* Atomically replace the overlay file: write a same-directory temp file,
* fsync it, then rename over the target. A crash never leaves a torn JSON at
* the real path (readers see either the old or the new file).
* @param path - target file path.
* @param manual - overlay to persist.
*/
async function writeManualGroups(path, manual) {
const json = `${JSON.stringify(manual, null, 2)}\n`;
await mkdir(dirname(path), { recursive: true });
const tmp = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
const handle = await open(tmp, "w");
try {
await handle.writeFile(json, "utf8");
await handle.sync();
} catch (error) {
await handle.close().catch(() => {});
await unlink(tmp).catch(() => {});
throw error;
}
await handle.close();
try {
await rename(tmp, path);
} catch (error) {
await unlink(tmp).catch(() => {});
throw error;
}
}
//#endregion
//#region src/index.ts
/** Plugin identity for cordis.yml rows. */
const name = "dsh-workspace-groups";
/** Services required before mounting: the webserver route. */
const inject = ["webServer"];
/** Cap on the PUT body: the overlay is tiny; anything bigger is a client bug. */
const MAX_MANUAL_BODY_BYTES = 65536;
/** Error with an HTTP status, mapped to a plain-text 4xx/5xx response. */
var HttpError = class extends Error {
status;
constructor(status, message) {
super(message);
this.status = status;
}
};
/** Write a plain-text error response with the given status. */
function writeError(res, status, message) {
res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8" });
res.end(message);
}
/** Plugin body: mount the config route. */
/** Collect the request body as UTF-8 text, rejecting oversized bodies. */
async function readBody(req, limit) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
size += buffer.length;
if (size > limit) throw new HttpError(413, "request body too large");
chunks.push(buffer);
}
if (chunks.length === 0) throw new HttpError(400, "empty request body");
return Buffer.concat(chunks).toString("utf8");
}
/** Plugin body: mount the config snapshot route and the overlay write route. */
function apply(ctx) {
const configPath = defaultConfigPath();
const manualPath = defaultManualPath();
ctx.effect(() => ctx.webServer.register({
kind: "exact",
path: "/workspace-groups/config",
@ -2538,13 +2740,17 @@ function apply(ctx) {
return;
}
let config;
let manual;
try {
config = await readGroupsConfig(configPath);
[config, manual] = await Promise.all([readGroupsConfig(configPath), readManualGroups(manualPath)]);
} catch (error) {
writeError(res, 500, `workspace-groups: failed to read config: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const body = JSON.stringify(config);
const body = JSON.stringify({
...config,
manual
});
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-cache",
@ -2553,6 +2759,45 @@ function apply(ctx) {
res.end(req.method === "HEAD" ? void 0 : body);
}
}), "dsh-workspace-groups: /workspace-groups/config route");
ctx.effect(() => ctx.webServer.register({
kind: "exact",
path: "/workspace-groups/manual",
handler: async (req, res) => {
if (req.method !== "PUT") {
writeError(res, 405, "method not allowed");
return;
}
let raw;
try {
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES));
} catch (error) {
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
let manual;
try {
manual = parseManualGroups(raw);
const ruleConfig = (await readGroupsConfig(configPath)).categories;
validateManualGroups(manual, ruleConfig.map((category) => category.name));
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
try {
await writeManualGroups(manualPath, manual);
} catch (error) {
writeError(res, 500, `workspace-groups: failed to write manual overlay: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const body = JSON.stringify({ ok: true });
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(body)
});
res.end(body);
}
}), "dsh-workspace-groups: /workspace-groups/manual route");
}
//#endregion
export { apply, inject, name };

View File

@ -1,4 +1,24 @@
import type { GroupsBrowserProps } from './contract.ts';
/** Row reference used by drop targets: which kind of row, which key. */
export type DropRowRef = {
kind: 'category' | 'workspace';
key: string;
};
/**
* Current drop indicator. A `line` renders a 2px insertion line above/below a
* row (project reorder inside a group, or group reorder); an `into` renders
* the whole-row highlight used when dropping a project into a group. Drop
* handlers re-derive before/after from the drop event itself, so the
* indicator is purely visual and can never go stale.
*/
export type DragIndicator = {
mode: 'line';
row: DropRowRef;
before: boolean;
} | {
mode: 'into';
categoryKey: string;
} | null;
/**
* Render the browsing region.
* @param props - composed slot props (shell owner share + store + injected actions).

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' | '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';
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.moveToUncategorized' | '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' | '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';
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
/** Simplified Chinese dictionary. */
export declare const zh: WorkspaceGroupsDict;

View File

@ -1,26 +1,70 @@
/**
* Row components for the workspace-groups tree. Kept dependency-light: they
* consume only React, primitives (StateDot/Menu/icons), and the shared CSS
* string. Each row owns its hover actions menu; dialogs live in the browser
* root so they survive row unmounts during collapse.
*
* Drag & drop: workspace rows are draggable sources; category rows (and
* workspace rows, standing for their containing category) are drop targets.
* The payload is a custom dataTransfer type so only in-plugin drags land.
*/
import { type DragEvent } from 'react';
import { type StateDotState } from '@deepseek-ai/dsh-client-ui-primitives';
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts';
type T = TranslateNS<'workspaceGroups'>;
/** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */
export declare const DND_WORKSPACE_TYPE = "application/x-dsh-workspace-groups";
/** dataTransfer type carrying the dragged category key (group reorder). */
export declare const DND_CATEGORY_TYPE = "application/x-dsh-workspace-groups-category";
/** Whether a drag carries any of the plugin's payloads (drop targets accept both). */
export declare function hasPluginDragType(types: DOMStringList | readonly string[]): boolean;
/** Primary status dot state for a session row. */
export declare function sessionDotState(node: Pick<SessionNode, 'pendingInteraction' | 'running' | 'runningSubagentCount' | 'completed'>): StateDotState;
/** Compact relative time ("now"/"5min"/"3h"/"2d"/"4mo"/"1y"). */
export declare function relativeTimeLabel(updatedAt: number, now: number): string;
/** One category folder row. */
export declare function CategoryRow({ node, t, onToggle }: {
/** Drop-target props shared by category and workspace rows (all optional). */
export interface RowDropProps {
/** Row is under the dragged workspace — show the drop highlight. */
dropActive?: boolean;
/** Insertion indicator: a line above (before) or below (after) this row. */
insertLine?: 'before' | 'after';
/** Accept a drag over this row (must preventDefault to allow the drop). */
onRowDragOver?: (event: DragEvent) => void;
/** Clear the highlight when the pointer leaves the row. */
onRowDragLeave?: (event: DragEvent) => void;
/** Drop a workspace onto this row. */
onRowDrop?: (event: DragEvent) => void;
}
/**
* 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 }: {
node: CategoryNode;
t: T;
onToggle: () => void;
}): import("react").JSX.Element;
/** One workspace folder row inside a category. */
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete }: {
/** Rename/delete actions; the hover menu renders only when both provided. */
onRename?: () => void;
onDelete?: () => void;
/** Group reorder source; the row becomes draggable only when provided. */
onDragStartCategory?: (event: DragEvent) => void;
} & RowDropProps): import("react").JSX.Element;
/** One workspace folder row inside a category: draggable source + drop target. */
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, hasOverride, onMoveOut, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
node: WorkspaceGroupNode;
t: T;
onToggle: () => void;
onNewSession: () => void;
onRename: () => void;
onDelete: () => void;
}): import("react").JSX.Element;
/** Workspace has a manual group override — offer "move to uncategorized". */
hasOverride?: boolean;
onMoveOut?: () => void;
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
onDragStartExtra?: () => void;
} & RowDropProps): import("react").JSX.Element;
/** One session leaf row. */
export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
node: SessionNode;

View File

@ -5,7 +5,7 @@
* (blank rows only when current, archived excluded, subagent rows excluded).
*/
import { type PendingInteractionStatus, type SessionId, type SessionListState, type SessionSearchResultItem, type WorkspaceId, type WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client';
import { type GroupsConfig } from '../core/types.ts';
import { type GroupsConfig, type ManualGroups } from '../core/types.ts';
/** One top-level session row inside a workspace folder. */
export interface SessionNode {
id: SessionId;
@ -68,11 +68,15 @@ export declare function workspaceLabel(cwd: string | undefined): string;
* @param list - sessions list snapshot (`current` feeds containsCurrent).
* @param workspaces - real workspaces in stable Host order.
* @param archivedSessionIds - registry-global archive set.
* @param config - sidecar grouping config.
* @param config - sidecar grouping config (rule categories).
* @param view - local expansion arrays.
* @returns category sections in render order (configured categories first, uncategorized last).
* @param manual - runtime overlay (manual groups + overrides). A workspace's
* manual override wins over rule classification; removing it reverts to rules.
* @returns category sections in render order (rule categories first, then
* manual-only ones, uncategorized last). Manual groups render even while
* empty; empty rule buckets stay hidden.
*/
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView): CategoryNode[];
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups): CategoryNode[];
/** Bounded set of matched sessions plus content snippets (feeds the search tree). */
export interface SearchMatchSet {
/** Session ids that matched (local metadata hits + Host content hits). */
@ -94,13 +98,16 @@ export declare function deriveSearchMatches(list: SessionListState, workspaces:
* Build a three-level search tree containing ONLY the branches that hold a
* matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched
* session carries `matched: true` so rows render with the search-hit tint.
* Classification uses the same precedence as the idle tree (manual override →
* rules), so search shows the same grouping the user sees.
*
* @param list - sessions list snapshot.
* @param workspaces - real workspaces in stable Host order.
* @param config - sidecar grouping config.
* @param matchedIds - set of session ids that matched the query.
* @param archivedSessionIds - registry-global archive set.
* @param manual - runtime overlay (manual groups + overrides).
* @param snippetsBySession - optional content-match snippets keyed by session id.
* @returns categories in render order, pruned to matched branches only.
*/
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], snippetsBySession?: ReadonlyMap<SessionId, string>): CategoryNode[];
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>): CategoryNode[];

View File

@ -1,15 +1,61 @@
/**
* Pure classification logic: decides which category a workspace belongs to.
* Shared by the host half (validation) and the client half (tree derivation),
* so the rule semantics can never drift between the config surface and the
* rendered tree.
*/
import { type GroupCategory } from './types.ts';
/**
* Classify a workspace into its category.
* @param categories - configured categories, in render order.
* @param path - workspace canonical directory path.
* @param title - workspace display title.
* @returns the matching category, or undefined when no rule matches.
* Pure classification + ordering logic: decides which category a workspace
* belongs to and how categories/workspaces are ordered. Shared by the host
* half (validation) and the client half (tree derivation), so the semantics
* can never drift between the config surface and the rendered tree.
*
* Category identity: a category's STABLE origin is its YAML rule category
* name (or a manual-group name). Its DISPLAY key is what the tree renders and
* what assignments reference — for rule categories that is the rename
* override when present. Hidden rule categories are inert: workspaces that
* would match them fall into the uncategorized bucket.
*/
import { 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;
/** 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). */
export declare function originalRuleNameForDisplay(categories: readonly GroupCategory[], manual: ManualGroups | undefined, key: string): string | undefined;
/**
* Effective category entries in display order: rule categories (YAML order,
* hidden skipped, renamed applied) first, then manual-only groups in
* creation order — unless `manual.categoryOrder` overrides the sequence.
* The uncategorized bucket is never included (it always renders last).
*/
export interface EffectiveCategory {
/** Display key (what the tree renders and assignments reference). */
key: string;
/** Origin: a YAML rule category or a manual group. */
source: 'rule' | 'manual';
}
export declare function effectiveCategories(config: GroupsConfig, manual: ManualGroups | undefined): EffectiveCategory[];
/** Display keys of all effective categories (uncategorized bucket excluded). */
export declare function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[];
/**
* Resolve the category key a workspace renders under. Precedence:
* manual override (`null` = force uncategorized) → rule classification
* (hidden rules inert) → uncategorized bucket (`undefined`).
*/
export declare function resolveCategory(config: GroupsConfig, manual: ManualGroups | undefined, workspaceId: string, path: string, title: string): string | undefined;
/** Whether a category key is a manual-only group (manageable via list). */
export declare function isManualOnlyCategory(config: GroupsConfig, manual: ManualGroups | undefined, key: string): boolean;
/**
* Names that may not be used for a new/renamed group: the reserved
* uncategorized label plus every current display key.
*/
export declare function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set<string>;
/**
* Order a bucket of workspace ids: the stored per-category order first
* (filtered to actual members), then any remaining members in `fallback`
* (host) order. Deterministic; the renderer never re-sorts on its own.
*/
export declare function orderedWorkspaceIds(manual: ManualGroups | undefined, categoryKey: string, members: readonly string[]): string[];
/** Move `id` before `beforeId` (undefined = append) within an ordered list. */
export declare function moveBefore(list: readonly string[], id: string, beforeId: string | undefined): string[];
/** Move `id` after `afterId` (undefined = append) within an ordered list. */
export declare function moveAfter(list: readonly string[], id: string, afterId: string | undefined): string[];

View File

@ -25,6 +25,61 @@ export interface GroupCategory {
export interface GroupsConfig {
/** Category folders, in render order. First match wins. */
categories: GroupCategory[];
/**
* Runtime grouping overlay (manual groups + per-workspace overrides).
* Optional: the YAML file itself never carries it — the host GET route
* merges it from `workspace-groups.manual.json`, and the browser PUT route
* replaces it whole.
*/
manual?: ManualGroups;
}
/**
* Runtime-managed grouping overlay: groups created in the sidebar UI plus
* per-workspace category overrides and user-controlled ordering. Owned by the
* plugin (JSON sidecar, `$DSH_HOME/workspace-groups.manual.json`), never
* written back into the operator YAML.
*
* 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.
*/
export interface ManualGroups {
/**
* Manually created category folder names. These have no rules — they render
* even while empty (a new group appears before anything is dragged into
* it) and hold only workspaces assigned to them.
*/
categories: string[];
/**
* Per-workspace category override, keyed by workspace id. Value is a
* category display name (rule or manual), or `null` to force the workspace
* into the uncategorized bucket even when a rule would match. An absent
* key means "classify by rules".
*/
assignments: Record<string, string | null>;
/**
* Display order of all category keys (rule display names + manual names).
* The uncategorized bucket is never listed — it always renders last.
* Absent = rule categories first (YAML order), manual groups appended in
* creation order.
*/
categoryOrder?: string[];
/**
* Per-category ordered workspace ids (user drag-reorder within a group).
* Keyed by category display name; absent key = host registration order.
*/
workspaceOrder?: Record<string, string[]>;
/**
* Rule category rename overrides: original YAML rule category name →
* display name (UI rename of a rule group). Rules still classify by the
* original name; only the rendered label/keys change.
*/
renamed?: Record<string, string>;
/**
* Rule category original names hidden by a UI delete. Hidden rules are
* inert: workspaces matching them fall into the uncategorized bucket.
*/
hidden?: string[];
}
/** The label of the fallback bucket for unmatched workspaces. */
export declare const UNCATEGORIZED_LABEL = "\u672A\u5206\u7C7B";

35
lib/types/host-manual.d.ts vendored Normal file
View File

@ -0,0 +1,35 @@
import { type ManualGroups } from './core/types.ts';
/** Default overlay location: `$DSH_HOME/workspace-groups.manual.json`. */
export declare function defaultManualPath(): string;
/**
* Parse + shape-validate a raw overlay document into a ManualGroups.
* Validates types only — category references are checked against the rule set
* at the write boundary (validateManualGroups), because reads must tolerate
* files written while the rule set was different.
* @param raw - parsed JSON value.
* @returns the normalized overlay.
* @throws when the shape is malformed (non-mapping, bad names, duplicates,
* the reserved uncategorized label, bad assignment/order values).
*/
export declare function parseManualGroups(raw: unknown): ManualGroups;
/**
* Cross-validate a parsed overlay against the current rule categories
* (write boundary only). Every assignment value must be `null`, a rule
* display name, a manual category name, or the uncategorized label; order
* keys must reference existing categories; renames/hides must reference
* actual rule categories.
* @param manual - parsed overlay.
* @param ruleCategoryNames - current YAML rule category original names.
* @throws when the overlay references categories that do not exist.
*/
export declare function validateManualGroups(manual: ManualGroups, ruleCategoryNames: readonly string[]): void;
/** Read + parse the overlay file. A missing file yields an empty overlay. */
export declare function readManualGroups(path: string): Promise<ManualGroups>;
/**
* Atomically replace the overlay file: write a same-directory temp file,
* fsync it, then rename over the target. A crash never leaves a torn JSON at
* the real path (readers see either the old or the new file).
* @param path - target file path.
* @param manual - overlay to persist.
*/
export declare function writeManualGroups(path: string, manual: ManualGroups): Promise<void>;

View File

@ -3,5 +3,5 @@ import type { GroupsContext } from './context-types.ts';
export declare const name = "dsh-workspace-groups";
/** Services required before mounting: the webserver route. */
export declare const inject: string[];
/** Plugin body: mount the config route. */
/** Plugin body: mount the config snapshot route and the overlay write route. */
export declare function apply(ctx: GroupsContext): void;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 173 KiB

457
scripts/verify-groups.mjs Normal file
View File

@ -0,0 +1,457 @@
/**
* CDP 真机验证脚本(dsh-workspace-groups v0.2/v0.3)。
*
* 用法:
* node scripts/verify-groups.mjs [baseUrl] [cdpPort] [chromeBin]
*
* 行为:
* - 启动独立 headless Chrome(独立 user-data-dir),打开 baseUrl 的 GUI;
* - v0.2:新建分组弹窗 → 空分组渲染 → 拖拽项目进分组 → PUT 落盘 →
* 刷新持久化 → 非法 PUT 400;
* - v0.3:拖拽项目组内排序 + 拖动时其他分组项目收起、规则分类行出现
* 「⋯」菜单 → 重命名(renamed 落盘)→ 删除(成员回未分类 + hidden 落盘)、
* 未分类恒为最末段;
* - v0.4:拖拽插入位置指示线(上半=插到行前 / 下半=插到行后):项目
* 拖到目标行下半 → 插到目标之后;分组向下拖 → 移到目标分组之后、
* 向上拖 → 移到目标分组之前;
* - 现场恢复:还原原 overlay(原无文件则删除),不留测试数据;
* - 依赖 host 已重启(PUT /workspace-groups/manual 可用);
* - 以 0/1 退出码供质量门调用。
*/
import { spawn } from 'node:child_process'
import { mkdtemp, rm, unlink, access } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const BASE = process.argv[2] ?? 'http://127.0.0.1:3080'
const CDP_PORT = Number(process.argv[3] ?? 9333)
const CHROME = process.argv[4] ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
const results = []
function report(name, ok, detail = '') {
results.push({ name, ok })
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`)
}
/** Minimal CDP client over one WebSocket. */
class CDP {
constructor(wsUrl) {
this.ws = new WebSocket(wsUrl)
this.nextId = 1
this.pending = new Map()
}
async open() {
await new Promise((resolve, reject) => {
this.ws.addEventListener('open', resolve, { once: true })
this.ws.addEventListener('error', reject, { once: true })
})
this.ws.addEventListener('message', (event) => {
const msg = JSON.parse(event.data)
if (msg.id !== undefined && this.pending.has(msg.id)) {
const { resolve, reject } = this.pending.get(msg.id)
this.pending.delete(msg.id)
if (msg.error) reject(new Error(msg.error.message))
else resolve(msg.result)
}
})
}
send(method, params = {}) {
const id = this.nextId++
this.ws.send(JSON.stringify({ id, method, params }))
return new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }))
}
close() { this.ws.close() }
}
const sleep = (ms) => new Promise(r => setTimeout(r, ms))
async function main() {
const profileDir = await mkdtemp(join(tmpdir(), 'wg-cdp-'))
let chrome
let page
try {
chrome = spawn(CHROME, [
`--remote-debugging-port=${CDP_PORT}`,
`--user-data-dir=${profileDir}`,
'--headless=new',
'--no-first-run',
'--no-default-browser-check',
'--window-size=1440,900',
'about:blank',
], { stdio: 'ignore' })
// Wait for the DevTools endpoint.
let targets
for (let i = 0; i < 60; i++) {
try {
const res = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`)
if (res.ok) break
} catch { /* not up yet */ }
await sleep(250)
}
if (chrome.exitCode !== null) throw new Error('chrome exited early')
// Open the GUI page.
const newRes = await fetch(`http://127.0.0.1:${CDP_PORT}/json/new?${encodeURIComponent(BASE)}`, { method: 'PUT' })
const target = await newRes.json()
page = new CDP(target.webSocketDebuggerUrl)
await page.open()
const evaluate = async (expression) => {
const result = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
if (result.exceptionDetails) throw new Error(`page evaluate failed: ${JSON.stringify(result.exceptionDetails)}`)
return result.result.value
}
const waitFor = async (expression, timeoutMs = 15000) => {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (await evaluate(expression)) return true
await sleep(250)
}
return false
}
// ---- 0. host 面就绪(GET 含 manual;PUT 可用) ----
let snapshot
try {
const res = await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' })
snapshot = await res.json()
report('host GET /workspace-groups/config 返回 manual 字段', res.ok && 'manual' in snapshot, `manual=${JSON.stringify(snapshot.manual)}`)
} catch (error) {
report('host GET /workspace-groups/config 可访问', false, String(error))
return 1
}
const originalManual = snapshot.manual ?? { categories: [], assignments: {} }
const overlayPath = join(process.env.DSH_HOME ?? join(process.env.HOME ?? '.', '.dsh'), 'workspace-groups.manual.json')
const overlayExistedBefore = await access(overlayPath).then(() => true, () => false)
// ---- 1. GUI 树就绪 ----
report('GUI 三层树渲染(.wgRoot + 项目行)', await waitFor(`document.querySelectorAll('.wgProjectRow').length > 0`))
report('区头存在「新建分组」按钮', await evaluate(`!!document.querySelector('button[aria-label="新建分组"]')`))
// ---- 2. 新建分组 ----
const groupName = '验证分组'
await evaluate(`document.querySelector('button[aria-label="新建分组"]').click()`)
report('新建分组弹窗出现', await waitFor(`!!document.querySelector('.wgRenameInput')`))
await evaluate(`(() => {
const input = document.querySelector('.wgRenameInput')
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set
setter.call(input, ${JSON.stringify(groupName)})
input.dispatchEvent(new Event('input', { bubbles: true }))
})()`)
await evaluate(`(() => {
const btn = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === '创建')
if (btn) btn.click()
})()`)
report('空分组立即渲染', await waitFor(`!!document.querySelector('.wgCategoryRow[data-wg-category="${groupName}"]')`))
// ---- 3. 拖拽项目进分组 ----
const wsid = await evaluate(`document.querySelector('.wgProjectRow')?.getAttribute('data-wsid') ?? ''`)
if (wsid === '') { report('取到待拖拽项目行', false); return 1 }
const dragStart = await evaluate(`(() => {
const source = document.querySelector('.wgProjectRow[data-wsid="${wsid}"]')
const target = document.querySelector('.wgCategoryRow[data-wg-category="${groupName}"]')
if (!source || !target) return { error: 'missing source/target' }
const dt = new DataTransfer()
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
const types = Array.prototype.slice.call(dt.types || [])
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: dt }))
target.__wgDt = dt // reuse the same DataTransfer for the drop step
return { types }
})()`)
report('dragstart 携带自定义类型', dragStart.types?.includes('application/x-dsh-workspace-groups') === true, `types=${JSON.stringify(dragStart.types)}`)
// React commits the drop-highlight on the next render — wait for the class.
report('dragover 目标行高亮', await waitFor(`document.querySelector('.wgCategoryRow[data-wg-category="${groupName}"]')?.classList.contains('wgDropTarget') === true`, 5000))
const dropped = await evaluate(`(() => {
const target = document.querySelector('.wgCategoryRow[data-wg-category="${groupName}"]')
if (!target?.__wgDt) return false
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: target.__wgDt }))
return true
})()`)
report('drop 事件派发', dropped === true)
// A workspace sits under a group when the group's section contains its row.
const movedUnderGroup = `(() => {
const section = document.querySelector('.wgCategoryRow[data-wg-category="${groupName}"]')?.parentElement
return !!section && !!section.querySelector('.wgProjectRow[data-wsid="${wsid}"]')
})()`
report('drop 后项目移入新分组', await waitFor(movedUnderGroup))
// ---- 4. 落盘 + 持久化 ----
await sleep(500)
const afterDrop = await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' }).then(r => r.json())
const persisted = afterDrop.manual?.assignments?.[wsid] === groupName
report('PUT 落盘:assignments 包含拖入记录', persisted)
await page.send('Page.reload')
report('刷新后分组与归类保留', await waitFor(`(() => {
const section = document.querySelector('.wgCategoryRow[data-wg-category="${groupName}"]')?.parentElement
return !!section && !!section.querySelector('.wgProjectRow[data-wsid="${wsid}"]')
})()`))
// ---- 5. 非法 PUT 被拒 ----
const bad = await fetch(`${BASE}/workspace-groups/manual`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ categories: [], assignments: { [wsid]: '幽灵分组' } }),
})
report('非法 PUT(未知分类)返回 400', bad.status === 400, `status=${bad.status}`)
// ---- 5.5 v0.3:组内排序 + 拖动时其他分组项目收起 ------------------------
const ruleKeys = snapshot.categories?.map(c => c.name) ?? []
const cat1 = ruleKeys[0]
const cat2 = ruleKeys[1]
if (cat1 === undefined || cat2 === undefined) {
report('v0.3 需两个规则分类(跳过排序/收起断言)', false, `categories=${JSON.stringify(ruleKeys)}`)
} else {
// Expand both rule categories so their project rows are visible.
const expandCat = (key) => evaluate(`(() => {
const row = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(key)}]')
if (!row) return false
if (row.getAttribute('aria-expanded') === 'false') row.click()
return true
})()`)
await expandCat(cat1)
await expandCat(cat2)
const rowsVisible = await waitFor(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
return !!s1 && !!s2 && s1.querySelectorAll('.wgProjectRow').length >= 2 && s2.querySelectorAll('.wgProjectRow').length >= 1
})()`)
report('两个规则分类展开且项目行可见', rowsVisible)
const reorder = await evaluate(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
if (!s1) return { error: 'no section' }
const rows = s1.querySelectorAll('.wgProjectRow')
const source = rows[1] // drag the second project
const target = rows[0] // drop before the first
if (!source || !target) return { error: 'rows missing' }
const dt = new DataTransfer()
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
window.__wgDt = dt // stash for the drop step (React re-renders may recreate rows)
return { wsid: source.getAttribute('data-wsid'), targetWsid: target.getAttribute('data-wsid') }
})()`)
// React commits the collapse on the next render — wait for the other
// category's project rows to disappear before dropping.
report('拖动项目时其他分组项目收起', await waitFor(`(() => {
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
return !!s2 && s2.querySelectorAll('.wgProjectRow').length === 0
})()`, 5000))
await evaluate(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
if (!s1) return false
const target = s1.querySelector('.wgProjectRow')
if (!target || !window.__wgDt) return false
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
return true
})()`)
// The user-visible contract: the dragged project now renders first in the group.
report('组内拖拽排序(第二个项目移到第一个之前)', await waitFor(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
if (!s1) return false
const first = s1.querySelector('.wgProjectRow')
return !!first && first.getAttribute('data-wsid') === ${JSON.stringify(reorder.wsid)}
})()`))
// ---- v0.4:拖到目标行下半 → 插到目标之后(指示线可见) ----
const reorderAfter = await evaluate(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
if (!s1) return { error: 'no section' }
const rows = s1.querySelectorAll('.wgProjectRow')
const source = rows[0] // currently the first project
const target = rows[1] // drop on the BOTTOM half of the second
if (!source || !target) return { error: 'rows missing' }
const dt = new DataTransfer()
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
const rect = target.getBoundingClientRect()
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientY: rect.top + rect.height - 1, dataTransfer: dt }))
window.__wgDt = dt // stash for the drop step
return { sourceWsid: source.getAttribute('data-wsid'), targetWsid: target.getAttribute('data-wsid') }
})()`)
report('拖项目悬停行下半 → 下方插入指示线', await waitFor(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
return !!s1 && !!s1.querySelector('.wgProjectRow.wgInsertAfter')
})()`, 5000))
await evaluate(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
if (!s1) return false
const target = s1.querySelector('.wgProjectRow[data-wsid="${reorderAfter.targetWsid}"]')
if (!target || !window.__wgDt) return false
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, clientY: target.getBoundingClientRect().top + target.getBoundingClientRect().height - 1, dataTransfer: window.__wgDt }))
return true
})()`)
report('项目拖到目标行下半 → 插入到目标之后', await waitFor(`(() => {
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
if (!s1) return false
const first = s1.querySelector('.wgProjectRow')
return !!first && first.getAttribute('data-wsid') === ${JSON.stringify(reorderAfter.targetWsid)}
})()`))
// ---- v0.4:分组拖动 — 下半 = 移到目标分组之后 ----
const groupDown = await evaluate(`(() => {
const source = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
if (!source || !target) return false
const dt = new DataTransfer()
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
const rect = target.getBoundingClientRect()
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientY: rect.top + rect.height - 1, dataTransfer: dt }))
window.__wgCatDt = dt
return true
})()`)
report('拖分组悬停目标行下半 → 下方插入指示线', groupDown && await waitFor(`!!document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}].wgInsertAfter')`, 5000))
await evaluate(`(() => {
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
if (!target || !window.__wgCatDt) return false
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, clientY: target.getBoundingClientRect().top + target.getBoundingClientRect().height - 1, dataTransfer: window.__wgCatDt }))
return true
})()`)
report('分组向下拖 → 移到目标分组之后', await waitFor(`fetch(${JSON.stringify(BASE)} + '/workspace-groups/config', { cache: 'no-store' }).then(r => r.json()).then(d => {
const o = d.manual?.categoryOrder ?? []
return o.indexOf(${JSON.stringify(cat2)}) > o.indexOf(${JSON.stringify(cat1)})
})`))
// ---- v0.4:分组拖动 — 上半 = 移到目标分组之前 ----
const groupUp = await evaluate(`(() => {
const source = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
if (!source || !target) return false
const dt = new DataTransfer()
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
const rect = target.getBoundingClientRect()
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientY: rect.top + 1, dataTransfer: dt }))
window.__wgCatDt = dt
return true
})()`)
report('拖分组悬停目标行上半 → 上方插入指示线', groupUp && await waitFor(`!!document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}].wgInsertBefore')`, 5000))
await evaluate(`(() => {
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
if (!target || !window.__wgCatDt) return false
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, clientY: target.getBoundingClientRect().top + 1, dataTransfer: window.__wgCatDt }))
return true
})()`)
report('分组向上拖 → 移到目标分组之前', await waitFor(`fetch(${JSON.stringify(BASE)} + '/workspace-groups/config', { cache: 'no-store' }).then(r => r.json()).then(d => {
const o = d.manual?.categoryOrder ?? []
return o.indexOf(${JSON.stringify(cat1)}) < o.indexOf(${JSON.stringify(cat2)})
})`))
// ---- v0.3:规则分类行出现菜单 → 重命名 → 删除回未分类 ------------------
const hasMenu = await evaluate(`(() => {
const row = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
if (!row) return false
row.querySelector('button[aria-label*="重命名分组"]')?.click()
return !!row.querySelector('button[aria-label*="重命名分组"]')
})()`)
report('规则分类行出现「⋯」菜单(重命名/删除入口)', hasMenu)
const renamed = `${cat1}·改`
const renameFlow = await evaluate(`(() => {
const item = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === '重命名分组')
if (!item) return false
item.click()
return true
})()`)
report('菜单点击「重命名分组」打开弹窗', renameFlow && await waitFor(`!!document.querySelector('.wgRenameInput')`, 4000))
await evaluate(`(() => {
const input = document.querySelector('.wgRenameInput')
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set
setter.call(input, ${JSON.stringify(renamed)})
input.dispatchEvent(new Event('input', { bubbles: true }))
})()`)
await evaluate(`(() => {
const btn = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === '重命名' && !b.textContent.includes('分组'))
if (btn) btn.click()
})()`)
report('重命名规则分类后以新名渲染', await waitFor(`!!document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(renamed)}]')`))
report('renamed 落盘(原规则名 → 新名)', await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' })
.then(r => r.json()).then(d => d.manual?.renamed?.[cat1] === renamed))
// Delete the renamed rule group: its projects must go to 未分类 (null).
// Capture the group's members first (expand the group if collapsed),
// then drive the delete flow.
await evaluate(`(() => {
const row = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(renamed)}]')
if (row && row.getAttribute('aria-expanded') === 'false') row.click()
return true
})()`)
const memberIds = await evaluate(`(() => {
const s = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(renamed)}]')?.parentElement
return s ? [...s.querySelectorAll('.wgProjectRow')].map(r => r.getAttribute('data-wsid')) : []
})()`)
await evaluate(`(() => {
const row = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(renamed)}]')
row?.querySelector('button[aria-label*="重命名分组"]')?.click()
return true
})()`)
await waitFor(`[...document.querySelectorAll('button')].some(b => b.textContent.trim() === '删除分组')`, 4000)
await evaluate(`(() => {
const item = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === '删除分组')
if (item) item.click()
return true
})()`)
// The confirm button lives in the delete dialog (also labelled 删除分组).
await waitFor(`(() => {
const modal = [...document.querySelectorAll('[role="dialog"]')].at(-1)
return !!modal && [...modal.querySelectorAll('button')].some(b => b.textContent.trim() === '删除分组')
})()`, 4000)
await evaluate(`(() => {
const modal = [...document.querySelectorAll('[role="dialog"]')].at(-1)
const btn = modal ? [...modal.querySelectorAll('button')].find(b => b.textContent.trim() === '删除分组') : undefined
if (btn) btn.click()
return true
})()`)
report('删除分组后分组消失', await waitFor(`!document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(renamed)}]')`))
// The uncategorized bucket first appears COLLAPSED — expand it before
// asserting its members (data is correct; rows render on expand).
await evaluate(`(() => {
const row = document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')
if (row && row.getAttribute('aria-expanded') === 'false') row.click()
return true
})()`)
// Every former member must now render inside the 未分类 section (bottom).
report('删除后成员回未分类(DOM)', await waitFor(`(() => {
const s = document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')?.parentElement
if (!s) return false
const ids = new Set([...s.querySelectorAll('.wgProjectRow')].map(r => r.getAttribute('data-wsid')))
return ${JSON.stringify(memberIds)}.every(id => ids.has(id))
})()`), `members=${JSON.stringify(memberIds)}`)
const deleted = await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' }).then(r => r.json())
const assignments = deleted.manual?.assignments ?? {}
report('删除后 hidden 落盘且引用清理', deleted.manual?.hidden?.includes(cat1) === true
&& !Object.values(assignments).includes(renamed)
&& !Object.keys(deleted.manual?.workspaceOrder ?? {}).includes(renamed)
&& !(deleted.manual?.categoryOrder ?? []).includes(renamed))
report('未分类恒为最末段', await waitFor(`(() => {
const rows = document.querySelectorAll('.wgCategoryRow')
return rows.length > 0 && rows[rows.length - 1].getAttribute('data-wg-category') === ${JSON.stringify('未分类')}
})()`))
}
// ---- 6. 现场恢复 ----
await fetch(`${BASE}/workspace-groups/manual`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(originalManual),
})
if (!overlayExistedBefore) {
// The original environment had no overlay file — remove the one we created.
await unlink(overlayPath).catch(() => {})
}
await page.send('Page.reload')
await waitFor(`!!document.querySelector('.wgRoot')`, 8000)
const cleaned = await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' }).then(r => r.json())
const backToOriginal = JSON.stringify(cleaned.manual ?? { categories: [], assignments: {} }) === JSON.stringify(originalManual)
report('现场恢复:overlay 还原为原始内容', backToOriginal)
} catch (error) {
console.error('验证脚本异常:', error)
} finally {
if (page) page.close()
if (chrome) chrome.kill('SIGKILL')
await rm(profileDir, { recursive: true, force: true })
}
const failed = results.filter(r => !r.ok)
console.log(`\n结果: ${results.length - failed.length}/${results.length} 通过`)
return failed.length === 0 ? 0 : 1
}
process.exit(await main())

View File

@ -1,35 +1,66 @@
/**
* The workspace-groups browsing region filling the sidebar shell's
* `sidebar.workspaces` hole: section header (title + right-aligned search +
* add workspace), the three-level tree (category → workspace → session),
* and the workspace/session dialogs. Wide state renders the full browser;
* rail state renders the two region icons (search / add workspace) as 36px
* controls on the shell's shared rail entry path, each requesting expansion
* through the owner share.
* new-group + add workspace), the three-level tree (category → workspace →
* session), group management dialogs, and the workspace/session dialogs. Wide
* state renders the full browser; rail state renders the two region icons
* (search / add workspace) as 36px controls on the shell's shared rail entry
* path, each requesting expansion through the owner share.
*
* Data: workspaces/sessions via the framework global hooks; grouping config
* via the host half's `/workspace-groups/config` route (refetched on mount).
* Runtime group management (create/rename/delete any group, drag workspaces
* between groups and into position, drag groups into position) persists
* through `PUT /workspace-groups/manual`; the sidecar YAML is never rewritten
* (rule-group rename/delete ride the overlay `renamed`/`hidden` maps).
*/
import { useEffect, useMemo, useRef, useState } from 'react'
import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'
import {
Button,
IconCloseFill14,
IconFolderOpenOutline16,
IconProjectAddOutline16,
IconSearchOutline16,
Modal,
Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { SessionId, SessionListState, SessionSearchResultItem, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client'
import { classify } from '../core/matcher.ts'
import type { GroupsConfig } from '../core/types.ts'
import {
displayCategoryKeys,
moveAfter,
moveBefore,
originalRuleNameForDisplay,
resolveCategory,
takenCategoryNames,
} from '../core/matcher.ts'
import { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'
import type { GroupsBrowserProps } from './contract.ts'
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, type CategoryNode } from './tree.ts'
import { CategoryRow, SessionRow, WorkspaceRow } from './rows.tsx'
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, UNCATEGORIZED_KEY, type CategoryNode } from './tree.ts'
import { CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, SessionRow, WorkspaceRow } from './rows.tsx'
import css from './styles.css?inline'
const SEARCH_DEBOUNCE_MS = 250
const SEARCH_QUERY_MAX_CODE_UNITS = 500
/** Overlay with every optional field materialized (plain-object edits, no undefined spreads). */
type NormalizedManual = Required<ManualGroups>
const EMPTY_MANUAL: NormalizedManual = {
categories: [], assignments: {}, categoryOrder: [], workspaceOrder: {}, renamed: {}, hidden: [],
}
/** Materialize optional overlay fields so every update is a plain object edit. */
function normalizeManual(manual: ManualGroups): NormalizedManual {
return {
categories: manual.categories,
assignments: manual.assignments,
categoryOrder: manual.categoryOrder ?? [],
workspaceOrder: manual.workspaceOrder ?? {},
renamed: manual.renamed ?? {},
hidden: manual.hidden ?? [],
}
}
function sanitizeSearchQuery(value: string): string {
const withoutNul = value.replaceAll('\0', '')
if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul
@ -48,14 +79,57 @@ interface RemoteSearchState {
hasMore: boolean
}
/** Minimal fetch of the grouping config (host route; no-cache revalidation). */
async function fetchGroupsConfig(): Promise<GroupsConfig> {
/** Light runtime guard for the manual overlay attached to the config fetch. */
function isManualGroups(value: unknown): value is ManualGroups {
if (typeof value !== 'object' || value === null) return false
const candidate = value as { categories?: unknown; assignments?: unknown }
return Array.isArray(candidate.categories) && typeof candidate.assignments === 'object' && candidate.assignments !== null
}
/** Minimal fetch of the grouping config + runtime overlay (no-cache revalidation). */
async function fetchGroupsConfig(): Promise<{ config: GroupsConfig; manual: NormalizedManual }> {
const response = await fetch('/workspace-groups/config', { cache: 'no-cache' })
if (!response.ok) throw new Error(`config request failed: ${response.status}`)
const body = (await response.json()) as GroupsConfig
return Array.isArray(body.categories) ? body : { categories: [] }
const config: GroupsConfig = Array.isArray(body.categories) ? body : { categories: [] }
return { config, manual: isManualGroups(body.manual) ? normalizeManual(body.manual) : EMPTY_MANUAL }
}
/** Persist the whole runtime overlay (idempotent; the host validates + writes). */
async function saveManualOverlay(manual: ManualGroups): Promise<void> {
const response = await fetch('/workspace-groups/manual', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(manual),
})
if (!response.ok) {
let message = `manual save failed: ${response.status}`
try {
const text = await response.text()
if (text !== '') message = text
} catch { /* keep the fallback message */ }
throw new Error(message)
}
}
/** One group-management dialog state: create, or rename an existing group. */
type GroupDialogState = { mode: 'create' } | { mode: 'rename'; from: string } | null
/** Row reference used by drop targets: which kind of row, which key. */
export type DropRowRef = { kind: 'category' | 'workspace'; key: string }
/**
* Current drop indicator. A `line` renders a 2px insertion line above/below a
* row (project reorder inside a group, or group reorder); an `into` renders
* the whole-row highlight used when dropping a project into a group. Drop
* handlers re-derive before/after from the drop event itself, so the
* indicator is purely visual and can never go stale.
*/
export type DragIndicator =
| { mode: 'line'; row: DropRowRef; before: boolean }
| { mode: 'into'; categoryKey: string }
| null
/**
* Render the browsing region.
* @param props - composed slot props (shell owner share + store + injected actions).
@ -92,17 +166,25 @@ export function GroupsBrowser({
return () => { style.remove() }
}, [])
// Grouping config from the host route.
// Grouping config from the host route + the runtime manual overlay.
const [config, setConfig] = useState<GroupsConfig>({ categories: [] })
const [manual, setManual] = useState<NormalizedManual>(EMPTY_MANUAL)
const [configError, setConfigError] = useState<string | null>(null)
const reloadConfig = () => {
setConfigError(null)
fetchGroupsConfig().then(setConfig).catch((reason: unknown) => {
fetchGroupsConfig().then(({ config: nextConfig, manual: nextManual }) => {
setConfig(nextConfig)
setManual(nextManual)
}).catch((reason: unknown) => {
setConfigError(reason instanceof Error ? reason.message : String(reason))
})
}
useEffect(() => { reloadConfig() }, [])
// Transient save errors for drag/menu group operations (dialog errors are local).
const [manualError, setManualError] = useState<string | null>(null)
const [manualSaving, setManualSaving] = useState(false)
const workspaces = useWorkspaces(state => state.items)
const workspacePhase = useWorkspaces(state => state.phase)
const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds)
@ -122,23 +204,23 @@ export function GroupsBrowser({
// every store change (the reported "cannot collapse" bug).
useEffect(() => {
if (current === undefined || currentWorkspaceKey === undefined) return
const category = categoriesForCurrent(config, workspaces, current)
const category = categoriesForCurrent(config, workspaces, current, manual)
if (category !== undefined && !Object.hasOwn(categoryExpansion, category)) {
actions.setCategoryExpanded(category, true)
}
if (!Object.hasOwn(workspaceExpansion, currentWorkspaceKey)) {
actions.setWorkspaceExpanded(currentWorkspaceKey, true)
}
}, [current, currentWorkspaceKey, config, workspaces, categoryExpansion, workspaceExpansion, actions])
}, [current, currentWorkspaceKey, config, workspaces, manual, categoryExpansion, workspaceExpansion, actions])
// Drop expansion keys that no longer exist (config edits / workspace deletion).
// Drop expansion keys that no longer exist (group edits / workspace deletion).
useEffect(() => {
if (workspacePhase !== 'ready') return
actions.retainKeys(
config.categories.map(c => c.name),
displayCategoryKeys(config, manual),
workspaces.map(w => w.workspaceId as string),
)
}, [actions, config, workspacePhase, workspaces])
}, [actions, config, manual, workspacePhase, workspaces])
const [query, setQuery] = useState('')
const [searchExpanded, setSearchExpanded] = useState(false)
@ -197,8 +279,8 @@ export function GroupsBrowser({
() => deriveGroups(list, workspaces, archivedSessionIds, config, {
expandedCategories,
expandedWorkspaces,
}),
[list, workspaces, archivedSessionIds, config, expandedCategories, expandedWorkspaces],
}, manual),
[list, workspaces, archivedSessionIds, config, manual, expandedCategories, expandedWorkspaces],
)
// Add workspace flow: self-contained (no directory-flow hole dependency).
@ -295,6 +377,274 @@ export function GroupsBrowser({
})
}
// ---- Runtime group management ----------------------------------------------
const [groupDialog, setGroupDialog] = useState<GroupDialogState>(null)
const [groupDraft, setGroupDraft] = useState('')
const [groupError, setGroupError] = useState<string | null>(null)
const [groupBusy, setGroupBusy] = useState(false)
const [groupDeleteTarget, setGroupDeleteTarget] = useState<string | null>(null)
const [groupDeleting, setGroupDeleting] = useState(false)
const [groupDeleteError, setGroupDeleteError] = useState<string | null>(null)
const takenNames = useMemo(() => takenCategoryNames(config, manual), [config, manual])
const groupTrimmed = groupDraft.trim()
const groupNameIssue = groupDialog !== null && groupTrimmed !== ''
? (groupTrimmed === UNCATEGORIZED_LABEL
? t('group.nameReserved')
: (groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)
? null
: takenNames.has(groupTrimmed) ? t('group.nameDuplicate') : null)
: null
const groupBlocked = groupBusy || groupTrimmed === '' || groupNameIssue !== null
|| (groupDialog !== null && groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)
const confirmGroupDialog = () => {
if (groupBlocked || groupDialog === null) return
const name = groupTrimmed
const from = groupDialog.mode === 'rename' ? groupDialog.from : undefined
const renaming = groupDialog.mode === 'rename' && from !== name
let next: NormalizedManual
if (groupDialog.mode === 'create') {
next = { ...manual, categories: [...manual.categories, name] }
} else {
// Rename: rule groups ride the `renamed` map, manual groups the list;
// every reference (assignments / workspaceOrder / categoryOrder) follows.
const originalRule = from !== undefined ? originalRuleNameForDisplay(config.categories, manual, from) : undefined
next = {
...manual,
...(originalRule !== undefined
? { renamed: { ...manual.renamed, [originalRule]: name } }
: { categories: manual.categories.map(c => c === from ? name : c) }),
assignments: Object.fromEntries(
Object.entries(manual.assignments).map(([id, category]): [string, string | null] => [id, category === from ? name : category]),
),
workspaceOrder: Object.fromEntries(
Object.entries(manual.workspaceOrder).map(([key, ids]): [string, string[]] => [key === from ? name : key, ids]),
),
categoryOrder: manual.categoryOrder.map(key => key === from ? name : key),
}
}
setGroupBusy(true)
setGroupError(null)
saveManualOverlay(next).then(() => {
setManual(next)
setManualError(null)
setGroupBusy(false)
setGroupDialog(null)
setGroupDraft('')
// Keep the renamed group open (its old expansion key is dropped by retainKeys).
if (renaming) actions.setCategoryExpanded(name, true)
}).catch((reason: unknown) => {
setGroupBusy(false)
setGroupError(reason instanceof Error ? reason.message : String(reason))
})
}
const confirmGroupDelete = () => {
if (groupDeleting || groupDeleteTarget === null) return
const name = groupDeleteTarget
const originalRule = originalRuleNameForDisplay(config.categories, manual, name)
// Every project currently in the group goes to 未分类 (forced, not rule-
// reclassified), regardless of how it landed there.
const assignments = { ...manual.assignments }
for (const workspace of workspaces) {
if (resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) === name) {
assignments[workspace.workspaceId] = null
}
}
const workspaceOrder = Object.fromEntries(
Object.entries(manual.workspaceOrder).filter(([key]) => key !== name),
)
const next: NormalizedManual = {
...manual,
assignments,
workspaceOrder,
categoryOrder: manual.categoryOrder.filter(key => key !== name),
...(originalRule !== undefined
? {
renamed: Object.fromEntries(Object.entries(manual.renamed).filter(([key]) => key !== originalRule)),
hidden: [...manual.hidden, originalRule],
}
: { categories: manual.categories.filter(c => c !== name) }),
}
setGroupDeleting(true)
setGroupDeleteError(null)
saveManualOverlay(next).then(() => {
setManual(next)
setManualError(null)
setGroupDeleting(false)
setGroupDeleteTarget(null)
}).catch((reason: unknown) => {
setGroupDeleting(false)
setGroupDeleteError(reason instanceof Error ? reason.message : String(reason))
})
}
// ---- Drag & drop (move/reorder workspaces, reorder groups) ------------------
const [dragIndicator, setDragIndicator] = useState<DragIndicator>(null)
// Cancel any stale indicator when a drag ends outside a row (or is aborted).
useEffect(() => {
const clear = () => setDragIndicator(null)
document.addEventListener('dragend', clear)
return () => { document.removeEventListener('dragend', clear) }
}, [])
/** Move a workspace into a category (or reorder inside it when `beforeWorkspaceId`/`afterWorkspaceId`). */
const moveWorkspaceTo = async (workspaceId: string, categoryKey: string, beforeWorkspaceId?: string, afterWorkspaceId?: string): Promise<void> => {
if (manualSaving) return
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) return
setManualSaving(true)
try {
let next: NormalizedManual
if (categoryKey === UNCATEGORIZED_KEY) {
// Drop on 未分类: force uncategorized and drop from every order list.
const assignments = { ...manual.assignments, [workspaceId]: null }
const workspaceOrder = Object.fromEntries(
Object.entries(manual.workspaceOrder).map(([key, ids]) => [key, ids.filter(id => id !== workspaceId)]),
)
next = { ...manual, assignments, workspaceOrder }
} else {
const currentKey = resolveCategory(config, manual, workspaceId, workspace.path, workspace.title)
const movingAcross = currentKey !== categoryKey
const assignments = movingAcross
? { ...manual.assignments, [workspaceId]: categoryKey }
: manual.assignments
const targetOrder = afterWorkspaceId !== undefined
? moveAfter(manual.workspaceOrder[categoryKey] ?? [], workspaceId, afterWorkspaceId)
: moveBefore(manual.workspaceOrder[categoryKey] ?? [], workspaceId, beforeWorkspaceId)
const workspaceOrder = { ...manual.workspaceOrder, [categoryKey]: targetOrder }
if (movingAcross && currentKey !== undefined && workspaceOrder[currentKey] !== undefined) {
workspaceOrder[currentKey] = workspaceOrder[currentKey]!.filter(id => id !== workspaceId)
}
next = { ...manual, assignments, workspaceOrder }
}
await saveManualOverlay(next)
setManual(next)
setManualError(null)
if (categoryKey !== UNCATEGORIZED_KEY) actions.setCategoryExpanded(categoryKey, true)
} catch (reason) {
setManualError(reason instanceof Error ? reason.message : String(reason))
} finally {
setManualSaving(false)
}
}
/** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (未分类 target = append). */
const moveCategory = async (draggedKey: string, beforeKey?: string, afterKey?: string): Promise<void> => {
if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return
setManualSaving(true)
try {
const order = displayCategoryKeys(config, manual)
const categoryOrder = afterKey !== undefined
? moveAfter(order, draggedKey, afterKey)
: moveBefore(order, draggedKey, beforeKey)
const next: NormalizedManual = { ...manual, categoryOrder }
await saveManualOverlay(next)
setManual(next)
setManualError(null)
} catch (reason) {
setManualError(reason instanceof Error ? reason.message : String(reason))
} finally {
setManualSaving(false)
}
}
/**
* 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
* the indicator the user last saw — even when dragover and drop arrive in
* the same tick.
*/
const onDropRow = (categoryKey: string, row: DropRowRef) => (event: DragEvent): void => {
event.preventDefault()
setDragIndicator(null)
const draggedCategory = event.dataTransfer.getData(DND_CATEGORY_TYPE)
if (draggedCategory !== '') {
// Group reorder: only category rows are targets (project rows fold
// during group drags); before/after follows the drop position.
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
const before = event.clientY < rect.top + rect.height / 2
const beforeKey = row.kind === 'category' && before ? row.key : undefined
const afterKey = row.kind === 'category' && !before ? row.key : undefined
void moveCategory(draggedCategory, beforeKey, afterKey)
return
}
const workspaceId = event.dataTransfer.getData(DND_WORKSPACE_TYPE) || event.dataTransfer.getData('text/plain')
if (workspaceId === '') return
// Project move/reorder: a line on a project row = reorder before/after it;
// dropping anywhere else in a category = move into the group (its end).
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
const before = event.clientY < rect.top + rect.height / 2
const beforeWsid = row.kind === 'workspace' && before ? row.key : undefined
const afterWsid = row.kind === 'workspace' && !before ? row.key : undefined
void moveWorkspaceTo(workspaceId, categoryKey, beforeWsid, afterWsid)
}
const onDragOverRow = (row: DropRowRef) => (event: DragEvent): void => {
if (!hasPluginDragType(event.dataTransfer.types)) return
const draggingCategory = Array.from(event.dataTransfer.types as Iterable<string>).includes(DND_CATEGORY_TYPE)
if (draggingCategory && row.kind !== 'category') return // group drags target category rows only
event.preventDefault()
event.dataTransfer.dropEffect = 'move'
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
const before = event.clientY < rect.top + rect.height / 2
if (draggingCategory || row.kind === 'workspace') {
// Group reorder (line on a category row) or project reorder inside a
// group (line on a project row).
setDragIndicator(prev =>
prev?.mode === 'line' && prev.row.kind === row.kind && prev.row.key === row.key && prev.before === before
? prev
: { mode: 'line', row, before })
} else {
// Dropping a project INTO a group: whole-row highlight.
setDragIndicator(prev =>
prev?.mode === 'into' && prev.categoryKey === row.key ? prev : { mode: 'into', categoryKey: row.key })
}
}
const onDragLeaveRow = (event: DragEvent): void => {
if (event.currentTarget.contains(event.relatedTarget as Node | null)) return
setDragIndicator(null)
}
// While dragging a project, everything else folds: other categories collapse
// (project rows render only inside expanded categories), and every session
// expansion collapses — the source category stays open so dropping on a
// sibling row can reorder inside it.
const onDragStartWorkspace = (workspaceId: string) => (): void => {
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
const sourceKey = workspace === undefined
? undefined
: resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
for (const key of Object.keys(categoryExpansion)) {
if (!categoryExpansion[key]) continue
if (sourceKey !== undefined && key === sourceKey) continue
actions.setCategoryExpanded(key, false)
}
for (const key of Object.keys(workspaceExpansion)) {
if (workspaceExpansion[key]) actions.setWorkspaceExpanded(key, false)
}
}
// While dragging a group, every group folds (their rows stay visible as
// reorder targets).
const onDragStartCategory = (categoryKey: string) => (event: DragEvent): void => {
event.dataTransfer.setData(DND_CATEGORY_TYPE, categoryKey)
event.dataTransfer.effectAllowed = 'move'
for (const key of Object.keys(categoryExpansion)) {
if (categoryExpansion[key]) actions.setCategoryExpanded(key, false)
}
}
const now = Date.now()
return (
@ -344,6 +694,20 @@ export function GroupsBrowser({
)}
</div>
)}
<Tooltip label={t('group.create')} side="bottom" delayMs={500}>
<button
type="button"
className="wgIconButton"
aria-label={t('group.create')}
onClick={() => {
setGroupDraft('')
setGroupError(null)
setGroupDialog({ mode: 'create' })
}}
>
<IconFolderOpenOutline16 size={wide ? 16 : 18} />
</button>
</Tooltip>
<Tooltip label={t('workspace.add')} side="bottom" delayMs={500}>
<button
type="button"
@ -376,6 +740,9 @@ export function GroupsBrowser({
{configError !== null && (
<div className="wgSearchStatus" role="status">{t('configUnavailable')}</div>
)}
{manualError !== null && (
<div className="wgSearchStatus wgManualError" role="alert">{t('manual.saveError')}: {manualError}</div>
)}
{wide && normalizedQuery !== '' ? (
<SearchBody
list={list}
@ -388,6 +755,7 @@ export function GroupsBrowser({
current={current}
now={now}
open={open}
manual={manual}
t={t}
/>
) : (
@ -402,6 +770,13 @@ export function GroupsBrowser({
current={current}
now={now}
t={t}
manageable={category.key !== UNCATEGORIZED_KEY}
dragIndicator={dragIndicator}
onDragOverRow={onDragOverRow}
onDragLeaveRow={onDragLeaveRow}
onDropRow={onDropRow}
{...(category.key === UNCATEGORIZED_KEY ? {} : { onDragStartCategory: onDragStartCategory(category.key) })}
onDragStartWorkspace={onDragStartWorkspace}
onToggleCategory={() => { actions.setCategoryExpanded(category.key, !category.expanded) }}
onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}
onNewSession={startSession}
@ -418,12 +793,68 @@ export function GroupsBrowser({
onSessionRename={onSessionRename}
onSessionArchive={onSessionArchive}
onFork={forkSession}
onGroupRename={() => {
setGroupDraft(category.key)
setGroupError(null)
setGroupDialog({ mode: 'rename', from: category.key })
}}
onGroupDelete={() => {
setGroupDeleteTarget(category.key)
setGroupDeleteError(null)
}}
onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}
hasOverride={(workspaceId) => Object.hasOwn(manual.assignments, workspaceId)}
/>
))}
</div>
)}
</div>
{/* Group create / rename dialog */}
<Modal
open={groupDialog !== null}
onClose={() => { setGroupDialog(null) }}
closeLabel={t('close')}
title={groupDialog?.mode === 'rename' ? t('group.renameTitle') : t('group.createTitle')}
footer={(
<>
<Button variant="outline" onClick={() => { setGroupDialog(null) }}>{t('group.createCancel')}</Button>
<Button variant="primary" disabled={groupBlocked} onClick={confirmGroupDialog}>
{groupDialog?.mode === 'rename' ? t('group.renameConfirm') : t('group.createConfirm')}
</Button>
</>
)}
>
<input
className="wgRenameInput"
value={groupDraft}
aria-label={t('group.createPlaceholder')}
placeholder={t('group.createPlaceholder')}
autoFocus
onChange={(e) => { setGroupDraft(e.target.value); setGroupError(null) }}
onKeyDown={(e) => { if (e.key === 'Enter') confirmGroupDialog() }}
/>
{groupNameIssue !== null && <div className="wgAddError" role="alert">{groupNameIssue}</div>}
{groupError !== null && <div className="wgAddError" role="alert">{groupError}</div>}
</Modal>
{/* Group delete dialog */}
<Modal
open={groupDeleteTarget !== null}
onClose={() => { setGroupDeleteTarget(null) }}
closeLabel={t('close')}
title={t('group.deleteTitle')}
footer={(
<>
<Button variant="outline" onClick={() => { setGroupDeleteTarget(null) }}>{t('group.deleteCancel')}</Button>
<Button variant="outline" disabled={groupDeleting} onClick={confirmGroupDelete}>{t('group.delete')}</Button>
</>
)}
>
<div className="wgAddError">{t('group.deleteConfirm')}</div>
{groupDeleteError !== null && <div className="wgAddError" role="alert">{groupDeleteError}</div>}
</Modal>
{/* Workspace rename dialog */}
<Modal
open={renameTarget !== null}
@ -513,18 +944,28 @@ function categoriesForCurrent(
config: GroupsConfig,
workspaces: readonly WorkspaceView[],
current: SessionId,
manual: ManualGroups,
): string | undefined {
const workspace = workspaces.find(w => w.sessionIds.includes(current))
if (workspace === undefined) return undefined
return classify(config.categories, workspace.path, workspace.title)?.name
return resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
}
/** One category section: header row + expanded workspace folders. */
function CategorySection({ category, current, now, t, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork }: {
function CategorySection({ category, current, now, t, manageable, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onMoveOut, hasOverride }: {
category: CategoryNode
current: SessionId | undefined
now: number
t: GroupsBrowserProps['t']
/** Rename/delete menu + group reorder source (false for the uncategorized bucket). */
manageable: boolean
dragIndicator: DragIndicator
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). */
onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void
onDragStartCategory?: (event: DragEvent) => void
onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void
onToggleCategory: () => void
onToggleWorkspace: (key: string) => void
onNewSession: (workspaceId?: WorkspaceId) => void
@ -534,10 +975,28 @@ function CategorySection({ category, current, now, t, onToggleCategory, onToggle
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
onSessionArchive: (sessionId: SessionId) => void
onFork: (sessionId: SessionId) => void
onGroupRename: () => void
onGroupDelete: () => void
onMoveOut: (workspaceId: WorkspaceId) => void
hasOverride: (workspaceId: WorkspaceId) => boolean
}) {
const categoryLine = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'category' && dragIndicator.row.key === category.key
? (dragIndicator.before ? 'before' : 'after')
: undefined
const categoryInto = dragIndicator?.mode === 'into' && dragIndicator.categoryKey === category.key
return (
<div role="group">
<CategoryRow node={category} t={t} onToggle={onToggleCategory} />
<CategoryRow
node={category}
t={t}
onToggle={onToggleCategory}
{...(manageable ? { onRename: onGroupRename, onDelete: onGroupDelete, onDragStartCategory } : {})}
dropActive={categoryInto}
{...(categoryLine !== undefined ? { insertLine: categoryLine } : {})}
onRowDragOver={onDragOverRow({ kind: 'category', key: category.key })}
onRowDragLeave={onDragLeaveRow}
onRowDrop={onDropRow(category.key, { kind: 'category', key: category.key })}
/>
{category.expanded && (
<div role="group">
{category.workspaces.map((workspace) => (
@ -549,6 +1008,16 @@ function CategorySection({ category, current, now, t, onToggleCategory, onToggle
onNewSession={() => { onNewSession(workspace.workspaceId) }}
onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}
onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}
hasOverride={hasOverride(workspace.workspaceId)}
onMoveOut={() => { onMoveOut(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 && workspace.sessions.map((session) => (
<SessionRow
@ -576,7 +1045,7 @@ function CategorySection({ category, current, now, t, onToggleCategory, onToggle
* 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as
* the idle tree, so search keeps the same folder hierarchy the user is used to.
*/
function SearchBody({ list, workspaces, config, archivedSessionIds, query, remote, resultLimit, current, now, open, t }: {
function SearchBody({ list, workspaces, config, archivedSessionIds, query, remote, resultLimit, current, now, open, manual, t }: {
list: SessionListState
workspaces: readonly WorkspaceView[]
config: GroupsConfig
@ -587,6 +1056,7 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, query, remot
current: SessionId | undefined
now: number
open: (sessionId: SessionId) => void
manual: ManualGroups
t: GroupsBrowserProps['t']
}) {
const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }
@ -595,8 +1065,8 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, query, remot
[list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],
)
const groups = useMemo(
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, matches.snippetsBySession),
[list, workspaces, config, matches, archivedSessionIds],
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession),
[list, workspaces, config, matches, archivedSessionIds, manual],
)
const pending = currentRemote.status === 'loading'
const failed = currentRemote.status === 'error'

View File

@ -31,6 +31,22 @@ export type WorkspaceGroupsKey =
| 'workspace.renamePlaceholder'
| 'workspace.renameConfirm'
| 'workspace.renameCancel'
| 'workspace.moveToUncategorized'
| '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'
| 'manual.saveError'
| 'session.new'
| 'session.rename'
| 'session.archive'
@ -81,6 +97,22 @@ export const zh: WorkspaceGroupsDict = {
'workspace.renamePlaceholder': '工作区名称',
'workspace.renameConfirm': '重命名',
'workspace.renameCancel': '取消',
'workspace.moveToUncategorized': '移到未分类',
'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': '该名称不可用',
'manual.saveError': '分组变更保存失败',
'session.new': '新建会话',
'session.rename': '重命名会话',
'session.archive': '归档',
@ -130,6 +162,22 @@ export const en: WorkspaceGroupsDict = {
'workspace.renamePlaceholder': 'Workspace name',
'workspace.renameConfirm': 'Rename',
'workspace.renameCancel': 'Cancel',
'workspace.moveToUncategorized': 'Move to Uncategorized',
'group.create': 'New group',
'group.createTitle': 'New group',
'group.createPlaceholder': 'Group name',
'group.createConfirm': 'Create',
'group.createCancel': 'Cancel',
'group.rename': 'Rename group',
'group.renameTitle': 'Rename group',
'group.renameConfirm': 'Rename',
'group.delete': 'Delete group',
'group.deleteTitle': 'Delete group',
'group.deleteConfirm': 'Deleting removes this group; every project inside it returns to Uncategorized. Delete?',
'group.deleteCancel': 'Cancel delete',
'group.nameDuplicate': 'A group with this name already exists',
'group.nameReserved': 'This name is not available',
'manual.saveError': 'Could not save group changes',
'session.new': 'New Session',
'session.rename': 'Rename session',
'session.archive': 'Archive',

View File

@ -3,8 +3,12 @@
* consume only React, primitives (StateDot/Menu/icons), and the shared CSS
* string. Each row owns its hover actions menu; dialogs live in the browser
* root so they survive row unmounts during collapse.
*
* Drag & drop: workspace rows are draggable sources; category rows (and
* 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 } from 'react'
import { useState, type DragEvent } from 'react'
import {
IconArchiveOutline20,
IconBranchOutline16,
@ -12,6 +16,7 @@ import {
IconEllipsisOutline16,
IconFolderClose16,
IconFolderOpen16,
IconFolderOpenOutline16,
IconPlusOutline16,
IconTriangleRightFill14,
IconTrashOutline16,
@ -25,6 +30,17 @@ import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts'
type T = TranslateNS<'workspaceGroups'>
/** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */
export const DND_WORKSPACE_TYPE = 'application/x-dsh-workspace-groups'
/** dataTransfer type carrying the dragged category key (group reorder). */
export const DND_CATEGORY_TYPE = 'application/x-dsh-workspace-groups-category'
/** Whether a drag carries any of the plugin's payloads (drop targets accept both). */
export function hasPluginDragType(types: DOMStringList | readonly string[]): boolean {
const list = Array.from(types as Iterable<string>)
return list.includes(DND_WORKSPACE_TYPE) || list.includes(DND_CATEGORY_TYPE)
}
/** Pending interaction status → primitives StateDot state. */
function pendingState(status: SessionNode['pendingInteraction']): StateDotState | undefined {
switch (status) {
@ -58,20 +74,51 @@ export function relativeTimeLabel(updatedAt: number, now: number): string {
return `${Math.floor(diff / (365 * DAY))}y`
}
/** One category folder row. */
export function CategoryRow({ node, t, onToggle }: {
/** Drop-target props shared by category and workspace rows (all optional). */
export interface RowDropProps {
/** Row is under the dragged workspace — show the drop highlight. */
dropActive?: boolean
/** Insertion indicator: a line above (before) or below (after) this row. */
insertLine?: 'before' | 'after'
/** Accept a drag over this row (must preventDefault to allow the drop). */
onRowDragOver?: (event: DragEvent) => void
/** Clear the highlight when the pointer leaves the row. */
onRowDragLeave?: (event: DragEvent) => void
/** Drop a workspace onto this row. */
onRowDrop?: (event: DragEvent) => void
}
/**
* 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 }: {
node: CategoryNode
t: T
onToggle: () => void
}) {
/** Rename/delete actions; the hover menu renders only when both provided. */
onRename?: () => void
onDelete?: () => 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
return (
<div
className="wgCategoryRow"
className={`wgCategoryRow${dropActive ? ' wgDropTarget' : ''}${insertLine === 'before' ? ' wgInsertBefore' : insertLine === 'after' ? ' wgInsertAfter' : ''}`}
role="treeitem"
aria-expanded={node.expanded}
aria-label={t('section.workspaces')}
data-wg-category={node.key}
draggable={onDragStartCategory !== undefined}
onClick={onToggle}
onDragStart={onDragStartCategory}
onDragOver={onRowDragOver}
onDragLeave={onRowDragLeave}
onDrop={onRowDrop}
>
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
<IconTriangleRightFill14 />
@ -81,30 +128,79 @@ export function CategoryRow({ node, t, onToggle }: {
</span>
<span className="wgCategoryLabel">{node.label}</span>
<span className="wgCategoryCount">{count}</span>
{manageable && (
<span className="wgRowActions">
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={[
{ id: 'rename', label: t('group.rename'), icon: <IconEditOutline16 /> },
{ id: 'delete', label: t('group.delete'), icon: <IconTrashOutline16 />, danger: true },
]}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'rename') onRename()
if (id === 'delete') onDelete()
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('group.rename')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutline16 />
</button>
)}
/>
</span>
)}
</div>
)
}
/** One workspace folder row inside a category. */
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete }: {
/** One workspace folder row inside a category: draggable source + drop target. */
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, hasOverride = false, onMoveOut, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
node: WorkspaceGroupNode
t: T
onToggle: () => void
onNewSession: () => void
onRename: () => void
onDelete: () => void
}) {
/** Workspace has a manual group override — offer "move to uncategorized". */
hasOverride?: boolean
onMoveOut?: () => void
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
onDragStartExtra?: () => void
} & RowDropProps) {
const [menuOpen, setMenuOpen] = useState(false)
const menuItems = [
...(hasOverride && onMoveOut !== undefined
? [{ id: 'moveOut', label: t('workspace.moveToUncategorized'), icon: <IconFolderOpenOutline16 size={16} /> }]
: []),
{ id: 'rename', label: t('workspace.rename'), icon: <IconEditOutline16 /> },
{ id: 'delete', label: t('workspace.delete'), icon: <IconTrashOutline16 />, danger: true },
]
const onDragStart = (event: DragEvent): void => {
event.dataTransfer.setData(DND_WORKSPACE_TYPE, node.workspaceId)
event.dataTransfer.effectAllowed = 'move'
onDragStartExtra?.()
}
return (
<div
className={`wgProjectRow${node.containsCurrent ? ' wgProjectActive' : ''}`}
className={`wgProjectRow${node.containsCurrent ? ' wgProjectActive' : ''}${dropActive ? ' wgDropTarget' : ''}${insertLine === 'before' ? ' wgInsertBefore' : insertLine === 'after' ? ' wgInsertAfter' : ''}`}
role="treeitem"
aria-expanded={node.expanded}
data-wsid={node.workspaceId}
draggable
onClick={onToggle}
onDragStart={onDragStart}
onDragOver={onRowDragOver}
onDragLeave={onRowDragLeave}
onDrop={onRowDrop}
>
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
<IconTriangleRightFill14 />
@ -120,6 +216,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'moveOut') onMoveOut?.()
if (id === 'rename') onRename()
if (id === 'delete') onDelete()
}}
@ -129,6 +226,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('workspace.rename')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
@ -139,6 +237,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('session.new')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); onNewSession() }}
>

View File

@ -110,12 +110,51 @@
border-radius: 6px;
cursor: pointer;
user-select: none;
position: relative;
}
.wgCategoryRow:hover {
background: var(--dsw-bg-hover, rgba(127, 127, 127, 0.12));
}
/* Manual-group menu on category rows appears on hover (like workspace rows). */
.wgCategoryRow:hover .wgRowActions,
.wgCategoryRow:focus-within .wgRowActions {
opacity: 1;
}
/* Active drag-over drop target: a workspace may be dropped into this group. */
.wgDropTarget {
background: var(--dsw-bg-selected, rgba(74, 144, 217, 0.18));
outline: 1px dashed var(--dsw-accent, #4a90d9);
outline-offset: -1px;
}
/* Insertion indicator while dragging: a 2px line above (before) or below
(after) the row — the exact spot the dragged project/group will land.
Top half of the row = before, bottom half = after. */
.wgInsertBefore::before,
.wgInsertAfter::after {
content: '';
position: absolute;
left: 2px;
right: 2px;
height: 2px;
border-radius: 1px;
background: var(--dsw-accent, #4a90d9);
box-shadow: 0 0 0 1px color-mix(in srgb, var(--dsw-accent, #4a90d9) 25%, transparent);
pointer-events: none;
z-index: 6;
}
.wgInsertBefore::before {
top: -1px;
}
.wgInsertAfter::after {
bottom: -1px;
}
.wgChevron {
display: inline-flex;
align-items: center;
@ -166,6 +205,7 @@
border-radius: 6px;
cursor: pointer;
user-select: none;
position: relative;
}
.wgProjectRow:hover {
@ -284,6 +324,13 @@
text-align: center;
}
/* Transient save errors for group operations (drag / menu). */
.wgManualError {
color: var(--dsw-fg-1, inherit);
text-align: left;
word-break: break-word;
}
.wgRail {
display: flex;
flex-direction: column;

View File

@ -15,8 +15,8 @@ import {
type WorkspaceId,
type WorkspaceView,
} from '@deepseek-ai/dsh-client-runtime/client'
import { classify } from '../core/matcher.ts'
import { UNCATEGORIZED_LABEL, type GroupsConfig } from '../core/types.ts'
import { effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'
import { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'
/** One top-level session row inside a workspace folder. */
export interface SessionNode {
@ -135,9 +135,13 @@ function workspaceSessions(
* @param list - sessions list snapshot (`current` feeds containsCurrent).
* @param workspaces - real workspaces in stable Host order.
* @param archivedSessionIds - registry-global archive set.
* @param config - sidecar grouping config.
* @param config - sidecar grouping config (rule categories).
* @param view - local expansion arrays.
* @returns category sections in render order (configured categories first, uncategorized last).
* @param manual - runtime overlay (manual groups + overrides). A workspace's
* manual override wins over rule classification; removing it reverts to rules.
* @returns category sections in render order (rule categories first, then
* manual-only ones, uncategorized last). Manual groups render even while
* empty; empty rule buckets stay hidden.
*/
export function deriveGroups(
list: SessionListState,
@ -145,37 +149,51 @@ export function deriveGroups(
archivedSessionIds: readonly SessionId[],
config: GroupsConfig,
view: GroupsTreeView,
manual: ManualGroups,
): CategoryNode[] {
const archived = new Set(archivedSessionIds)
const expandedCategories = new Set(view.expandedCategories)
const expandedWorkspaces = new Set(view.expandedWorkspaces)
const descendants = indexSubagentDescendants(list.byId)
// Bucket workspaces by category, preserving host order inside each bucket.
// Bucket workspaces by display key. Seed with every effective category so
// manual groups render while empty; the uncategorized bucket is appended
// LAST (groups always sit above ungrouped projects).
const byCategory = new Map<string, WorkspaceView[]>()
const categorized = new Set<WorkspaceId>()
for (const category of config.categories) {
byCategory.set(category.name, [])
for (const { key } of effectiveCategories(config, manual)) {
byCategory.set(key, [])
}
byCategory.set(UNCATEGORIZED_KEY, [])
for (const workspace of workspaces) {
const category = classify(config.categories, workspace.path, workspace.title)
const key = category !== undefined ? category.name : UNCATEGORIZED_KEY
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
?? UNCATEGORIZED_KEY
if (!byCategory.has(key)) byCategory.set(key, [])
byCategory.get(key)!.push(workspace)
categorized.add(workspace.workspaceId)
}
const manualCategories = new Set(manual.categories)
const currentWorkspaceId = list.current === undefined
? undefined
: workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId
const nodes: CategoryNode[] = []
for (const [key, bucket] of byCategory) {
if (bucket.length === 0) continue
// Effective categories in display order (categoryOrder applied), then the
// uncategorized bucket pinned to the very bottom.
const orderedKeys = [
...effectiveCategories(config, manual).map(e => e.key),
UNCATEGORIZED_KEY,
]
for (const key of orderedKeys) {
const bucket = byCategory.get(key) ?? []
// Manual groups stay visible while empty; everything else hides when empty.
if (bucket.length === 0 && !manualCategories.has(key)) continue
const expanded = expandedCategories.has(key)
const ordered = orderedWorkspaceIds(manual, key, bucket.map(w => w.workspaceId as string))
const workspaceNodes: WorkspaceGroupNode[] = []
let containsCurrent = false
for (const workspace of bucket) {
for (const workspaceId of ordered) {
const workspace = bucket.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) continue
const sessions = workspaceSessions(list, workspace, archived, descendants)
const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId
@ -287,12 +305,15 @@ export function deriveSearchMatches(
* Build a three-level search tree containing ONLY the branches that hold a
* matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched
* session carries `matched: true` so rows render with the search-hit tint.
* Classification uses the same precedence as the idle tree (manual override →
* rules), so search shows the same grouping the user sees.
*
* @param list - sessions list snapshot.
* @param workspaces - real workspaces in stable Host order.
* @param config - sidecar grouping config.
* @param matchedIds - set of session ids that matched the query.
* @param archivedSessionIds - registry-global archive set.
* @param manual - runtime overlay (manual groups + overrides).
* @param snippetsBySession - optional content-match snippets keyed by session id.
* @returns categories in render order, pruned to matched branches only.
*/
@ -302,13 +323,15 @@ export function deriveSearchGroups(
config: GroupsConfig,
matchedIds: ReadonlySet<SessionId>,
archivedSessionIds: readonly SessionId[],
manual: ManualGroups,
snippetsBySession?: ReadonlyMap<SessionId, string>,
): CategoryNode[] {
const archived = new Set(archivedSessionIds)
const descendants = indexSubagentDescendants(list.byId)
const byCategory = new Map<string, WorkspaceGroupNode[]>()
for (const category of config.categories) byCategory.set(category.name, [])
for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])
byCategory.set(UNCATEGORIZED_KEY, [])
for (const workspace of workspaces) {
// Only sessions that matched the query and are visible in this folder.
@ -327,8 +350,8 @@ export function deriveSearchGroups(
}
if (nodes.length === 0) continue
const category = classify(config.categories, workspace.path, workspace.title)
const key = category !== undefined ? category.name : UNCATEGORIZED_KEY
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
?? UNCATEGORIZED_KEY
if (!byCategory.has(key)) byCategory.set(key, [])
byCategory.get(key)!.push({
workspaceId: workspace.workspaceId,
@ -343,8 +366,14 @@ export function deriveSearchGroups(
}
const categories: CategoryNode[] = []
for (const [key, workspaceNodes] of byCategory) {
if (workspaceNodes.length === 0) continue
// Same display order as the idle tree; the uncategorized bucket stays last.
const orderedKeys = [
...effectiveCategories(config, manual).map(e => e.key),
UNCATEGORIZED_KEY,
]
for (const key of orderedKeys) {
const workspaceNodes = byCategory.get(key)
if (workspaceNodes === undefined || workspaceNodes.length === 0) continue
categories.push({
key,
label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,

View File

@ -1,10 +1,23 @@
/**
* Pure classification logic: decides which category a workspace belongs to.
* Shared by the host half (validation) and the client half (tree derivation),
* so the rule semantics can never drift between the config surface and the
* rendered tree.
* Pure classification + ordering logic: decides which category a workspace
* belongs to and how categories/workspaces are ordered. Shared by the host
* half (validation) and the client half (tree derivation), so the semantics
* can never drift between the config surface and the rendered tree.
*
* Category identity: a category's STABLE origin is its YAML rule category
* name (or a manual-group name). Its DISPLAY key is what the tree renders and
* what assignments reference — for rule categories that is the rename
* override when present. Hidden rule categories are inert: workspaces that
* would match them fall into the uncategorized bucket.
*/
import { normalizePath, type GroupCategory, type GroupRule } from './types.ts'
import {
normalizePath,
UNCATEGORIZED_LABEL,
type GroupCategory,
type GroupRule,
type GroupsConfig,
type ManualGroups,
} from './types.ts'
/** One rule match against a workspace's path and title. */
function ruleMatches(rule: GroupRule, path: string, title: string): boolean {
@ -19,16 +32,176 @@ function ruleMatches(rule: GroupRule, path: string, title: string): boolean {
return false
}
/**
* Classify a workspace into its category.
* @param categories - configured categories, in render order.
* @param path - workspace canonical directory path.
* @param title - workspace display title.
* @returns the matching category, or undefined when no rule matches.
*/
/** Classify a workspace by rules only; hidden categories are inert. */
export function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined {
for (const category of categories) {
if (category.rules.some(rule => ruleMatches(rule, path, title))) return category
}
return undefined
}
/** Display name of a rule category: the rename override when present. */
export function ruleDisplayName(manual: ManualGroups | undefined, originalName: string): string {
return manual?.renamed?.[originalName] ?? originalName
}
/** Whether a rule category has been hidden by a UI delete. */
export function isHiddenRule(manual: ManualGroups | undefined, originalName: string): boolean {
return manual?.hidden?.includes(originalName) ?? false
}
/** Rule category display names, in YAML render order (hidden ones excluded). */
export function ruleDisplayNames(categories: readonly GroupCategory[], manual: ManualGroups | undefined): string[] {
const names: string[] = []
for (const category of categories) {
if (isHiddenRule(manual, category.name)) continue
names.push(ruleDisplayName(manual, category.name))
}
return names
}
/** Original YAML rule name whose display name equals `key` (undefined when none). */
export function originalRuleNameForDisplay(
categories: readonly GroupCategory[],
manual: ManualGroups | undefined,
key: string,
): string | undefined {
return categories.find(c => ruleDisplayName(manual, c.name) === key)?.name
}
/**
* Effective category entries in display order: rule categories (YAML order,
* hidden skipped, renamed applied) first, then manual-only groups in
* creation order — unless `manual.categoryOrder` overrides the sequence.
* The uncategorized bucket is never included (it always renders last).
*/
export interface EffectiveCategory {
/** Display key (what the tree renders and assignments reference). */
key: string
/** Origin: a YAML rule category or a manual group. */
source: 'rule' | 'manual'
}
export function effectiveCategories(
config: GroupsConfig,
manual: ManualGroups | undefined,
): EffectiveCategory[] {
const entries: EffectiveCategory[] = []
const seen = new Set<string>()
for (const category of config.categories) {
if (isHiddenRule(manual, category.name)) continue
const key = ruleDisplayName(manual, category.name)
if (seen.has(key)) continue
seen.add(key)
entries.push({ key, source: 'rule' })
}
for (const name of manual?.categories ?? []) {
if (seen.has(name)) continue
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
})
}
/** Display keys of all effective categories (uncategorized bucket excluded). */
export function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[] {
return effectiveCategories(config, manual).map(e => e.key)
}
/**
* Resolve the category key a workspace renders under. Precedence:
* manual override (`null` = force uncategorized) → rule classification
* (hidden rules inert) → uncategorized bucket (`undefined`).
*/
export function resolveCategory(
config: GroupsConfig,
manual: ManualGroups | undefined,
workspaceId: string,
path: string,
title: string,
): string | undefined {
const override = manual?.assignments[workspaceId]
if (override !== undefined) return override ?? undefined // null forces the uncategorized bucket
const matched = classify(config.categories, path, title)
if (matched === undefined) return undefined
if (isHiddenRule(manual, matched.name)) return undefined
return ruleDisplayName(manual, matched.name)
}
/** Whether a category key is a manual-only group (manageable via list). */
export function isManualOnlyCategory(
config: GroupsConfig,
manual: ManualGroups | undefined,
key: string,
): boolean {
return (manual?.categories.includes(key) ?? false) && !ruleDisplayNames(config.categories, manual).includes(key)
}
/**
* Names that may not be used for a new/renamed group: the reserved
* uncategorized label plus every current display key.
*/
export function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set<string> {
const taken = new Set<string>(displayCategoryKeys(config, manual))
taken.add(UNCATEGORIZED_LABEL)
return taken
}
/**
* Order a bucket of workspace ids: the stored per-category order first
* (filtered to actual members), then any remaining members in `fallback`
* (host) order. Deterministic; the renderer never re-sorts on its own.
*/
export function orderedWorkspaceIds(
manual: ManualGroups | undefined,
categoryKey: string,
members: readonly string[],
): string[] {
const stored = manual?.workspaceOrder?.[categoryKey]
if (stored === undefined || stored.length === 0) return [...members]
const memberSet = new Set(members)
const ordered: string[] = []
const seen = new Set<string>()
for (const id of stored) {
if (!memberSet.has(id) || seen.has(id)) continue
seen.add(id)
ordered.push(id)
}
for (const id of members) {
if (seen.has(id)) continue
ordered.push(id)
}
return ordered
}
/** Move `id` before `beforeId` (undefined = append) within an ordered list. */
export function moveBefore(list: readonly string[], id: string, beforeId: string | undefined): string[] {
const rest = list.filter(x => x !== id)
if (beforeId === undefined) return [...rest, id]
const index = rest.indexOf(beforeId)
if (index === -1) return [...rest, id]
rest.splice(index, 0, id)
return rest
}
/** Move `id` after `afterId` (undefined = append) within an ordered list. */
export function moveAfter(list: readonly string[], id: string, afterId: string | undefined): string[] {
const rest = list.filter(x => x !== id)
if (afterId === undefined) return [...rest, id]
const index = rest.indexOf(afterId)
if (index === -1) return [...rest, id]
rest.splice(index + 1, 0, id)
return rest
}

View File

@ -28,6 +28,62 @@ export interface GroupCategory {
export interface GroupsConfig {
/** Category folders, in render order. First match wins. */
categories: GroupCategory[]
/**
* Runtime grouping overlay (manual groups + per-workspace overrides).
* Optional: the YAML file itself never carries it — the host GET route
* merges it from `workspace-groups.manual.json`, and the browser PUT route
* replaces it whole.
*/
manual?: ManualGroups
}
/**
* Runtime-managed grouping overlay: groups created in the sidebar UI plus
* per-workspace category overrides and user-controlled ordering. Owned by the
* plugin (JSON sidecar, `$DSH_HOME/workspace-groups.manual.json`), never
* written back into the operator YAML.
*
* 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.
*/
export interface ManualGroups {
/**
* Manually created category folder names. These have no rules — they render
* even while empty (a new group appears before anything is dragged into
* it) and hold only workspaces assigned to them.
*/
categories: string[]
/**
* Per-workspace category override, keyed by workspace id. Value is a
* category display name (rule or manual), or `null` to force the workspace
* into the uncategorized bucket even when a rule would match. An absent
* key means "classify by rules".
*/
assignments: Record<string, string | null>
/**
* Display order of all category keys (rule display names + manual names).
* The uncategorized bucket is never listed — it always renders last.
* Absent = rule categories first (YAML order), manual groups appended in
* creation order.
*/
categoryOrder?: string[]
/**
* Per-category ordered workspace ids (user drag-reorder within a group).
* Keyed by category display name; absent key = host registration order.
*/
workspaceOrder?: Record<string, string[]>
/**
* Rule category rename overrides: original YAML rule category name →
* display name (UI rename of a rule group). Rules still classify by the
* original name; only the rendered label/keys change.
*/
renamed?: Record<string, string>
/**
* Rule category original names hidden by a UI delete. Hidden rules are
* inert: workspaces matching them fall into the uncategorized bucket.
*/
hidden?: string[]
}
/** The label of the fallback bucket for unmatched workspaces. */

228
src/host-manual.ts Normal file
View File

@ -0,0 +1,228 @@
/**
* Runtime grouping overlay for dsh-workspace-groups: manual groups created in
* the sidebar UI and per-workspace category overrides. Stored in a plugin-
* owned JSON sidecar (`$DSH_HOME/workspace-groups.manual.json`), separate from
* the operator YAML — the YAML stays the rule source, this file only records
* runtime decisions, and writes are atomic (temp file + fsync + rename).
*
* The browser PUT route writes the whole overlay (idempotent, last write
* wins); reads tolerate hand-edited content (parse-only) while the write
* boundary cross-validates against the current rule categories.
*/
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 { UNCATEGORIZED_LABEL, type ManualGroups } from './core/types.ts'
/** Default overlay location: `$DSH_HOME/workspace-groups.manual.json`. */
export function defaultManualPath(): string {
const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== ''
? process.env.DSH_HOME
: resolve(homedir(), '.dsh')
return resolve(home, 'workspace-groups.manual.json')
}
/**
* Parse + shape-validate a raw overlay document into a ManualGroups.
* Validates types only — category references are checked against the rule set
* at the write boundary (validateManualGroups), because reads must tolerate
* files written while the rule set was different.
* @param raw - parsed JSON value.
* @returns the normalized overlay.
* @throws when the shape is malformed (non-mapping, bad names, duplicates,
* the reserved uncategorized label, bad assignment/order values).
*/
export function parseManualGroups(raw: unknown): ManualGroups {
if (raw === undefined || raw === null) return { categories: [], assignments: {} }
if (typeof raw !== 'object' || Array.isArray(raw)) {
throw new Error('workspace-groups.manual.json: top-level value must be a mapping')
}
const source = raw as Record<string, unknown>
const categories: string[] = []
if (source.categories !== undefined) {
if (!Array.isArray(source.categories)) {
throw new Error('workspace-groups.manual.json: categories must be a list')
}
const seen = new Set<string>()
for (const entry of source.categories) {
if (typeof entry !== 'string' || entry.trim() === '') {
throw new Error('workspace-groups.manual.json: each manual category must be a non-empty string')
}
const name = entry.trim()
if (name === UNCATEGORIZED_LABEL) {
throw new Error(`workspace-groups.manual.json: manual category name "${name}" is reserved`)
}
if (seen.has(name)) {
throw new Error(`workspace-groups.manual.json: duplicate manual category "${name}"`)
}
seen.add(name)
categories.push(name)
}
}
const assignments: Record<string, string | null> = {}
if (source.assignments !== undefined) {
if (typeof source.assignments !== 'object' || source.assignments === null || Array.isArray(source.assignments)) {
throw new Error('workspace-groups.manual.json: assignments must be a mapping')
}
for (const [workspaceId, category] of Object.entries(source.assignments)) {
if (workspaceId.trim() === '') {
throw new Error('workspace-groups.manual.json: assignment keys must be non-empty')
}
if (category === null) {
assignments[workspaceId] = null // force uncategorized
continue
}
if (typeof category !== 'string' || category.trim() === '') {
throw new Error(`workspace-groups.manual.json: assignment "${workspaceId}" must be a category name or null`)
}
assignments[workspaceId] = category.trim()
}
}
const manual: ManualGroups = { categories, assignments }
if (source.categoryOrder !== undefined) {
manual.categoryOrder = parseStringList(source.categoryOrder, 'categoryOrder', true)
}
if (source.hidden !== undefined) {
manual.hidden = parseStringList(source.hidden, 'hidden', true)
}
if (source.renamed !== undefined) {
if (typeof source.renamed !== 'object' || source.renamed === null || Array.isArray(source.renamed)) {
throw new Error('workspace-groups.manual.json: renamed must be a mapping')
}
const renamed: Record<string, string> = {}
for (const [original, display] of Object.entries(source.renamed)) {
if (original.trim() === '') throw new Error('workspace-groups.manual.json: renamed keys must be non-empty')
if (typeof display !== 'string' || display.trim() === '') {
throw new Error(`workspace-groups.manual.json: renamed "${original}" must be a non-empty string`)
}
renamed[original] = display.trim()
}
manual.renamed = renamed
}
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')
}
const workspaceOrder: Record<string, string[]> = {}
for (const [categoryKey, ids] of Object.entries(source.workspaceOrder)) {
if (categoryKey.trim() === '') {
throw new Error('workspace-groups.manual.json: workspaceOrder keys must be non-empty')
}
workspaceOrder[categoryKey] = parseStringList(ids, `workspaceOrder["${categoryKey}"]`, true)
}
manual.workspaceOrder = workspaceOrder
}
return manual
}
/** Parse a list of non-empty strings, optionally de-duplicated. */
function parseStringList(value: unknown, field: string, unique: boolean): string[] {
if (!Array.isArray(value)) {
throw new Error(`workspace-groups.manual.json: ${field} must be a list`)
}
const seen = new Set<string>()
const result: string[] = []
for (const entry of value) {
if (typeof entry !== 'string' || entry.trim() === '') {
throw new Error(`workspace-groups.manual.json: ${field} entries must be non-empty strings`)
}
const trimmed = entry.trim()
if (unique && seen.has(trimmed)) {
throw new Error(`workspace-groups.manual.json: ${field} has duplicate entry "${trimmed}"`)
}
seen.add(trimmed)
result.push(trimmed)
}
return result
}
/**
* Cross-validate a parsed overlay against the current rule categories
* (write boundary only). Every assignment value must be `null`, a rule
* display name, a manual category name, or the uncategorized label; order
* keys must reference existing categories; renames/hides must reference
* actual rule categories.
* @param manual - parsed overlay.
* @param ruleCategoryNames - current YAML rule category original names.
* @throws when the overlay references categories that do not exist.
*/
export function validateManualGroups(manual: ManualGroups, ruleCategoryNames: readonly string[]): void {
const ruleNames = new Set(ruleCategoryNames)
const allowed = new Set<string>(ruleCategoryNames.map(name => ruleDisplayName(manual, name)))
for (const name of manual.categories) allowed.add(name)
allowed.add(UNCATEGORIZED_LABEL)
for (const [workspaceId, category] of Object.entries(manual.assignments)) {
if (category === null) continue
if (!allowed.has(category)) {
throw new Error(`workspace-groups.manual.json: assignment "${workspaceId}" references unknown category "${category}"`)
}
}
for (const key of manual.categoryOrder ?? []) {
if (!allowed.has(key) || key === UNCATEGORIZED_LABEL) {
throw new Error(`workspace-groups.manual.json: categoryOrder references unknown category "${key}"`)
}
}
for (const key of Object.keys(manual.workspaceOrder ?? {})) {
if (!allowed.has(key) || key === UNCATEGORIZED_LABEL) {
throw new Error(`workspace-groups.manual.json: workspaceOrder references unknown category "${key}"`)
}
}
for (const original of Object.keys(manual.renamed ?? {})) {
if (!ruleNames.has(original)) {
throw new Error(`workspace-groups.manual.json: renamed references unknown rule category "${original}"`)
}
}
for (const original of manual.hidden ?? []) {
if (!ruleNames.has(original)) {
throw new Error(`workspace-groups.manual.json: hidden references unknown rule category "${original}"`)
}
}
}
/** Read + parse the overlay file. A missing file yields an empty overlay. */
export async function readManualGroups(path: string): Promise<ManualGroups> {
let text: string
try {
text = await readFile(path, 'utf8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { categories: [], assignments: {} }
throw error
}
return parseManualGroups(JSON.parse(text))
}
/**
* Atomically replace the overlay file: write a same-directory temp file,
* fsync it, then rename over the target. A crash never leaves a torn JSON at
* the real path (readers see either the old or the new file).
* @param path - target file path.
* @param manual - overlay to persist.
*/
export async function writeManualGroups(path: string, manual: ManualGroups): Promise<void> {
const json = `${JSON.stringify(manual, null, 2)}\n`
await mkdir(dirname(path), { recursive: true })
const tmp = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
const handle = await open(tmp, 'w')
try {
await handle.writeFile(json, 'utf8')
await handle.sync()
} catch (error) {
await handle.close().catch(() => {})
await unlink(tmp).catch(() => {})
throw error
}
await handle.close()
try {
await rename(tmp, path)
} catch (error) {
await unlink(tmp).catch(() => {})
throw error
}
}

View File

@ -1,17 +1,27 @@
/**
* dsh-workspace-groups host half: serves the sidecar grouping config to the
* browser half over a single fenced GET route (`/workspace-groups/config`).
* browser half and persists the runtime grouping overlay.
*
* The route is a read-only snapshot endpoint: the browser half fetches it on
* load (and refetches on demand), the classification rules stay operator-
* editable in the YAML file, and no core workspace.json / session storage is
* touched. Static content — the config is small and operator-owned — uses
* `Cache-Control: no-cache` so a page reload revalidates against the file
* without the browser serving a stale grouping.
* Routes:
* - `GET /workspace-groups/config` — snapshot of the YAML rule categories
* merged with the runtime manual overlay (groups + assignments). Read-only
* for the rules; the overlay is attached so one fetch boots the browser.
* - `PUT /workspace-groups/manual` — replace the whole manual overlay
* (manual groups + per-workspace overrides). Validated against the current
* rule categories, written atomically to the plugin-owned JSON sidecar.
*
* Core workspace.json / session storage is never touched.
*/
import type { ServerResponse } from 'node:http'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { GroupsContext } from './context-types.ts'
import { defaultConfigPath, readGroupsConfig, type GroupsConfig } from './host-config.ts'
import { defaultConfigPath, readGroupsConfig } from './host-config.ts'
import {
defaultManualPath,
parseManualGroups,
readManualGroups,
validateManualGroups,
writeManualGroups,
} from './host-manual.ts'
/** Plugin identity for cordis.yml rows. */
export const name = 'dsh-workspace-groups'
@ -19,15 +29,41 @@ export const name = 'dsh-workspace-groups'
/** Services required before mounting: the webserver route. */
export const inject = ['webServer']
/** Cap on the PUT body: the overlay is tiny; anything bigger is a client bug. */
const MAX_MANUAL_BODY_BYTES = 64 * 1024
/** Error with an HTTP status, mapped to a plain-text 4xx/5xx response. */
class HttpError extends Error {
constructor(readonly status: number, message: string) {
super(message)
}
}
/** Write a plain-text error response with the given status. */
function writeError(res: ServerResponse, status: number, message: string): void {
res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' })
res.end(message)
}
/** Plugin body: mount the config route. */
/** Collect the request body as UTF-8 text, rejecting oversized bodies. */
async function readBody(req: IncomingMessage, limit: number): Promise<string> {
const chunks: Buffer[] = []
let size = 0
for await (const chunk of req) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
size += buffer.length
if (size > limit) throw new HttpError(413, 'request body too large')
chunks.push(buffer)
}
if (chunks.length === 0) throw new HttpError(400, 'empty request body')
return Buffer.concat(chunks).toString('utf8')
}
/** Plugin body: mount the config snapshot route and the overlay write route. */
export function apply(ctx: GroupsContext): void {
const configPath = defaultConfigPath()
const manualPath = defaultManualPath()
ctx.effect(() => ctx.webServer.register({
kind: 'exact',
path: '/workspace-groups/config',
@ -36,14 +72,18 @@ export function apply(ctx: GroupsContext): void {
writeError(res, 405, 'method not allowed')
return
}
let config: GroupsConfig
let config
let manual
try {
config = await readGroupsConfig(configPath)
;[config, manual] = await Promise.all([
readGroupsConfig(configPath),
readManualGroups(manualPath),
])
} catch (error) {
writeError(res, 500, `workspace-groups: failed to read config: ${error instanceof Error ? error.message : String(error)}`)
return
}
const body = JSON.stringify(config)
const body = JSON.stringify({ ...config, manual })
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
@ -52,4 +92,47 @@ export function apply(ctx: GroupsContext): void {
res.end(req.method === 'HEAD' ? undefined : body)
},
}), 'dsh-workspace-groups: /workspace-groups/config route')
ctx.effect(() => ctx.webServer.register({
kind: 'exact',
path: '/workspace-groups/manual',
handler: async (req, res) => {
if (req.method !== 'PUT') {
writeError(res, 405, 'method not allowed')
return
}
let raw: unknown
try {
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
} catch (error) {
const status = error instanceof HttpError ? error.status : 400
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
let manual
try {
manual = parseManualGroups(raw)
// The write boundary knows the current rule set; reject assignments
// into categories that exist nowhere (catches stale client state).
const ruleConfig = (await readGroupsConfig(configPath)).categories
validateManualGroups(manual, ruleConfig.map(category => category.name))
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
try {
await writeManualGroups(manualPath, manual)
} catch (error) {
writeError(res, 500, `workspace-groups: failed to write manual overlay: ${error instanceof Error ? error.message : String(error)}`)
return
}
const body = JSON.stringify({ ok: true })
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(body),
})
res.end(body)
},
}), 'dsh-workspace-groups: /workspace-groups/manual route')
}

View File

@ -1,11 +1,23 @@
/**
* Pure-logic tests: classification rules (the matcher) and config parsing.
* Pure-logic tests: classification rules (the matcher v2: display names,
* ordering, force-uncategorized) and config parsing.
* These are the plugin's business rules — no DOM, no cordis runtime.
*/
import { describe, expect, it } from 'vitest'
import { classify } from '../src/core/matcher.ts'
import {
displayCategoryKeys,
effectiveCategories,
isManualOnlyCategory,
moveAfter,
moveBefore,
orderedWorkspaceIds,
originalRuleNameForDisplay,
resolveCategory,
ruleDisplayName,
takenCategoryNames,
} from '../src/core/matcher.ts'
import { parseGroupsConfig } from '../src/host-config.ts'
import type { GroupsConfig } from '../src/core/types.ts'
import { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../src/core/types.ts'
const CONFIG: GroupsConfig = {
categories: [
@ -25,18 +37,15 @@ const CONFIG: GroupsConfig = {
describe('classify', () => {
it('matches by path prefix', () => {
const category = classify(CONFIG.categories, '/Users/zcol/Project/SkillsManagePlugins', 'SkillsManagePlugins')
expect(category?.name).toBe('DSH 插件')
expect(resolveCategory(CONFIG, undefined, 'ws', '/Users/zcol/Project/SkillsManagePlugins', 'SkillsManagePlugins')).toBe('DSH 插件')
})
it('matches by name substring', () => {
const category = classify(CONFIG.categories, '/Users/zcol/Project/DeepSeek峰谷小组件', 'DeepSeek峰谷小组件')
expect(category?.name).toBe('DSH 插件')
expect(resolveCategory(CONFIG, undefined, 'ws', '/Users/zcol/Project/DeepSeek峰谷小组件', 'DeepSeek峰谷小组件')).toBe('DSH 插件')
})
it('matches by basename substring', () => {
const category = classify(CONFIG.categories, '/Users/zcol/Project/SomeDocs', 'SomeDocs')
expect(category?.name).toBe('文档')
expect(resolveCategory(CONFIG, undefined, 'ws', '/Users/zcol/Project/SomeDocs', 'SomeDocs')).toBe('文档')
})
it('first match wins across categories', () => {
@ -46,18 +55,131 @@ describe('classify', () => {
{ name: 'B', rules: [{ nameContains: 'common' }] },
],
}
const category = classify(config.categories, '/p/x', 'common-project')
expect(category?.name).toBe('A')
expect(resolveCategory(config, undefined, 'ws', '/p/x', 'common-project')).toBe('A')
})
it('returns undefined when nothing matches', () => {
const category = classify(CONFIG.categories, '/tmp/random', 'Random')
expect(category).toBeUndefined()
expect(resolveCategory(CONFIG, undefined, 'ws', '/tmp/random', 'Random')).toBeUndefined()
})
})
describe('resolveCategory (v2 overlay semantics)', () => {
it('a manual override wins over rules', () => {
const manual: ManualGroups = { categories: ['临时'], assignments: { 'ws-manual': '临时' } }
expect(resolveCategory(CONFIG, manual, 'ws-manual', '/Users/zcol/Project/SomeDocs', 'SomeDocs')).toBe('临时')
})
it('path prefix matching strips trailing slashes', () => {
const category = classify(CONFIG.categories, '/Users/zcol/Project/SkillsManagePlugins/sub', 'Sub')
expect(category?.name).toBe('DSH 插件')
it('a null override forces the uncategorized bucket even when a rule matches', () => {
const manual: ManualGroups = { categories: [], assignments: { 'ws-null': null } }
expect(resolveCategory(CONFIG, manual, 'ws-null', '/Users/zcol/Project/SkillsManagePlugins', 'SkillsManagePlugins')).toBeUndefined()
})
it('falls back to rules without an override', () => {
const manual: ManualGroups = { categories: ['临时'], assignments: { 'ws-other': '临时' } }
expect(resolveCategory(CONFIG, manual, 'ws-x', '/Users/zcol/Project/SkillsManagePlugins', 'SkillsManagePlugins')).toBe('DSH 插件')
})
it('a renamed rule category resolves to its display name', () => {
const manual: ManualGroups = { categories: [], assignments: {}, renamed: { 'DSH 插件': '插件集' } }
expect(ruleDisplayName(manual, 'DSH 插件')).toBe('插件集')
expect(resolveCategory(CONFIG, manual, 'ws-x', '/Users/zcol/Project/SkillsManagePlugins', 'SkillsManagePlugins')).toBe('插件集')
expect(originalRuleNameForDisplay(CONFIG.categories, manual, '插件集')).toBe('DSH 插件')
})
it('a hidden rule category is inert — matches fall to uncategorized', () => {
const manual: ManualGroups = { categories: [], assignments: {}, hidden: ['DSH 插件'] }
expect(resolveCategory(CONFIG, manual, 'ws-x', '/Users/zcol/Project/SkillsManagePlugins', 'SkillsManagePlugins')).toBeUndefined()
})
})
describe('displayCategoryKeys / effectiveCategories', () => {
it('rule categories first, manual ones appended', () => {
const manual: ManualGroups = { categories: ['临时', '归档'], assignments: {} }
expect(displayCategoryKeys(CONFIG, manual)).toEqual(['DSH 插件', '文档', '临时', '归档'])
})
it('categoryOrder overrides the sequence; unknown entries keep default order', () => {
const manual: ManualGroups = {
categories: ['临时'],
assignments: {},
categoryOrder: ['临时', '文档', 'DSH 插件'],
}
expect(displayCategoryKeys(CONFIG, manual)).toEqual(['临时', '文档', 'DSH 插件'])
})
it('hidden rules drop out; renamed rules appear under the new name', () => {
const manual: ManualGroups = {
categories: [],
assignments: {},
hidden: ['文档'],
renamed: { 'DSH 插件': '插件集' },
}
const keys = displayCategoryKeys(CONFIG, manual)
expect(keys).toEqual(['插件集'])
expect(effectiveCategories(CONFIG, manual)[0]).toEqual({ key: '插件集', source: 'rule' })
})
it('uncategorized is never part of the key list', () => {
expect(displayCategoryKeys(CONFIG, undefined).includes(UNCATEGORIZED_LABEL)).toBe(false)
})
})
describe('isManualOnlyCategory', () => {
const manual: ManualGroups = { categories: ['临时'], assignments: {} }
it('true for a manual-only category', () => {
expect(isManualOnlyCategory(CONFIG, manual, '临时')).toBe(true)
})
it('false for a rule category', () => {
expect(isManualOnlyCategory(CONFIG, manual, 'DSH 插件')).toBe(false)
})
it('false for an unknown name', () => {
expect(isManualOnlyCategory(CONFIG, manual, '不存在')).toBe(false)
})
it('false when the overlay is absent', () => {
expect(isManualOnlyCategory(CONFIG, undefined, '临时')).toBe(false)
})
})
describe('takenCategoryNames', () => {
it('covers rule display names, manual groups and the reserved label', () => {
const manual: ManualGroups = {
categories: ['临时'],
assignments: {},
renamed: { 'DSH 插件': '插件集' },
}
const taken = takenCategoryNames(CONFIG, manual)
expect(taken.has('插件集')).toBe(true)
expect(taken.has('文档')).toBe(true)
expect(taken.has('临时')).toBe(true)
expect(taken.has(UNCATEGORIZED_LABEL)).toBe(true)
expect(taken.has('新分组')).toBe(false)
})
})
describe('orderedWorkspaceIds / moveBefore / moveAfter', () => {
it('stored order wins, missing members appended in fallback order', () => {
const manual: ManualGroups = { categories: [], assignments: {}, workspaceOrder: { 'DSH 插件': ['b', 'a'] } }
expect(orderedWorkspaceIds(manual, 'DSH 插件', ['a', 'b', 'c'])).toEqual(['b', 'a', 'c'])
})
it('falls back to host order without a stored order', () => {
expect(orderedWorkspaceIds(undefined, 'DSH 插件', ['a', 'b'])).toEqual(['a', 'b'])
})
it('moveBefore moves an id before a target (or appends)', () => {
expect(moveBefore(['a', 'b', 'c'], 'c', 'a')).toEqual(['c', 'a', 'b'])
expect(moveBefore(['a', 'b', 'c'], 'a', undefined)).toEqual(['b', 'c', 'a'])
expect(moveBefore(['a', 'b', 'c'], 'c', 'zzz')).toEqual(['a', 'b', 'c'])
})
it('moveAfter moves an id after a target (or appends)', () => {
expect(moveAfter(['a', 'b', 'c'], 'a', 'c')).toEqual(['b', 'c', 'a'])
expect(moveAfter(['a', 'b', 'c'], 'c', undefined)).toEqual(['a', 'b', 'c'])
expect(moveAfter(['a', 'b', 'c'], 'a', 'zzz')).toEqual(['b', 'c', 'a'])
})
})

165
tests/manual.test.ts Normal file
View File

@ -0,0 +1,165 @@
/**
* Manual-overlay tests: shape validation, cross-validation against rule
* categories, and the atomic file round-trip (temp dir, no host needed).
*/
import { describe, expect, it } from 'vitest'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import {
parseManualGroups,
readManualGroups,
validateManualGroups,
writeManualGroups,
} from '../src/host-manual.ts'
import { UNCATEGORIZED_LABEL, type ManualGroups } from '../src/core/types.ts'
const RULE_NAMES = ['DSH 插件', '个人项目']
describe('parseManualGroups', () => {
it('parses a valid overlay', () => {
const parsed = parseManualGroups({
categories: ['临时'],
assignments: { 'ws-1': '临时', 'ws-2': 'DSH 插件' },
})
expect(parsed).toEqual({
categories: ['临时'],
assignments: { 'ws-1': '临时', 'ws-2': 'DSH 插件' },
})
})
it('empty / undefined input yields an empty overlay', () => {
expect(parseManualGroups(undefined)).toEqual({ categories: [], assignments: {} })
expect(parseManualGroups({})).toEqual({ categories: [], assignments: {} })
})
it('rejects a non-mapping top level', () => {
expect(() => parseManualGroups([])).toThrow(/mapping/)
expect(() => parseManualGroups('nope')).toThrow(/mapping/)
})
it('rejects non-string / empty category names and trims them', () => {
expect(() => parseManualGroups({ categories: [42] })).toThrow(/non-empty string/)
expect(() => parseManualGroups({ categories: [''] })).toThrow(/non-empty string/)
expect(parseManualGroups({ categories: [' 临时 '] }).categories).toEqual(['临时'])
})
it('rejects the reserved uncategorized label as a manual category', () => {
expect(() => parseManualGroups({ categories: [UNCATEGORIZED_LABEL] })).toThrow(/reserved/)
})
it('rejects duplicate category names', () => {
expect(() => parseManualGroups({ categories: ['临时', '临时'] })).toThrow(/duplicate/)
})
it('rejects a non-mapping assignments value', () => {
expect(() => parseManualGroups({ assignments: [] })).toThrow(/assignments/)
})
it('rejects empty assignment keys and non-string assignment values', () => {
expect(() => parseManualGroups({ assignments: { '': '临时' } })).toThrow(/non-empty/)
expect(() => parseManualGroups({ assignments: { 'ws-1': 42 } })).toThrow(/category name/)
})
it('accepts null assignment values (force uncategorized)', () => {
const parsed = parseManualGroups({ assignments: { 'ws-1': null } })
expect(parsed.assignments['ws-1']).toBeNull()
})
it('parses the v2 ordering/rename/hidden fields', () => {
const parsed = parseManualGroups({
categories: ['临时'],
assignments: { 'ws-1': '临时' },
categoryOrder: ['临时', 'DSH 插件'],
workspaceOrder: { '临时': ['ws-1'] },
renamed: { 'DSH 插件': '插件集' },
hidden: ['文档'],
})
expect(parsed.categoryOrder).toEqual(['临时', 'DSH 插件'])
expect(parsed.workspaceOrder).toEqual({ '临时': ['ws-1'] })
expect(parsed.renamed).toEqual({ 'DSH 插件': '插件集' })
expect(parsed.hidden).toEqual(['文档'])
})
it('rejects duplicate categoryOrder / hidden entries', () => {
expect(() => parseManualGroups({ categoryOrder: ['A', 'A'] })).toThrow(/duplicate/)
expect(() => parseManualGroups({ hidden: ['A', 'A'] })).toThrow(/duplicate/)
})
it('rejects non-string renamed values', () => {
expect(() => parseManualGroups({ renamed: { 'DSH 插件': 42 } })).toThrow(/non-empty string/)
})
})
describe('validateManualGroups v2 (write boundary)', () => {
it('accepts null assignments and renamed-display targets', () => {
const manual: ManualGroups = {
categories: ['临时'],
assignments: { 'ws-1': null, 'ws-2': '插件集' },
renamed: { 'DSH 插件': '插件集' },
}
expect(() => validateManualGroups(manual, RULE_NAMES)).not.toThrow()
})
it('rejects renamed keys that are not rule categories', () => {
const manual: ManualGroups = { categories: [], assignments: {}, renamed: { '幽灵规则': 'X' } }
expect(() => validateManualGroups(manual, RULE_NAMES)).toThrow(/renamed/)
})
it('rejects hidden entries that are not rule categories', () => {
const manual: ManualGroups = { categories: [], assignments: {}, hidden: ['幽灵规则'] }
expect(() => validateManualGroups(manual, RULE_NAMES)).toThrow(/hidden/)
})
it('rejects categoryOrder / workspaceOrder keys that exist nowhere', () => {
const manual1: ManualGroups = { categories: [], assignments: {}, categoryOrder: ['幽灵'] }
expect(() => validateManualGroups(manual1, RULE_NAMES)).toThrow(/categoryOrder/)
const manual2: ManualGroups = { categories: [], assignments: {}, workspaceOrder: { '幽灵': [] } }
expect(() => validateManualGroups(manual2, RULE_NAMES)).toThrow(/workspaceOrder/)
})
})
describe('validateManualGroups (write boundary)', () => {
it('accepts assignments into rule, manual, and uncategorized categories', () => {
const manual: ManualGroups = {
categories: ['临时'],
assignments: { 'ws-1': '临时', 'ws-2': 'DSH 插件', 'ws-3': UNCATEGORIZED_LABEL },
}
expect(() => validateManualGroups(manual, RULE_NAMES)).not.toThrow()
})
it('rejects an assignment into a category that exists nowhere', () => {
const manual: ManualGroups = { categories: [], assignments: { 'ws-1': '幽灵分组' } }
expect(() => validateManualGroups(manual, RULE_NAMES)).toThrow(/unknown category/)
})
})
describe('manual file round-trip', () => {
it('a missing file yields an empty overlay', async () => {
const dir = await mkdtemp(join(tmpdir(), 'wg-manual-'))
try {
expect(await readManualGroups(join(dir, 'missing.json'))).toEqual({ categories: [], assignments: {} })
} finally {
await rm(dir, { recursive: true, force: true })
}
})
it('write then read returns the same overlay (atomic publish)', async () => {
const dir = await mkdtemp(join(tmpdir(), 'wg-manual-'))
const path = join(dir, 'workspace-groups.manual.json')
try {
const overlay: ManualGroups = {
categories: ['临时'],
assignments: { 'ws-1': '临时', 'ws-2': 'DSH 插件' },
}
await writeManualGroups(path, overlay)
expect(await readManualGroups(path)).toEqual(overlay)
// The persisted file is valid JSON with a trailing newline.
const text = await readFile(path, 'utf8')
expect(JSON.parse(text)).toEqual(overlay)
expect(text.endsWith('\n')).toBe(true)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
})

163
tests/tree.test.ts Normal file
View File

@ -0,0 +1,163 @@
/**
* Tree-derivation tests: the renderer's data-shaping contract — manual
* overrides win over rules, manual groups render while empty, rule buckets
* hide while empty, and the uncategorized bucket collects the rest.
* 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.
*/
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 } from '../src/client/tree.ts'
import { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../src/core/types.ts'
const CONFIG: GroupsConfig = {
categories: [
{ name: 'DSH 插件', rules: [{ nameContains: '插件' }] },
{ name: '文档', rules: [{ basenameContains: 'docs' }] },
],
}
function workspace(id: string, path: string, title: string, sessionIds: string[] = []): WorkspaceView {
return { workspaceId: id, path, title, createdAt: '2026-01-01T00:00:00.000Z', sessionIds } as unknown as WorkspaceView
}
function session(id: string, title: string): SessionSummary {
return {
id,
origin: 'user',
blank: false,
displayTitle: title,
running: false,
completed: false,
updatedAt: 1_700_000_000_000,
cwd: '/Users/zcol/Project/x',
} as unknown as SessionSummary
}
function listState(workspaces: WorkspaceView[], current?: string): SessionListState {
const byId: Record<string, SessionSummary> = {}
for (const ws of workspaces) {
for (const id of ws.sessionIds) byId[id] = session(id, `会话-${id}`)
}
return {
ids: Object.keys(byId),
byId,
current,
phase: 'ready',
subagentsByParent: {},
} as unknown as SessionListState
}
const VIEW = { expandedCategories: [], expandedWorkspaces: [] }
describe('deriveGroups with the manual overlay', () => {
const workspaces = [
workspace('ws-a', '/Users/zcol/Project/SomePlugin', 'DSH插件Demo'),
workspace('ws-b', '/Users/zcol/Project/MyDocs', 'MyDocs'),
workspace('ws-c', '/tmp/random', 'Random'),
]
it('groups by rules without an overlay', () => {
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, { categories: [], assignments: {} })
const labels = groups.map(g => g.label)
expect(labels).toEqual(['DSH 插件', '文档', UNCATEGORIZED_LABEL])
expect(groups[0]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a'])
expect(groups[1]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-b'])
expect(groups[2]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-c'])
})
it('a manual override moves a workspace into a manual group', () => {
const manual: ManualGroups = { categories: ['临时'], assignments: { 'ws-a': '临时' } }
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
const byLabel = new Map(groups.map(g => [g.label, g]))
expect(byLabel.get('临时')?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a'])
// ws-a left the rule bucket; with nothing left, the empty rule bucket hides.
expect(byLabel.has('DSH 插件')).toBe(false)
expect(byLabel.get('文档')?.workspaces.map(w => w.workspaceId)).toEqual(['ws-b'])
})
it('an empty manual group still renders (a new group appears before any drop)', () => {
const manual: ManualGroups = { categories: ['临时'], assignments: {} }
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
const byLabel = new Map(groups.map(g => [g.label, g]))
expect(byLabel.has('临时')).toBe(true)
expect(byLabel.get('临时')?.workspaces).toEqual([])
})
it('an empty rule bucket stays hidden', () => {
const manual: ManualGroups = { categories: [], assignments: {} }
const groups = deriveGroups(listState([]), [], [], CONFIG, VIEW, manual)
expect(groups).toEqual([])
})
it('drops into the uncategorized bucket are represented by absent overrides', () => {
// ws-a overridden to 临时; override removed → rule classification applies again.
const withOverride: ManualGroups = { categories: ['临时'], assignments: { 'ws-a': '临时' } }
const moved = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, withOverride)
expect(moved.find(g => g.label === '临时')?.workspaces).toHaveLength(1)
const reverted: ManualGroups = { categories: ['临时'], assignments: {} }
const back = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, reverted)
expect(back.find(g => g.label === '临时')?.workspaces).toHaveLength(0)
expect(back.find(g => g.label === 'DSH 插件')?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a'])
})
it('a null override forces the uncategorized bucket (rule match ignored)', () => {
const manual: ManualGroups = { categories: [], assignments: { 'ws-a': null } }
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
const byLabel = new Map(groups.map(g => [g.label, g]))
// ws-a forced to uncategorized; ws-c matches no rule and sits there too.
expect(byLabel.get(UNCATEGORIZED_LABEL)?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a', 'ws-c'])
expect(byLabel.has('DSH 插件')).toBe(false)
})
it('stored workspace order wins inside a bucket', () => {
const manual: ManualGroups = {
categories: [],
assignments: {},
workspaceOrder: { 'DSH 插件': ['ws-a2', 'ws-a1'] },
}
const ws = [
workspace('ws-a1', '/Users/zcol/Project/AA', '插件A1'),
workspace('ws-a2', '/Users/zcol/Project/BB', '插件A2'),
]
const groups = deriveGroups(listState(ws), ws, [], CONFIG, VIEW, manual)
expect(groups.find(g => g.label === 'DSH 插件')?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a2', 'ws-a1'])
})
it('the uncategorized bucket is always the last section', () => {
const manual: ManualGroups = {
categories: ['临时'],
assignments: { 'ws-b': '临时', 'ws-c': null },
categoryOrder: ['临时'],
}
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
expect(groups[groups.length - 1]?.label).toBe(UNCATEGORIZED_LABEL)
// ws-c (forced uncategorized) and any rule-less workspaces sit at the bottom.
expect(groups[groups.length - 1]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-c'])
})
it('a renamed rule category renders under the new name', () => {
const manual: ManualGroups = { categories: [], assignments: {}, renamed: { 'DSH 插件': '插件集' } }
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
const byLabel = new Map(groups.map(g => [g.label, g]))
expect(byLabel.has('插件集')).toBe(true)
expect(byLabel.get('插件集')?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a'])
expect(byLabel.has('DSH 插件')).toBe(false)
})
it('a hidden rule category is inert — its members fall to uncategorized', () => {
const manual: ManualGroups = { categories: [], assignments: {}, hidden: ['DSH 插件'] }
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
const byLabel = new Map(groups.map(g => [g.label, g]))
expect(byLabel.get(UNCATEGORIZED_LABEL)?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a', 'ws-c'])
})
})